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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlinx-coroutines-core/js/src/JSDispatcher.kt
|
hltj
| 151,721,407
| false
| null |
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.coroutines.internal.*
import org.w3c.dom.*
import kotlin.coroutines.*
import kotlin.js.Promise
private const val MAX_DELAY = Int.MAX_VALUE.toLong()
private fun delayToInt(timeMillis: Long): Int =
timeMillis.coerceIn(0, MAX_DELAY).toInt()
internal sealed class SetTimeoutBasedDispatcher: CoroutineDispatcher(), Delay {
inner class ScheduledMessageQueue : MessageQueue() {
internal val processQueue: dynamic = { process() }
override fun schedule() {
scheduleQueueProcessing()
}
override fun reschedule() {
setTimeout(processQueue, 0)
}
}
internal val messageQueue = ScheduledMessageQueue()
abstract fun scheduleQueueProcessing()
override fun dispatch(context: CoroutineContext, block: Runnable) {
messageQueue.enqueue(block)
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable): DisposableHandle {
val handle = setTimeout({ block.run() }, delayToInt(timeMillis))
return ClearTimeout(handle)
}
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
val handle = setTimeout({ with(continuation) { resumeUndispatched(Unit) } }, delayToInt(timeMillis))
// Actually on cancellation, but clearTimeout is idempotent
continuation.invokeOnCancellation(handler = ClearTimeout(handle).asHandler)
}
}
internal object NodeDispatcher : SetTimeoutBasedDispatcher() {
override fun scheduleQueueProcessing() {
process.nextTick(messageQueue.processQueue)
}
}
internal object SetTimeoutDispatcher : SetTimeoutBasedDispatcher() {
override fun scheduleQueueProcessing() {
setTimeout(messageQueue.processQueue, 0)
}
}
private class ClearTimeout(private val handle: Int) : CancelHandler(), DisposableHandle {
override fun dispose() {
clearTimeout(handle)
}
override fun invoke(cause: Throwable?) {
dispose()
}
override fun toString(): String = "ClearTimeout[$handle]"
}
internal class WindowDispatcher(private val window: Window) : CoroutineDispatcher(), Delay {
private val queue = WindowMessageQueue(window)
override fun dispatch(context: CoroutineContext, block: Runnable) = queue.enqueue(block)
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
window.setTimeout({ with(continuation) { resumeUndispatched(Unit) } }, delayToInt(timeMillis))
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable): DisposableHandle {
val handle = window.setTimeout({ block.run() }, delayToInt(timeMillis))
return object : DisposableHandle {
override fun dispose() {
window.clearTimeout(handle)
}
}
}
}
private class WindowMessageQueue(private val window: Window) : MessageQueue() {
private val messageName = "dispatchCoroutine"
init {
window.addEventListener("message", { event: dynamic ->
if (event.source == window && event.data == messageName) {
event.stopPropagation()
process()
}
}, true)
}
override fun schedule() {
Promise.resolve(Unit).then({ process() })
}
override fun reschedule() {
window.postMessage(messageName, "*")
}
}
/**
* An abstraction over JS scheduling mechanism that leverages micro-batching of dispatched blocks without
* paying the cost of JS callbacks scheduling on every dispatch.
*
* Queue uses two scheduling mechanisms:
* 1) [schedule] is used to schedule the initial processing of the message queue.
* JS engine-specific microtask mechanism is used in order to boost performance on short runs and a dispatch batch
* 2) [reschedule] is used to schedule processing of the queue after yield to the JS event loop.
* JS engine-specific macrotask mechanism is used not to starve animations and non-coroutines macrotasks.
*
* Yet there could be a long tail of "slow" reschedules, but it should be amortized by the queue size.
*/
internal abstract class MessageQueue : ArrayQueue<Runnable>() {
val yieldEvery = 16 // yield to JS macrotask event loop after this many processed messages
private var scheduled = false
abstract fun schedule()
abstract fun reschedule()
fun enqueue(element: Runnable) {
addLast(element)
if (!scheduled) {
scheduled = true
schedule()
}
}
fun process() {
try {
// limit number of processed messages
repeat(yieldEvery) {
val element = removeFirstOrNull() ?: return@process
element.run()
}
} finally {
if (isEmpty) {
scheduled = false
} else {
reschedule()
}
}
}
}
// We need to reference global setTimeout and clearTimeout so that it works on Node.JS as opposed to
// using them via "window" (which only works in browser)
private external fun setTimeout(handler: dynamic, timeout: Int = definedExternally): Int
private external fun clearTimeout(handle: Int = definedExternally)
| 294
| null |
99
| 255
|
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
| 5,388
|
kotlinx.coroutines-cn
|
Apache License 2.0
|
app/src/main/java/com/vitorpamplona/amethyst/ui/actions/NewPostView.kt
|
vitorpamplona
| 587,850,619
| false
| null |
package com.vitorpamplona.amethyst.ui.actions
import android.widget.Toast
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.model.Account
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.service.model.TextNoteEvent
import com.vitorpamplona.amethyst.ui.components.*
import com.vitorpamplona.amethyst.ui.note.ReplyInformation
import com.vitorpamplona.amethyst.ui.screen.loggedIn.UserLine
import kotlinx.coroutines.delay
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun NewPostView(onClose: () -> Unit, baseReplyTo: Note? = null, quote: Note? = null, account: Account) {
val postViewModel: NewPostViewModel = viewModel()
val context = LocalContext.current
// initialize focus reference to be able to request focus programmatically
val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current
val scroolState = rememberScrollState()
LaunchedEffect(Unit) {
postViewModel.load(account, baseReplyTo, quote)
delay(100)
focusRequester.requestFocus()
postViewModel.imageUploadingError.collect { error ->
Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
}
}
Dialog(
onDismissRequest = { onClose() },
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnClickOutside = false,
decorFitsSystemWindows = false
)
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Column(
modifier = Modifier
.padding(start = 10.dp, end = 10.dp, top = 10.dp)
.imePadding()
.weight(1f)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
CloseButton(onCancel = {
postViewModel.cancel()
onClose()
})
PostButton(
onPost = {
postViewModel.sendPost()
onClose()
},
isActive = postViewModel.message.text.isNotBlank() &&
!postViewModel.isUploadingImage
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(scroolState)
) {
if (postViewModel.replyTos != null && baseReplyTo?.event is TextNoteEvent) {
ReplyInformation(postViewModel.replyTos, postViewModel.mentions, account, "✖ ") {
postViewModel.removeFromReplyList(it)
}
}
OutlinedTextField(
value = postViewModel.message,
onValueChange = {
postViewModel.updateMessage(it)
},
keyboardOptions = KeyboardOptions.Default.copy(
capitalization = KeyboardCapitalization.Sentences
),
modifier = Modifier
.fillMaxWidth()
.border(
width = 1.dp,
color = MaterialTheme.colors.surface,
shape = RoundedCornerShape(8.dp)
)
.focusRequester(focusRequester)
.onFocusChanged {
if (it.isFocused) {
keyboardController?.show()
}
},
placeholder = {
Text(
text = stringResource(R.string.what_s_on_your_mind),
color = MaterialTheme.colors.onSurface.copy(alpha = 0.32f)
)
},
colors = TextFieldDefaults
.outlinedTextFieldColors(
unfocusedBorderColor = Color.Transparent,
focusedBorderColor = Color.Transparent
),
visualTransformation = UrlUserTagTransformation(MaterialTheme.colors.primary),
textStyle = LocalTextStyle.current.copy(textDirection = TextDirection.Content)
)
val myUrlPreview = postViewModel.urlPreview
if (myUrlPreview != null) {
Row(modifier = Modifier.padding(top = 5.dp)) {
if (isValidURL(myUrlPreview)) {
val removedParamsFromUrl =
myUrlPreview.split("?")[0].lowercase()
if (imageExtension.matcher(removedParamsFromUrl).matches()) {
AsyncImage(
model = myUrlPreview,
contentDescription = myUrlPreview,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.padding(top = 4.dp)
.fillMaxWidth()
.clip(shape = RoundedCornerShape(15.dp))
.border(
1.dp,
MaterialTheme.colors.onSurface.copy(alpha = 0.12f),
RoundedCornerShape(15.dp)
)
)
} else if (videoExtension.matcher(removedParamsFromUrl)
.matches()
) {
VideoView(myUrlPreview)
} else {
UrlPreview(myUrlPreview, myUrlPreview)
}
} else if (noProtocolUrlValidator.matcher(myUrlPreview).matches()) {
UrlPreview("https://$myUrlPreview", myUrlPreview)
}
}
}
}
}
val userSuggestions = postViewModel.userSuggestions
if (userSuggestions.isNotEmpty()) {
LazyColumn(
contentPadding = PaddingValues(
top = 10.dp
),
modifier = Modifier.heightIn(0.dp, 300.dp)
) {
itemsIndexed(
userSuggestions,
key = { _, item -> item.pubkeyHex }
) { _, item ->
UserLine(item, account) {
postViewModel.autocompleteWithUser(item)
}
}
}
}
Row(modifier = Modifier.fillMaxWidth()) {
UploadFromGallery(
isUploading = postViewModel.isUploadingImage,
tint = MaterialTheme.colors.primary,
modifier = Modifier.padding(bottom = 10.dp)
) {
postViewModel.upload(it, context)
}
}
}
}
}
}
}
@Composable
fun CloseButton(onCancel: () -> Unit) {
Button(
onClick = {
onCancel()
},
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults
.buttonColors(
backgroundColor = Color.Gray
)
) {
Icon(
painter = painterResource(id = R.drawable.ic_close),
contentDescription = stringResource(id = R.string.cancel),
modifier = Modifier.size(20.dp),
tint = Color.White
)
}
}
@Composable
fun PostButton(onPost: () -> Unit = {}, isActive: Boolean, modifier: Modifier = Modifier) {
Button(
modifier = modifier,
onClick = {
if (isActive) {
onPost()
}
},
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults
.buttonColors(
backgroundColor = if (isActive) MaterialTheme.colors.primary else Color.Gray
)
) {
Text(text = stringResource(R.string.post), color = Color.White)
}
}
@Composable
fun SaveButton(onPost: () -> Unit = {}, isActive: Boolean, modifier: Modifier = Modifier) {
Button(
modifier = modifier,
onClick = {
if (isActive) {
onPost()
}
},
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults
.buttonColors(
backgroundColor = if (isActive) MaterialTheme.colors.primary else Color.Gray
)
) {
Text(text = stringResource(R.string.save), color = Color.White)
}
}
@Composable
fun CreateButton(onPost: () -> Unit = {}, isActive: Boolean, modifier: Modifier = Modifier) {
Button(
modifier = modifier,
onClick = {
if (isActive) {
onPost()
}
},
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults
.buttonColors(
backgroundColor = if (isActive) MaterialTheme.colors.primary else Color.Gray
)
) {
Text(text = stringResource(R.string.create), color = Color.White)
}
}
@Composable
fun SearchButton(onPost: () -> Unit = {}, isActive: Boolean, modifier: Modifier = Modifier) {
Button(
modifier = modifier,
onClick = {
if (isActive) {
onPost()
}
},
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults
.buttonColors(
backgroundColor = if (isActive) MaterialTheme.colors.primary else Color.Gray
)
) {
Icon(
painter = painterResource(R.drawable.ic_search),
null,
modifier = Modifier.size(26.dp),
tint = Color.White
)
}
}
| 103
| null |
81
| 647
|
eff07bfb1e85b79d9d40f49e866eed24e8853bd0
| 13,685
|
amethyst
|
MIT License
|
common/src/main/kotlin/com/possible_triangle/skygrid/xml/resources/DimensionConfigs.kt
|
PssbleTrngle
| 174,212,271
| false
| null |
package com.possible_triangle.skygrid.xml.resources
import com.possible_triangle.skygrid.api.extensions.flat
import com.possible_triangle.skygrid.api.xml.elements.DimensionConfig
import com.possible_triangle.skygrid.api.xml.elements.ListWrapper
import com.possible_triangle.skygrid.api.xml.elements.providers.SingleBlock
import com.possible_triangle.skygrid.xml.ReferenceContext
import com.possible_triangle.skygrid.xml.XMLResource
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.MinecraftServer
import net.minecraft.world.level.block.Block
object DimensionConfigs : XMLResource<DimensionConfig>("dimensions", { DimensionConfig.serializer() }) {
val DEFAULT = DimensionConfig(ListWrapper(SingleBlock("bedrock")))
private val WEIGHT_MAP = hashMapOf<Block, HashMap<ResourceLocation, Double>>()
fun getProbability(block: Block): Map<ResourceLocation, Double> {
return WEIGHT_MAP[block] ?: emptyMap()
}
override fun merge(a: DimensionConfig, b: DimensionConfig): DimensionConfig {
return if (b.replace) b
else b.copy(
replace = false,
blocks = a.blocks + b.blocks,
loot = a.loot + b.loot,
mobs = a.mobs + b.mobs,
)
}
override fun onReload(server: MinecraftServer) {
validate(DEFAULT, server)
entries.forEach { (key, config) ->
val blocks = config.blocks.flat()
blocks.forEach { (block, probability) ->
WEIGHT_MAP.getOrPut(block) { hashMapOf() }[key] = probability
}
}
}
override fun validate(value: DimensionConfig, server: MinecraftServer): Boolean {
val registries = server.registryAccess()
val references = ReferenceContext()
return value.validate(registries, references)
}
}
| 3
|
Kotlin
|
1
| 11
|
6c61b498fe53a2107187c1b8d6a2c3cc30ab1bc6
| 1,832
|
Skygrid
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/org/stepik/android/view/auth/ui/activity/SocialAuthActivity.kt
|
StepicOrg
| 42,045,161
| false
| null |
package org.stepik.android.view.auth.ui.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import androidx.activity.viewModels
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.common.api.GoogleApiClient
import com.vk.api.sdk.VK
import com.vk.api.sdk.auth.VKAccessToken
import com.vk.api.sdk.auth.VKAuthCallback
import com.vk.api.sdk.auth.VKScope
import com.vk.api.sdk.exceptions.VKApiCodes
import jp.wasabeef.recyclerview.animators.FadeInDownAnimator
import kotlinx.android.synthetic.main.activity_auth_social.*
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.analytic.experiments.DeferredAuthSplitTest
import org.stepic.droid.analytic.experiments.OnboardingSplitTestVersion2
import org.stepic.droid.base.App
import org.stepic.droid.model.Credentials
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.ui.activities.MainFeedActivity
import org.stepic.droid.ui.activities.SmartLockActivityBase
import org.stepic.droid.ui.adapters.SocialAuthAdapter
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.ui.util.snackbar
import org.stepic.droid.util.ProgressHelper
import org.stepik.android.domain.auth.model.LoginFailType
import org.stepik.android.model.Course
import org.stepik.android.presentation.auth.SocialAuthPresenter
import org.stepik.android.presentation.auth.SocialAuthView
import org.stepik.android.view.auth.extension.getMessageFor
import org.stepik.android.view.auth.model.AutoAuth
import org.stepik.android.view.auth.model.SocialNetwork
import org.stepik.android.view.base.ui.span.TypefaceSpanCompat
import javax.inject.Inject
class SocialAuthActivity : SmartLockActivityBase(), SocialAuthView {
companion object {
private const val REQUEST_CODE_GOOGLE_SIGN_IN = 7007
private const val KEY_SOCIAL_ADAPTER_STATE = "social_adapter_state_key"
private const val KEY_SELECTED_SOCIAL_TYPE = "selected_social_type"
private const val EXTRA_WAS_LOGOUT_KEY = "wasLogoutKey"
private const val EXTRA_COURSE = "course"
private const val EXTRA_IS_FROM_MAIN_FEED = "is_from_main_feed"
private const val EXTRA_MAIN_CURRENT_INDEX = "main_current_index"
fun createIntent(context: Context, course: Course? = null, wasLogout: Boolean = false): Intent =
Intent(context, SocialAuthActivity::class.java)
.putExtra(EXTRA_COURSE, course)
.putExtra(EXTRA_WAS_LOGOUT_KEY, wasLogout)
fun createIntent(context: Context, isFromMainFeed: Boolean, mainCurrentIndex: Int): Intent =
Intent(context, SocialAuthActivity::class.java)
.putExtra(EXTRA_IS_FROM_MAIN_FEED, isFromMainFeed)
.putExtra(EXTRA_MAIN_CURRENT_INDEX, mainCurrentIndex)
}
@Inject
lateinit var deferredAuthSplitTest: DeferredAuthSplitTest
@Inject
lateinit var onboardingSplitTestVersion2: OnboardingSplitTestVersion2
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper
private val socialAuthPresenter: SocialAuthPresenter by viewModels { viewModelFactory }
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
// private lateinit var callbackManager: CallbackManager
private var selectedSocialType: SocialNetwork? = null
private var course: Course? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth_social)
course = intent.getParcelableExtra(EXTRA_COURSE)
injectComponent()
overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom)
dismissButton.setOnClickListener {
onBackPressed()
}
dismissButton.isVisible = true
// dismissButton.isVisible = deferredAuthSplitTest.currentGroup.isDeferredAuth || onboardingSplitTest.currentGroup == OnboardingSplitTest.Group.Personalized
launchSignUpButton.setOnClickListener {
analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_UP)
screenManager.showRegistration(this@SocialAuthActivity, course)
}
signInWithEmail.setOnClickListener {
analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN)
screenManager.showLogin(this@SocialAuthActivity, null, null, AutoAuth.NONE, course)
}
initGoogleApiClient(true) { showNetworkError() }
val recyclerState = savedInstanceState?.getSerializable(KEY_SOCIAL_ADAPTER_STATE)
if (recyclerState is SocialAuthAdapter.State) {
initSocialRecycler(recyclerState)
} else {
initSocialRecycler()
}
selectedSocialType = savedInstanceState?.getSerializable(KEY_SELECTED_SOCIAL_TYPE) as? SocialNetwork
val signInString = getString(R.string.sign_in)
val signInWithSocial = getString(R.string.sign_in_with_social_suffix)
val spannableSignIn = SpannableString(signInString + signInWithSocial)
val typefaceSpan = TypefaceSpanCompat(ResourcesCompat.getFont(this, R.font.roboto_medium))
spannableSignIn.setSpan(typefaceSpan, 0, signInString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
signInText.text = spannableSignIn
// callbackManager = CallbackManager.Factory.create()
// LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
// override fun onSuccess(loginResult: LoginResult) {
// socialAuthPresenter
// .authWithNativeCode(loginResult.accessToken.token, SocialNetwork.FACEBOOK)
// }
//
// override fun onCancel() {}
//
// override fun onError(exception: FacebookException) {
// analytic.reportError(Analytic.Login.FACEBOOK_ERROR, exception)
// showNetworkError()
// }
// })
if (checkPlayServices()) {
googleApiClient?.registerConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
override fun onConnected(bundle: Bundle?) {
val wasLogout = intent?.getBooleanExtra(EXTRA_WAS_LOGOUT_KEY, false) ?: false
if (wasLogout) {
Auth.CredentialsApi.disableAutoSignIn(googleApiClient)
}
requestCredentials()
}
override fun onConnectionSuspended(cause: Int) {}
})
}
onNewIntent(intent)
}
private fun injectComponent() {
App.component()
.authComponentBuilder()
.build()
.inject(this)
}
override fun onResume() {
super.onResume()
/**
* On Android 4, 5, 6 onSaveInstanceState is called after onStart
* and we can't show fragment dialog after onSaveInstanceState
*/
socialAuthPresenter.attachView(this)
}
override fun onPause() {
socialAuthPresenter.detachView(this)
super.onPause()
}
private fun initSocialRecycler(state: SocialAuthAdapter.State = SocialAuthAdapter.State.NORMAL) {
socialListRecyclerView.layoutManager = GridLayoutManager(this, 3)
socialListRecyclerView.itemAnimator = FadeInDownAnimator()
.apply {
removeDuration = 0
}
val adapter = SocialAuthAdapter(this::onSocialItemClicked, state)
showMore.setOnClickListener {
showMore.isVisible = false
showLess.isVisible = true
adapter.showMore()
}
showLess.setOnClickListener {
showLess.isVisible = false
showMore.isVisible = true
adapter.showLess()
}
showLess.isVisible = state == SocialAuthAdapter.State.EXPANDED
showMore.isVisible = state == SocialAuthAdapter.State.NORMAL
socialListRecyclerView.adapter = adapter
}
private fun onSocialItemClicked(type: SocialNetwork) {
analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN_SOCIAL, type.identifier)
when (type) {
SocialNetwork.GOOGLE -> {
if (googleApiClient == null) {
analytic.reportEvent(Analytic.Interaction.GOOGLE_SOCIAL_IS_NOT_ENABLED)
root_view.snackbar(messageRes = R.string.google_services_late)
} else {
val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient)
startActivityForResult(signInIntent, REQUEST_CODE_GOOGLE_SIGN_IN)
}
}
// SocialNetwork.FACEBOOK ->
// LoginManager.getInstance().logInWithReadPermissions(this, listOf("email"))
SocialNetwork.VK ->
VK.login(this, listOf(VKScope.OFFLINE, VKScope.EMAIL))
else -> {
selectedSocialType = type
screenManager.loginWithSocial(this, type)
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent?.data != null) {
redirectFromSocial(intent)
}
}
private fun redirectFromSocial(intent: Intent) {
val code = intent.data?.getQueryParameter("code") ?: return
val socialType = selectedSocialType ?: return
socialAuthPresenter.authWithCode(code, socialType)
}
override fun onCredentialsRetrieved(credentials: Credentials) {
screenManager.showLogin(this, credentials.login, credentials.password, AutoAuth.SMART_LOCK, course)
}
override fun onBackPressed() {
val fromMainFeed = intent?.extras?.getBoolean(EXTRA_IS_FROM_MAIN_FEED) ?: false
val index = intent?.extras?.getInt(EXTRA_MAIN_CURRENT_INDEX) ?: MainFeedActivity.defaultIndex
when {
fromMainFeed ->
screenManager.showMainFeed(this, index)
course != null ->
super.onBackPressed()
(onboardingSplitTestVersion2.currentGroup == OnboardingSplitTestVersion2.Group.Personalized ||
onboardingSplitTestVersion2.currentGroup == OnboardingSplitTestVersion2.Group.ControlPersonalized) && !sharedPreferenceHelper.isPersonalizedOnboardingWasShown ->
screenManager.showPersonalizedOnboarding(this)
// deferredAuthSplitTest.currentGroup.isDeferredAuth ->
// screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX)
else ->
screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX)
}
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.no_transition, R.anim.slide_out_to_bottom)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data != null && VK.onActivityResult(requestCode, resultCode, data, object : VKAuthCallback {
override fun onLogin(token: VKAccessToken) {
socialAuthPresenter
.authWithNativeCode(token.accessToken, SocialNetwork.VK, token.email)
}
override fun onLoginFailed(errorCode: Int) {
if (errorCode == VKApiCodes.CODE_AUTHORIZATION_FAILED) {
showNetworkError()
}
}
})) {
// vk will handle at callback
return
}
super.onActivityResult(requestCode, resultCode, data)
// callbackManager.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_GOOGLE_SIGN_IN && resultCode == Activity.RESULT_OK) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
// here is not only fail due to Internet, fix it. see: https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInResult
if (result?.isSuccess == true) {
val authCode = result.signInAccount?.serverAuthCode
if (authCode == null) {
analytic.reportEvent(Analytic.Login.GOOGLE_AUTH_CODE_NULL)
showNetworkError()
return
}
socialAuthPresenter
.authWithNativeCode(authCode, SocialNetwork.GOOGLE)
} else {
// check statusCode here https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes
val statusCode = result?.status?.statusCode?.toString() ?: "was null"
analytic.reportEvent(Analytic.Login.GOOGLE_FAILED_STATUS, statusCode)
showNetworkError()
}
}
}
override fun setState(state: SocialAuthView.State) {
if (state is SocialAuthView.State.Loading) {
ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG)
} else {
ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG)
}
when (state) {
is SocialAuthView.State.Success ->
screenManager.showMainFeedAfterLogin(this, course)
}
}
override fun showAuthError(failType: LoginFailType) {
root_view.snackbar(message = getMessageFor(failType))
// logout from socials
VK.logout()
if (googleApiClient?.isConnected == true) {
Auth.GoogleSignInApi.signOut(googleApiClient)
}
// fb:
// LoginManager.getInstance().logOut()
}
override fun showNetworkError() {
root_view.snackbar(messageRes = R.string.connectionProblems)
}
override fun onSocialLoginWithExistingEmail(email: String) {
screenManager.showLogin(this, email, null, AutoAuth.NONE, course)
}
override fun onSaveInstanceState(outState: Bundle) {
val adapter = socialListRecyclerView.adapter
if (adapter is SocialAuthAdapter) {
outState.putSerializable(KEY_SOCIAL_ADAPTER_STATE, adapter.state)
}
selectedSocialType?.let { outState.putSerializable(KEY_SELECTED_SOCIAL_TYPE, it) }
super.onSaveInstanceState(outState)
}
}
| 13
| null |
57
| 189
|
dd12cb96811a6fc2a7addcd969381570e335aca7
| 14,820
|
stepik-android
|
Apache License 2.0
|
src/main/kotlin/edu/ort/tuguia/core/category/domain/CategoryController.kt
|
ort-tuguia
| 480,584,853
| false
| null |
package edu.ort.tuguia.core.category.domain
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import javax.validation.Valid
@Tag(name = "Categories")
@RestController
@RequestMapping("/api/categories")
class CategoryController(private val categoryService: CategoryService) {
@Operation(summary = "Create a category")
@PostMapping("")
@ResponseStatus(HttpStatus.CREATED)
fun createCategory(@RequestBody @Valid @Parameter(description = "Category") category: Category): Category? {
return this.categoryService.createCategory(category)
}
@Operation(summary = "Get category by ID")
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun getCategoryById(@PathVariable @Parameter(description = "ID of category") id: String): Category? {
return this.categoryService.getCategoryById(id)
}
@Operation(summary = "Get category by name")
@GetMapping("/name/{name}")
@ResponseStatus(HttpStatus.OK)
fun getCategoryByName(@PathVariable @Parameter(description = "Name of category") name: String): Category? {
return this.categoryService.getCategoryByName(name)
}
@Operation(summary = "Get all categories")
@GetMapping("")
@ResponseStatus(HttpStatus.OK)
fun getAllCategories(): List<Category> {
return this.categoryService.getAllCategories()
}
@Operation(summary = "Update a category")
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun updateCategory(
@PathVariable @Parameter(description = "ID of category") id: String,
@RequestBody @Valid @Parameter(description = "Category") category: Category
): Category? {
category.id = id
return this.categoryService.updateCategory(category)
}
@Operation(summary = "Delete category by ID")
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun deleteCategoryById(@PathVariable @Parameter(description = "ID of category") id: String): Category? {
return this.categoryService.deleteCategoryById(id)
}
}
| 0
|
Kotlin
|
0
| 1
|
52cbddaf0946b7fcab0cec642415164621148881
| 2,217
|
tuguia-api
|
MIT License
|
app/src/main/java/io/minimaltools/task/presentation/feature/home/HomeUiState.kt
|
mtndrms
| 740,058,198
| false
|
{"Kotlin": 86733}
|
package io.minimaltools.task.presentation.feature.home
import io.minimaltools.task.data.local.entity.task.Task
data class HomeUiState(
val tasks: List<Task> = emptyList(),
val shouldDisplayPinnedTaskSnackbar: Boolean = false,
var startDate: Long? = null,
var endDate: Long? = null
)
| 0
|
Kotlin
|
0
| 0
|
425d09dc8f62fdf83f04772324bfb3da4b04f64c
| 301
|
Task
|
The Unlicense
|
src/app/src/main/java/com/helper/idealist/ui/activities/MainMenuActivity.kt
|
UIdealist
| 658,037,641
| false
|
{"Kotlin": 86984}
|
package com.helper.idealist.ui.activities
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.runtime.Composable
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Icon
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import com.helper.idealist.R
import com.helper.idealist.ui.drawers.MenuItem
import com.helper.idealist.ui.inputs.Input
import com.helper.idealist.ui.navigators.ScaffoldNavigatorDrawer
import com.helper.idealist.ui.theme.CustomTheme
import com.helper.idealist.ui.views.mainMenu.Brainstorms
import com.helper.idealist.ui.views.mainMenu.Ideas
import com.helper.idealist.ui.views.mainMenu.Projects
import com.helper.idealist.ui.views.mainMenu.Teams
import com.helper.idealist.ui.views.mainMenu.Home
class MainMenuActivity : ThemedActivity() {
@Composable
override fun content() {
// Generate items in navigation drawer
val items = arrayOf(
MenuItem(
icon = Icons.Default.Home,
iconDescription = stringResource(R.string.home_icon_description),
title = stringResource(R.string.menu_home_title),
identifier = "Home",
content = { Home() }
),
MenuItem(
icon = Icons.Default.Person,
iconDescription = stringResource(R.string.person_icon_description),
title = stringResource(R.string.menu_profile_title),
identifier = "Profile",
content = { Home() }
),
MenuItem(
icon = Icons.Default.Star,
iconDescription = stringResource(R.string.star_icon_description),
title = stringResource(R.string.menu_ideas_title),
identifier = "Ideas",
content = { Ideas() }
),
MenuItem(
icon = Icons.Default.Check,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_teams_title),
identifier = "Teams",
content = { Teams() }
),
MenuItem(
icon = Icons.Default.Build,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_projects_title),
identifier = "Projects",
content = { Projects() }
),
MenuItem(
icon = Icons.Default.Favorite,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_investments_title),
identifier = "Investments",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.Call,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_invest_title),
identifier = "Invest",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.DateRange,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_calendar_title),
identifier = "Calendar",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.LocationOn,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_meeting_title),
identifier = "Meeting",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.PlayArrow,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_events_title),
identifier = "Events",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.List,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_chats_title),
identifier = "Chat",
content = { Brainstorms() }
),
MenuItem(
icon = Icons.Default.ExitToApp,
iconDescription = stringResource(R.string.check_icon_description),
title = stringResource(R.string.menu_logout_title),
identifier = "Logout",
content = { Brainstorms() }
),
)
val searchText = remember { mutableStateOf ("") }
ScaffoldNavigatorDrawer(
items = items,
title = {
Input(
placeholder = stringResource(R.string.menu_search_title),
stateVar = searchText,
icon = Icons.Default.Search,
iconDescription = stringResource(R.string.search_icon_description)
)
},
actions = {
Icon(
modifier = Modifier
.padding(
end = CustomTheme.spaces.small,
)
.size(CustomTheme.spaces.smallImageSize),
painter = painterResource(R.drawable.person_icon),
contentDescription = stringResource(R.string.menu_icon_description),
tint = CustomTheme.colors.primary1
)
},
content = {
Home()
},
)
}
}
| 0
|
Kotlin
|
0
| 0
|
a06dfc5d94f592a65f20a963fade211ae05569cc
| 6,684
|
UIdealist-Mobile
|
Apache License 2.0
|
urist-access-logger/src/main/kotlin/org/dv/urist/AccessLogger.kt
|
dominic-jones
| 264,772,105
| false
|
{"Shell": 1, "Maven POM": 3, "JSON": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 5, "INI": 1, "Java": 1, "YAML": 1, "XML": 2}
|
package org.dv.urist
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders.REFERER
import org.springframework.http.HttpHeaders.USER_AGENT
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class AccessLogger(
private val uristApplicationProperties: UristApplicationProperties,
private val uristSlf4j: UristSlf4j
) {
private val log = LoggerFactory.getLogger(AccessLogger::class.java)
fun before() {
uristSlf4j.withService(uristApplicationProperties.service)
}
fun after(request: HttpServletRequest, response: HttpServletResponse) {
uristSlf4j.withStatus(response.status)
uristSlf4j.withRequestUri(request.requestURI)
uristSlf4j.withQueryParam(request.queryString)
uristSlf4j.withReferrer(request.getHeader(REFERER))
uristSlf4j.withUserAgent(request.getHeader(USER_AGENT))
if (uristApplicationProperties.accessLoggingEnabled) {
log.info(uristApplicationProperties.accessLogMessage)
}
}
}
| 8
| null |
1
| 1
|
4b394e362cc58fea4b28523e626e42473906f177
| 1,067
|
urist
|
Apache License 2.0
|
app/src/main/kotlin/com/peecock/ymusic/extensions/games/pacman/models/EnemyMovementModel.kt
|
geekeie
| 852,991,746
| false
|
{"Kotlin": 3810622, "Batchfile": 445}
|
package com.peecock.ymusic.extensions.games.pacman.models
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.geometry.Offset
data class EnemyMovementModel (
val redEnemyMovement: MutableState<Offset> = mutableStateOf(Offset(0F, 0F)),
val orangeEnemyMovement: MutableState<Offset> = mutableStateOf(Offset(0F, 0F))
)
| 0
|
Kotlin
|
0
| 0
|
bcc8e691579ea2c6f04e9287e45056e9fb85c532
| 392
|
YMusic
|
Apache License 2.0
|
kudos-compiler/src/main/java/com/kanyun/kudos/compiler/options/Option.kt
|
kanyun-inc
| 696,169,460
| false
|
{"Kotlin": 185284, "Java": 67470}
|
/*
* Copyright (C) 2023 Kanyun, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kanyun.kudos.compiler.options
import com.kanyun.kudos.compiler.logger
import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.CompilerConfigurationKey
import java.lang.ref.WeakReference
class Option<T : Any?>(
name: String,
private val defaultValue: T,
description: String,
valueDescription: String,
required: Boolean = false,
allowMultipleOccurrences: Boolean = false,
) {
private val key = CompilerConfigurationKey.create<T>(name)
private var value: T? = null
val option = CliOption(
name,
valueDescription,
description,
required,
allowMultipleOccurrences,
)
fun config(value: String?, configuration: CompilerConfiguration) {
val typedValue = when (defaultValue) {
is Boolean -> value?.toBooleanStrictOrNull() ?: defaultValue
is Int -> value?.toIntOrNull() ?: defaultValue
else -> value
} as T
if (typedValue != null) {
configuration.put(key, typedValue)
}
}
operator fun invoke(): T {
return value ?: (compilerConfiguration?.get()?.get(key) ?: defaultValue).also {
value = it
}
}
fun set(value: T) {
this.value = value
}
companion object {
private var compilerConfiguration: WeakReference<CompilerConfiguration>? = null
fun process(
option: AbstractCliOption,
value: String,
configuration: CompilerConfiguration,
) {
Options.all.firstOrNull {
it.option == option
}?.config(value, configuration)
}
fun initialize(compilerConfiguration: CompilerConfiguration) {
this.compilerConfiguration = WeakReference(compilerConfiguration)
}
fun dump() {
logger.warn(
Options.all.joinToString {
"${it.option.optionName}: ${it()}"
},
)
}
}
}
| 0
|
Kotlin
|
2
| 55
|
6c514dcf31302c6186f634a5b13337247298d35b
| 2,762
|
Kudos
|
Apache License 2.0
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/TriangulatedLineMesh.kt
|
kool-engine
| 81,503,047
| false
|
{"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597}
|
package de.fabmax.kool.scene
import de.fabmax.kool.KoolSystem
import de.fabmax.kool.math.MutableVec2f
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.spatial.BoundingBoxF
import de.fabmax.kool.modules.ksl.KslShader
import de.fabmax.kool.modules.ksl.KslUnlitShader
import de.fabmax.kool.modules.ksl.blocks.cameraData
import de.fabmax.kool.modules.ksl.blocks.convertColorSpace
import de.fabmax.kool.modules.ksl.blocks.fragmentColorBlock
import de.fabmax.kool.modules.ksl.blocks.mvpMatrix
import de.fabmax.kool.modules.ksl.lang.*
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.BlendMode
import de.fabmax.kool.pipeline.CullMethod
import de.fabmax.kool.pipeline.GpuType
import de.fabmax.kool.pipeline.backend.DepthRange
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.PrimitiveType
import de.fabmax.kool.scene.geometry.VertexView
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.LineString
import kotlin.math.max
import kotlin.math.min
fun Node.addTriangulatedLineMesh(
name: String = makeChildName("TriangulatedLineMesh"),
block: TriangulatedLineMesh.() -> Unit
): TriangulatedLineMesh {
val mesh = TriangulatedLineMesh(name).apply(block)
addNode(mesh)
return mesh
}
class TriangulatedLineMesh(geometry: IndexedVertexList, name: String = makeNodeName("TriangulatedLineMesh")) :
Mesh(geometry, name = name)
{
constructor(name: String = makeNodeName("TriangulatedLineMesh")) : this(IndexedVertexList(lineMeshAttribs), name)
private val lineBuffer = mutableListOf<LineVertex>()
private val lineAttribAccessor: MutableVec2f
private val prevDirAccessor: MutableVec3f
private val nextDirAccessor: MutableVec3f
var color = Color.RED
var width = 1f
init {
isCastingShadow = false
lineAttribAccessor = geometry.vertexIt.getVec2fAttribute(ATTRIB_LINE_ATTRIBS)
?: throw IllegalStateException("Mesh geometry misses required vertex attribute: $ATTRIB_LINE_ATTRIBS")
prevDirAccessor = geometry.vertexIt.getVec3fAttribute(ATTRIB_PREV_DIR)
?: throw IllegalStateException("Mesh geometry misses required vertex attribute: $ATTRIB_PREV_DIR")
nextDirAccessor = geometry.vertexIt.getVec3fAttribute(ATTRIB_NEXT_DIR)
?: throw IllegalStateException("Mesh geometry misses required vertex attribute: $ATTRIB_NEXT_DIR")
shader = Shader()
}
fun clear() {
lineBuffer.clear()
geometry.clear()
}
fun addLine(from: Vec3f, to: Vec3f, color: Color = this.color, width: Float = this.width): TriangulatedLineMesh {
return addLine(from, color, width, to, color, width)
}
fun addLine(
from: Vec3f,
fromColor: Color,
fromWidth: Float,
to: Vec3f,
toColor: Color,
toWidth: Float
): TriangulatedLineMesh {
moveTo(from, fromColor, fromWidth)
lineTo(to, toColor, toWidth)
return stroke()
}
fun addLine(vararg points: Vec3f): TriangulatedLineMesh {
return addLine(color, width, *points)
}
fun addLine(color: Color, width: Float, vararg points: Vec3f): TriangulatedLineMesh {
for (i in 0 until points.lastIndex) {
addLine(points[i], color, width, points[i+1], color, width)
}
return this
}
fun addLineString(lineString: LineString<*>, color: Color = this.color, width: Float = this.width): TriangulatedLineMesh {
for (i in 0 until lineString.lastIndex) {
addLine(lineString[i], color, width, lineString[i+1], color, width)
}
return this
}
fun moveTo(x: Float, y: Float, z: Float) = moveTo(Vec3f(x, y, z))
fun moveTo(
position: Vec3f,
color: Color = this.color,
width: Float = this.width,
vertexMod: (VertexView.() -> Unit)? = null
): TriangulatedLineMesh {
if (lineBuffer.isNotEmpty()) {
stroke()
}
lineBuffer.add(LineVertex(position, color, width, vertexMod))
return this
}
fun lineTo(x: Float, y: Float, z: Float) = lineTo(Vec3f(x, y, z))
fun lineTo(
position: Vec3f,
color: Color = this.color,
width: Float = this.width,
vertexMod: (VertexView.() -> Unit)? = null
): TriangulatedLineMesh {
lineBuffer.add(LineVertex(position, color, width, vertexMod))
return this
}
fun stroke(): TriangulatedLineMesh {
if (lineBuffer.size > 1) {
val startPos = MutableVec3f(lineBuffer.first()).mul(2f).subtract(lineBuffer[1])
val endPos = MutableVec3f(lineBuffer.last()).mul(2f)
.subtract(lineBuffer[lineBuffer.lastIndex - 1])
for (i in 0 until lineBuffer.size) {
val v = lineBuffer[i]
val p = if (i == 0) startPos else lineBuffer[i - 1]
val n = if (i == lineBuffer.lastIndex) endPos else lineBuffer[i + 1]
val ia = geometry.addLineVertex(v, -1f, p, n)
val ib = geometry.addLineVertex(v, 1f, p, n)
if (i > 0) {
geometry.addTriIndices(ia, ia - 2, ia - 1)
geometry.addTriIndices(ia, ia - 1, ib)
}
}
}
lineBuffer.clear()
return this
}
private fun IndexedVertexList.addLineVertex(vertex: LineVertex, u: Float, prevDir: Vec3f, nextDir: Vec3f): Int {
return addVertex {
set(vertex)
color.set(vertex.color)
lineAttribAccessor.set(u, vertex.width)
prevDirAccessor.set(prevDir)
nextDirAccessor.set(nextDir)
vertex.vertexMod?.invoke(this)
}
}
fun addWireframe(triMesh: IndexedVertexList, lineColor: Color? = null, width: Float = this.width) {
if (triMesh.primitiveType != PrimitiveType.TRIANGLES) {
throw IllegalArgumentException("Supplied mesh is not a triangle mesh: ${triMesh.primitiveType}")
}
val addedEdges = mutableSetOf<Long>()
for (i in 0 until triMesh.numIndices step 3) {
val i1 = triMesh.indices[i]
val i2 = triMesh.indices[i + 1]
val i3 = triMesh.indices[i + 2]
val e1 = min(i1, i2).toLong() shl 32 or max(i1, i2).toLong()
val e2 = min(i2, i3).toLong() shl 32 or max(i2, i3).toLong()
val e3 = min(i3, i1).toLong() shl 32 or max(i3, i1).toLong()
val v1 = triMesh[i1]
val v2 = triMesh[i2]
val v3 = triMesh[i3]
if (e1 !in addedEdges) {
addLine(v1, lineColor ?: v1.color, width, v2, lineColor ?: v2.color, width)
addedEdges += e1
}
if (e2 !in addedEdges) {
addLine(v2, lineColor ?: v2.color, width, v3, lineColor ?: v3.color, width)
addedEdges += e2
}
if (e3 !in addedEdges) {
addLine(v3, lineColor ?: v3.color, width, v1, lineColor ?: v1.color, width)
addedEdges += e3
}
}
}
fun addNormals(geometry: IndexedVertexList, lineColor: Color? = null, len: Float = 1f, width: Float = this.width) {
val tmpN = MutableVec3f()
geometry.forEach {
tmpN.set(it.normal).norm().mul(len).add(it.position)
val color = lineColor ?: it.color
addLine(it.position, color,width, tmpN, color, width)
}
}
fun addBoundingBox(aabb: BoundingBoxF, color: Color = this.color, width: Float = this.width) {
val p0 = Vec3f(aabb.min.x, aabb.min.y, aabb.min.z)
val p1 = Vec3f(aabb.min.x, aabb.min.y, aabb.max.z)
val p2 = Vec3f(aabb.min.x, aabb.max.y, aabb.max.z)
val p3 = Vec3f(aabb.min.x, aabb.max.y, aabb.min.z)
val p4 = Vec3f(aabb.max.x, aabb.min.y, aabb.min.z)
val p5 = Vec3f(aabb.max.x, aabb.min.y, aabb.max.z)
val p6 = Vec3f(aabb.max.x, aabb.max.y, aabb.max.z)
val p7 = Vec3f(aabb.max.x, aabb.max.y, aabb.min.z)
addLine(p0, p1, color, width)
addLine(p1, p2, color, width)
addLine(p2, p3, color, width)
addLine(p3, p0, color, width)
addLine(p4, p5, color, width)
addLine(p5, p6, color, width)
addLine(p6, p7, color, width)
addLine(p7, p4, color, width)
addLine(p0, p4, color, width)
addLine(p1, p5, color, width)
addLine(p2, p6, color, width)
addLine(p3, p7, color, width)
}
class LineVertex(position: Vec3f, val color: Color, val width: Float, val vertexMod: (VertexView.() -> Unit)?): Vec3f(position)
open class Shader(cfg: Config = defaultCfg) : KslShader("Triangulated Line Shader") {
constructor(block: Config.Builder.() -> Unit) : this(Config.Builder().apply(block).build())
init {
pipelineConfig = cfg.pipelineCfg
program.makeProgram(cfg)
cfg.modelCustomizer?.invoke(program)
}
private fun KslProgram.makeProgram(cfg: Config) {
val clipPos = interStageFloat4()
vertexStage {
val cross2 = functionFloat1("cross2") {
val v1 = paramFloat2("v1")
val v2 = paramFloat2("v2")
body {
v1.x * v2.y - v1.y * v2.x
}
}
val rotate90 = functionFloat2("rotate90") {
val v = paramFloat2("v")
val d = paramFloat1("d")
body {
float2Value(v.y * d, -v.x * d)
}
}
main {
val mvp = mvpMatrix().matrix
val camData = cameraData()
val ar = camData.viewport.z / camData.viewport.w
val vPrevPos = vertexAttribFloat3(ATTRIB_PREV_DIR.name)
val vNextPos = vertexAttribFloat3(ATTRIB_NEXT_DIR.name)
val vAttribs = vertexAttribFloat2(ATTRIB_LINE_ATTRIBS.name)
val pos = vertexAttribFloat3(Attribute.POSITIONS.name)
val shiftDir = vAttribs.x
val lineWidthPort = float1Port("lineWidth", vAttribs.y)
// project positions and compute 2d directions between prev, current and next points
val projPos = float4Var(mvp * float4Value(pos, 1f))
val projPrv = float4Var(mvp * float4Value(vPrevPos, 1f))
val projNxt = float4Var(mvp * float4Value(vNextPos, 1f))
val s = float2Var(projNxt.xy / projNxt.w - projPos.xy / projPos.w)
val r = float2Var(projPos.xy / projPos.w - projPrv.xy / projPrv.w)
s set normalize(s * float2Value(ar, 1f.const) * sign(projPos.w * projNxt.w))
r set normalize(r * float2Value(ar, 1f.const) * sign(projPos.w * projPrv.w))
// compute prev / next edge end points: rotate directions by 90°
val p = float2Var(rotate90(r, shiftDir))
val q = float2Var(rotate90(s, shiftDir))
// compute intersection points of prev and next edge
val x = float2Var((p + q) * 0.5f.const)
val rCrossS = float1Var(cross2(r, s))
`if`(abs(rCrossS) gt 0.001f.const) {
// lines are neither collinear nor parallel
val t = float1Var(clamp(cross2(q - p, s) / rCrossS, (-5f).const, 5f.const))
x set p + t * r
}
x.x *= 1f.const / ar
projPos.xy += (x * lineWidthPort.output / camData.viewport.w) * projPos.w
clipPos.input set projPos
outPosition set projPos
}
}
fragmentStage {
main {
val colorBlock = fragmentColorBlock(cfg.colorCfg)
val baseColor = float4Port("baseColor", colorBlock.outColor)
val outRgb = float3Var(baseColor.rgb)
outRgb set convertColorSpace(outRgb, cfg.colorSpaceConversion)
if (cfg.pipelineCfg.blendMode == BlendMode.BLEND_PREMULTIPLIED_ALPHA) {
outRgb set outRgb * baseColor.a
}
colorOutput(outRgb, baseColor.a)
if (cfg.depthFactor != 1f) {
val clipDepth = float1Var(clipPos.output.z / clipPos.output.w) * cfg.depthFactor.const
val isZeroToOne = KoolSystem.getContextOrNull()?.backend?.depthRange == DepthRange.ZERO_TO_ONE
if (isZeroToOne) {
outDepth set clipDepth
} else {
outDepth set (clipDepth + 1f.const) * 0.5f.const
}
}
}
}
}
companion object {
private val defaultCfg = Config.Builder().apply {
pipeline { cullMethod = CullMethod.NO_CULLING }
color { vertexColor() }
}.build()
}
class Config(builder: Builder) : KslUnlitShader.UnlitShaderConfig(builder) {
val depthFactor = builder.depthFactor
class Builder : KslUnlitShader.UnlitShaderConfig.Builder() {
var depthFactor = 1f
override fun build() = Config(this)
}
}
}
companion object {
val ATTRIB_LINE_ATTRIBS = Attribute("aLineAttribs", GpuType.FLOAT2)
val ATTRIB_PREV_DIR = Attribute("aPrevDir", GpuType.FLOAT3)
val ATTRIB_NEXT_DIR = Attribute("aNextDir", GpuType.FLOAT3)
val lineMeshAttribs = listOf(Attribute.COLORS, ATTRIB_LINE_ATTRIBS, Attribute.POSITIONS, ATTRIB_PREV_DIR, ATTRIB_NEXT_DIR)
}
}
| 9
|
Kotlin
|
20
| 303
|
8d05acd3e72ff2fc115d0939bf021a5f421469a5
| 14,082
|
kool
|
Apache License 2.0
|
src/main/kotlin/crackers/kobots/buttonboard/environment/OutsideState.kt
|
EAGrahamJr
| 647,347,853
| false
|
{"Kotlin": 40849, "Python": 2618, "Shell": 1111}
|
/*
* Copyright 2022-2023 by <NAME>, Jr.
*
* 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 crackers.kobots.buttonboard.environment
import crackers.hassk.EntityState
import crackers.kobots.app.AppCommon
import crackers.kobots.buttonboard.environment.EnvironmentDisplay.scaleImageAt
import crackers.kobots.buttonboard.environment.EnvironmentDisplay.temperatureColor
import crackers.kobots.parts.loadImage
import org.json.JSONObject
import java.awt.Color
import java.awt.Font
import java.awt.FontMetrics
import java.awt.Graphics2D
internal const val TEMP_HEIGHT = 40
internal const val TEMP_WIDTH = 128
/**
* Show the outside temperature and weather icon. This is currently scaled to fit in a 40x128 pixel area.
*/
class OutsideState(val graphics2D: Graphics2D, val x: Int, val y: Int) {
private val theFont = Font(Font.SANS_SERIF, Font.PLAIN, 32)
private val theFM: FontMetrics
init {
theFM = graphics2D.getFontMetrics(theFont)
}
internal fun show() =
with(graphics2D) {
val outsideTemp = AppCommon.hasskClient.getState("weather.home")
val temp = outsideTemp.temperature()
// clear the top area
color = Color.BLACK
fillRect(x, y, TEMP_WIDTH, TEMP_HEIGHT)
scaleImageAt(outsideTemp.icon()!!, x, y, TEMP_HEIGHT)
font = theFont
color = temperatureColor(temp)
drawString("$temp\u2109", x + 50, theFM.ascent)
}
private fun EntityState.icon() =
images[state] ?: images["default"].also {
EnvironmentDisplay.logger.warn("Unknown weather state: $state")
}
private val images by lazy {
mapOf(
"clear-night" to loadImage("/weather/clear-night.png"),
"cloudy" to loadImage("/weather/cloudy.png"),
"fog" to loadImage("/weather/fog.png"),
"mixed" to loadImage("/weather/mixed.png"),
"partlycloudy" to loadImage("/weather/partly-cloudy.png"),
"rainy" to loadImage("/weather/rain.png"),
"snowy" to loadImage("/weather/snow.png"),
"sunny" to loadImage("/weather/sunny.png"),
"windy" to loadImage("/weather/windy.png"),
"pouring" to loadImage("/weather/rainy_heavy.png"),
"default" to loadImage("/screaming.png"),
)
}
private fun EntityState.temperature() =
try {
JSONObject(attributes).optInt("temperature", 0)
} catch (_: Exception) {
0
}
}
| 0
|
Kotlin
|
0
| 0
|
9b983ea68f09dab1c670ad55bdbd79ff14001262
| 3,050
|
kobots-buttonboard
|
Apache License 2.0
|
libs/hello-libs/hello-chatbot/src/jsMain/kotlin/com/bkahlert/hello/chatbot/ui.kt
|
bkahlert
| 439,967,726
| false
|
{"Kotlin": 1721426, "CSS": 20318, "JavaScript": 11584, "Shell": 6384, "HTML": 2857, "SCSS": 588}
|
package com.bkahlert.hello.chatbot
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.chat.ChatRole
import com.bkahlert.hello.chat.chat
import com.bkahlert.hello.chat.chatMessage
import com.bkahlert.hello.fritz2.ContentBuilder
import com.bkahlert.hello.fritz2.srOnly
import com.bkahlert.hello.icon.heroicons.SolidHeroIcons
import com.bkahlert.hello.icon.icon
import dev.fritz2.core.HtmlTag
import dev.fritz2.core.RenderContext
import dev.fritz2.core.Store
import dev.fritz2.core.Tag
import dev.fritz2.core.placeholder
import dev.fritz2.core.storeOf
import dev.fritz2.core.type
import dev.fritz2.core.value
import dev.fritz2.core.values
import dev.fritz2.headless.components.inputField
import kotlinx.coroutines.flow.map
import org.w3c.dom.HTMLDivElement
public fun RenderContext.chat(chatbotSession: ChatbotSession): HtmlTag<HTMLDivElement> = chat(
history = {
chatMeta(chatbotSession)
chatHistory(chatbotSession)
},
prompt = {
chatPrompt(chatbotSession)
},
)
private fun RenderContext.chatMeta(chatbotSession: ChatbotSession) = div("w-full h-full grid place-items-center") {
className(chatbotSession.data.map { if (it.isEmpty()) "min-h-[10rem]" else "hidden" })
chatbotSession.data.render(this) {
div("flex gap-2 items-center") {
icon("w-8", Chatbot.ChatGPT.logo)
strong { +(chatbotSession.model ?: Chatbot.ChatGPT.defaultModel).id }
}
}
}
private fun RenderContext.chatHistory(chatbotSession: ChatbotSession): HtmlTag<HTMLDivElement> = div {
chatbotSession.data.renderEach {
chatMessage(it)
}
chatbotSession.response.render {
chatMessage(it)
}
}
private fun RenderContext.chatMessage(message: ChatMessage): HtmlTag<HTMLDivElement> = chatMessage(
image = { icon("w-6 rounded-full", message.icon) },
end = message.role == ChatRole.User,
) {
chatMessageContent(message.role) { +message.content }
}
private fun RenderContext.chatMessage(chunks: ChatbotChunks?) = when (chunks) {
null -> {}
else -> chunks.author.render { author ->
when (author) {
null -> {
chatMessage(
image = { icon("w-6 rounded-full", SolidHeroIcons.ellipsis_horizontal) },
)
}
else -> {
val (role, icon) = author
chatMessage(
image = { icon("w-6 rounded-full animate-spin", icon) },
end = role == ChatRole.User,
) {
chatMessageContent(author.first) {
chunks.data.renderEach({ it.id }) { span { +it.firstChoice.delta?.content.orEmpty() } }
}
}
}
}
}
}
private fun RenderContext.chatMessageContent(role: ChatRole, content: ContentBuilder<HTMLDivElement>): HtmlTag<HTMLDivElement> = when (role) {
ChatRole.User -> div("flex flex-col items-start gap-4 whitespace-pre-wrap break-words") { content() }
else -> div("markdown break-words prose dark:prose-invert") { content() }
}
private fun RenderContext.chatPrompt(
chatBotSession: ChatbotSession,
store: Store<String> = storeOf(""),
): Tag<HTMLDivElement> = inputField {
inputLabel {
value(store)
srOnly { +"You" }
inputTextfield {
type("text")
placeholder("Send a message...")
changes.values() handledBy {
chatBotSession.sendMessage(it)
value("")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
92e60b7eb9a74cfa957e05e3bf9e59f3ce3a582d
| 3,573
|
hello
|
MIT License
|
core/src/main/kotlin/org/hyrical/hcf/staff/StaffModeManager.kt
|
Hyrical
| 597,847,737
| false
|
{"Kotlin": 323471, "Java": 30373}
|
package org.hyrical.hcf.staff
import org.hyrical.hcf.staff.bukkit.BukkitModModeHook
/**
* Class created on 7/8/2023
* @author 98ping
* @project HCF
* @website https://solo.to/redis
*/
object StaffModeManager {
lateinit var activeHook: StaffModeHook
fun enable() {
//more to come using popular asf staff plugins
//like super vanish
this.activeHook = BukkitModModeHook()
}
}
| 13
|
Kotlin
|
0
| 3
|
74a1512f3af2db591bcd233d2012e4dbded10e8a
| 417
|
HCF
|
MIT License
|
core/src/main/java/com/extcode/project/core/domain/usecase/MovieAppUseCase.kt
|
Adithya-13
| 325,655,269
| false
| null |
package com.extcode.project.core.domain.usecase
import com.extcode.project.core.data.Resource
import com.extcode.project.core.domain.model.Movie
import kotlinx.coroutines.flow.Flow
interface MovieAppUseCase {
fun getAllMovies(sort: String): Flow<Resource<List<Movie>>>
fun getAllTvShows(sort: String): Flow<Resource<List<Movie>>>
fun getFavoriteMovies(sort: String): Flow<List<Movie>>
fun getFavoriteTvShows(sort: String): Flow<List<Movie>>
fun getSearchMovies(search: String): Flow<List<Movie>>
fun getSearchTvShows(search: String): Flow<List<Movie>>
fun setMovieFavorite(movie: Movie, state: Boolean)
}
| 0
|
Kotlin
|
8
| 21
|
1ba47f421412f6a26cf31c6b60b88feb883fe38b
| 641
|
MadeSubmsission
|
MIT License
|
kronos/src/test/java/com/hananrh/kronos/constraint/BlacklistConstraintTest.kt
|
hananrh
| 288,522,556
| false
|
{"Kotlin": 106265}
|
package com.hananrh.kronos.constraint
import com.hananrh.kronos.common.kronosTest
import com.hananrh.kronos.common.mapConfig
import com.hananrh.kronos.common.withRemoteMap
import com.hananrh.kronos.config.FeatureRemoteConfig
import com.hananrh.kronos.config.constraint.blacklist
import com.hananrh.kronos.config.type.intConfig
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
object BlacklistConstraintTest : Spek(kronosTest {
describe("Blacklist should control acceptable remote values") {
class Config : FeatureRemoteConfig by mapConfig() {
val someInt by intConfig {
default = 2
cached = false
blacklist = listOf(1, 3, 5)
}
}
val config = Config()
it("Should return remote value when not in blacklist") {
withRemoteMap("someInt" to 4)
assertEquals(4, config.someInt)
}
it("Should return default value when remote value in blacklist") {
withRemoteMap("someInt" to 3)
assertEquals(2, config.someInt)
}
}
})
| 0
|
Kotlin
|
0
| 0
|
b8757b4affcecae66613256f5ae3d32e12e7b773
| 1,041
|
kronos
|
MIT License
|
app/src/main/java/com/adversegecko3/twittergeckoui/ui/screens/NotificationsScreen.kt
|
Rviewer-Challenges
| 498,879,781
| false
|
{"Kotlin": 102440}
|
package com.adversegecko3.twittergeckoui.ui.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Settings
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.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.adversegecko3.twittergeckoui.R
import com.adversegecko3.twittergeckoui.model.Notification
import com.adversegecko3.twittergeckoui.model.Tweet
import com.adversegecko3.twittergeckoui.repo.TwitterRepository
import com.adversegecko3.twittergeckoui.ui.items.ItemNotification
import com.adversegecko3.twittergeckoui.ui.items.ItemTweet
@Composable
fun NotificationsScreen() {
Surface {
AllNotificationsScreen()
}
}
@Composable
fun AllNotificationsScreen() {
Column {
TopBarNotificationsScreen()
NotificationsFeed()
}
}
@Composable
fun TopBarNotificationsScreen() {
Row(
modifier = Modifier
.height(52.dp)
.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.profile_adversegecko3),
contentDescription = "User Profile Photo",
modifier = Modifier
.weight(1f)
.padding(start = 16.dp)
.clip(CircleShape)
)
Text(
text = "Notifications",
fontWeight = FontWeight.SemiBold,
fontSize = 24.sp,
modifier = Modifier
.weight(7f)
.padding(start = 32.dp),
letterSpacing = 0.65.sp
)
Image(
imageVector = Icons.Outlined.Settings,
contentDescription = "Tweet Order",
modifier = Modifier
.weight(1f),
colorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface)
)
}
Divider()
}
@Composable
fun NotificationsFeed() {
val twitterRepository = TwitterRepository()
val allNotifications = twitterRepository.getAllNotifications()
LazyColumn {
items(items = allNotifications) { notification ->
if (notification is Tweet) {
ItemTweet(tweet = notification)
} else if (notification is Notification) {
ItemNotification(notification = notification)
}
}
}
}
@Preview(showSystemUi = true)
@Composable
fun NotificationsScreenPreview() {
NotificationsScreen()
}
| 0
|
Kotlin
|
1
| 0
|
fcc13c2bfc8ad6e3b74779b2616926b93cf5677e
| 3,324
|
V7MtVULv0ExadsvYF4eh
|
MIT License
|
widgets/src/androidMain/kotlin/dev/icerock/moko/widgets/core/screen/ShowAlertExt.kt
|
icerockdev
| 218,209,603
| false
| null |
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets.screen
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import dev.icerock.moko.parcelize.Parcelize
import dev.icerock.moko.resources.desc.StringDesc
import kotlin.properties.ReadOnlyProperty
actual fun Screen<*>.showAlertDialog(dialogId: Int, factory: AlertDialogBuilder.() -> Unit) {
val context = context ?: return
val alert = AlertDialogBuilder(dialogId, context, childFragmentManager)
factory(alert)
alert.show()
}
actual class AlertDialogHandler
actual fun Screen<*>.registerAlertDialogHandler(
positive: ((dialogId: Int) -> Unit)?,
neutral: ((dialogId: Int) -> Unit)?,
negative: ((dialogId: Int) -> Unit)?
): ReadOnlyProperty<Screen<*>, AlertDialogHandler> = registerAttachFragmentHook(AlertDialogHandler()) { fragment ->
if (fragment !is AlertDialogFragment) return@registerAttachFragmentHook
fragment.listener = object : AlertDialogFragment.Listener {
override fun onPositivePressed(dialogId: Int) {
positive?.invoke(dialogId)
}
override fun onNeutralPressed(dialogId: Int) {
neutral?.invoke(dialogId)
}
override fun onNegativePressed(dialogId: Int) {
negative?.invoke(dialogId)
}
}
}
actual class AlertDialogBuilder(
private val dialogId: Int,
private val context: Context,
private val fragmentManager: FragmentManager
) {
private var title: String? = null
private var message: String? = null
private var positiveBtn: String? = null
private var neutralBtn: String? = null
private var negativeBtn: String? = null
actual fun title(title: StringDesc) {
this.title = title.toString(context)
}
actual fun message(message: StringDesc) {
this.message = message.toString(context)
}
actual fun positiveButton(title: StringDesc) {
positiveBtn = title.toString(context)
}
actual fun negativeButton(title: StringDesc) {
negativeBtn = title.toString(context)
}
actual fun neutralButton(title: StringDesc) {
neutralBtn = title.toString(context)
}
actual fun handler(handler: AlertDialogHandler) {
// handler is just mark that `Screen` have registered alert handler
}
internal fun show() {
val alertDialogFragment = AlertDialogFragment.instantiate(
arg = AlertDialogFragment.Arg(
dialogId = dialogId,
title = title,
message = message,
positiveBtn = positiveBtn,
neutralBtn = neutralBtn,
negativeBtn = negativeBtn
)
)
alertDialogFragment.show(fragmentManager, null)
}
}
class AlertDialogFragment : DialogFragment() {
var listener: Listener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val argument = arguments?.getParcelable<Arg>(ARG_KEY)
requireNotNull(argument) { "can't be opened without argument" }
val dialogId = argument.dialogId
return AlertDialog.Builder(requireContext()).apply {
setTitle(argument.title)
setMessage(argument.message)
argument.positiveBtn?.also {
setPositiveButton(it) { _, _ ->
listener?.onPositivePressed(dialogId)
}
}
argument.neutralBtn?.also {
setNeutralButton(it) { _, _ ->
listener?.onNeutralPressed(dialogId)
}
}
argument.negativeBtn?.also {
setNegativeButton(it) { _, _ ->
listener?.onNegativePressed(dialogId)
}
}
}.create()
}
// TODO improve this case
// now using String in arg, but in case of configuration change in AlertDialog will show old values...another version
// is not allow formatting stringdesc which can be very useful in dialogs.
@Parcelize
data class Arg(
val dialogId: Int,
val title: String?,
val message: String?,
val positiveBtn: String?,
val neutralBtn: String?,
val negativeBtn: String?
) : Parcelable
interface Listener {
fun onPositivePressed(dialogId: Int)
fun onNeutralPressed(dialogId: Int)
fun onNegativePressed(dialogId: Int)
}
companion object {
private const val ARG_KEY = "arg_bundle"
fun instantiate(arg: Arg): AlertDialogFragment {
return AlertDialogFragment().apply {
arguments = Bundle().apply { putParcelable(ARG_KEY, arg) }
}
}
}
}
| 40
|
Kotlin
|
29
| 334
|
63ea65d622f702432a5b5d1f587ba0fb8a81f95e
| 4,969
|
moko-widgets
|
Apache License 2.0
|
mock-interceptor/src/main/kotlin/com/gustafah/android/mockinterceptor/MockInterceptor.kt
|
gustafah
| 353,819,198
| false
| null |
package com.gustafah.android.mockinterceptor
import androidx.appcompat.app.AppCompatActivity
import com.gustafah.android.mockinterceptor.MockUtils.JSON_FIELD_DEFAULT
import com.gustafah.android.mockinterceptor.MockUtils.JSON_FIELD_REFERENCE
import com.gustafah.android.mockinterceptor.MockUtils.JSON_FIELD_SAVED_DATA
import com.gustafah.android.mockinterceptor.MockUtils.mockResponse
import com.gustafah.android.mockinterceptor.extensions.arrayWithFilterAndArgs
import com.gustafah.android.mockinterceptor.extensions.first
import com.gustafah.android.mockinterceptor.extensions.isNotEmpty
import com.gustafah.android.mockinterceptor.extensions.mapData
import com.gustafah.android.mockinterceptor.ui.MockOptionsActivity
import com.gustafah.android.mockinterceptor.ui.MockOptionsDialog
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import org.json.JSONObject
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
object MockInterceptor : Interceptor {
lateinit var config: MockConfig
private val isAwaiting = AtomicBoolean(false)
private val optChoice = AtomicInteger(-1)
private val mockFlow = Object()
private val lock = Object()
private var countDownLatch = CountDownLatch(1)
fun release(which: Int) = synchronized(lock) {
optChoice.set(which)
isAwaiting.set(false)
countDownLatch.countDown()
}
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val mockContent = config.fetchFileNameFromUrl(request)
JSONObject(mockContent).let {
if (it.has(JSON_FIELD_SAVED_DATA).not()) {
return mockResponse(code = 502, jsonResponse = it.toString(), request = request)
}
val arraySavedData = it.getJSONArray(JSON_FIELD_SAVED_DATA)
val arrayFilteredSavedData =
arraySavedData.arrayWithFilterAndArgs(config.requestArguments)
val jsonArray =
if (arrayFilteredSavedData.isNotEmpty()) arrayFilteredSavedData else arraySavedData
val default = it.getInt(JSON_FIELD_DEFAULT)
return if (config.selectorMode == MockConfig.OptionsSelectorMode.NO_SELECTION)
mockResponse(jsonArray.first(), request)
else if (MockUtils.autoMock || jsonArray.length() == 1) {
mockResponse(
jsonArray.getJSONObject(
if (default >= 0 && arrayFilteredSavedData.length() == 0) default else 0
),
request
)
} else {
synchronized(mockFlow) {
if (default >= 0) {
optChoice.set(default)
} else if (default == -2) {
optChoice.set((0 until jsonArray.length()).random())
} else {
val currentContext = config.context() as AppCompatActivity
val data = jsonArray.mapData()
if (config.selectorMode == MockConfig.OptionsSelectorMode.STANDARD) {
MockOptionsDialog.newInstance(
it.getString(JSON_FIELD_REFERENCE),
data.first,
data.second
).show(currentContext.supportFragmentManager, "MockOptionsDialog")
} else {
currentContext.startActivity(
MockOptionsActivity.makeIntent(
currentContext,
it.getString(JSON_FIELD_REFERENCE),
data.first,
data.second
)
)
}
waitValidation()
}
return@synchronized mockResponse(
jsonArray.getJSONObject(optChoice.get()),
request
)
}
}
}
}
private fun waitValidation() {
if (countDownLatch.count == 0L) {
countDownLatch = CountDownLatch(1)
}
isAwaiting.set(true)
countDownLatch.await()
}
}
| 0
|
Kotlin
|
1
| 5
|
1423aa2ee67fd287952d5dbe22fe2d3a68b0686d
| 4,504
|
mock-interceptor
|
Apache License 2.0
|
app/src/main/java/com/skyyo/template/application/persistance/room/cats/CatsDao.kt
|
Skyyo
| 408,838,169
| false
|
{"Kotlin": 60413}
|
package com.skyyo.template.application.persistance.room.cats
import androidx.room.*
import com.skyyo.template.application.models.local.Cat
import kotlinx.coroutines.flow.Flow
@Dao
interface CatsDao {
@Transaction
suspend fun deleteAndInsertCats(cats: List<Cat>) {
deleteCats()
insertCats(cats)
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCats(cats: List<Cat>)
@Query("SELECT * from cats_table")
fun observeCats(): Flow<List<Cat>>
@Query("DELETE from cats_table")
suspend fun deleteCats()
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(cats: List<Cat>)
@Query("DELETE FROM cats_table")
suspend fun clearAll()
}
| 0
|
Kotlin
|
1
| 4
|
7075f867384212f00408e945b7116b002169f9ad
| 735
|
android-compose-template
|
MIT License
|
src/main/kotlin/moe/gensoukyo/gui/event/EventListener.kt
|
MineCraftGensoukyo
| 402,519,776
| false
|
{"Kotlin": 107155}
|
package moe.gensoukyo.gui.event
import me.wuxie.wakeshow.wakeshow.api.WuxieAPI
import me.wuxie.wakeshow.wakeshow.api.event.PlayerCloseScreenEvent
import me.wuxie.wakeshow.wakeshow.api.event.PlayerOpenScreenEvent
import me.wuxie.wakeshow.wakeshow.api.event.PlayerPostClickComponentEvent
import me.wuxie.wakeshow.wakeshow.ui.WxScreen
import me.wuxie.wakeshow.wakeshow.ui.component.WButton
import me.wuxie.wakeshow.wakeshow.ui.component.WSlot
import me.wuxie.wakeshow.wakeshow.ui.component.WTextList
import moe.gensoukyo.gui.pages.DecomposePageTools
import moe.gensoukyo.gui.pages.EnhancePageTools
import moe.gensoukyo.gui.pages.Pages.pages
import moe.gensoukyo.gui.pages.ProficiencyPageTools
import moe.gensoukyo.gui.util.ClearCache
import moe.gensoukyo.gui.util.EmbeddingTools
import moe.gensoukyo.lib.maps.DataToken
import moe.gensoukyo.lib.server.npcApi
import moe.gensoukyo.gui.config.MainConfig.printDebugInfo
import org.bukkit.event.player.PlayerLoginEvent
import org.bukkit.event.player.PlayerQuitEvent
import taboolib.common.platform.event.EventPriority
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.info
object EventListener {
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun playerOpenScreenEventListener(e: PlayerOpenScreenEvent) {
if (printDebugInfo) {
info("${e.player.name}打开${e.screen.id} - ${e.screen}")
}
pages.forEach {
if (e.screen.id == it.key) {
if (it.value != null) {
it.value!!.guiPrepare(e.screen)
}
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun playerCloseScreenEventListener(e: PlayerCloseScreenEvent) {
if (printDebugInfo) {
info("${e.player.name}关闭${e.screen.id} - ${e.screen}")
}
pages.forEach {
if (e.screen.id == it.key) {
if (it.value != null) {
it.value!!.giveBackItems(e.player, e.screen)
}
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun playerPostClickComponentEventListener(e: PlayerPostClickComponentEvent) {
if (printDebugInfo) {
info("${e.player.name}点击${e.component.id} - ${e.component}")
}
if (e.screen.id == "强化UI") {
if (e.component.id == "equipment") {
e.screen.container.getComponent("image_success").w = 0
e.screen.container.getComponent("image_success").h = 0
e.screen.container.getComponent("image_fail").w = 0
e.screen.container.getComponent("image_fail").h = 0
val equip = (e.component as WSlot).itemStack
val equipText = e.screen.container.getComponent("enhance_level_text") as WTextList
EnhancePageTools.refreshEquip(equip, equipText)
WuxieAPI.updateGui(e.player)
return
}
if (e.component.id == "stone") {
e.screen.container.getComponent("image_success").w = 0
e.screen.container.getComponent("image_success").h = 0
e.screen.container.getComponent("image_fail").w = 0
e.screen.container.getComponent("image_fail").h = 0
val stone = (e.component as WSlot).itemStack
val stoneLevelText = e.screen.container.getComponent("stone_level_text") as WTextList
val stoneProbText = e.screen.container.getComponent("stone_prob_text") as WTextList
EnhancePageTools.refreshStone(stone, stoneLevelText, stoneProbText)
WuxieAPI.updateGui(e.player)
return
}
}
if (e.screen.id == "熟练度UI") {
if (e.component.id == "weapon_from") {
val from = (e.component as WSlot).itemStack
val fromText = e.screen.container.getComponent("weapon_from_text") as WTextList
ProficiencyPageTools.refreshWeaponTransfer(from, fromText)
WuxieAPI.updateGui(e.player)
return
}
if (e.component.id == "weapon_to") {
val to = (e.component as WSlot).itemStack
val toText = e.screen.container.getComponent("weapon_to_text") as WTextList
ProficiencyPageTools.refreshWeaponTransfer(to, toText)
WuxieAPI.updateGui(e.player)
return
}
if (e.component.id == "weapon_extract") {
val extract = (e.component as WSlot).itemStack
val extractText = e.screen.container.getComponent("weapon_extract_text") as WTextList
ProficiencyPageTools.refreshWeaponExtract(extract, extractText)
WuxieAPI.updateGui(e.player)
return
}
}
if (e.screen.id == "分解UI") {
if (e.component.id == "equipment" || e.component.id == "output") {
val equip = (e.screen.container.getComponent("equipment") as WSlot).itemStack
val output = (e.screen.container.getComponent("output") as WSlot).itemStack
val equipText = e.screen.container.getComponent("equipment_text") as WTextList
val outputText = e.screen.container.getComponent("output_text") as WTextList
DecomposePageTools.refresh(equip, output, equipText, outputText)
WuxieAPI.updateGui(e.player)
return
}
}
if (e.screen.id == "镶嵌UI") {
if (e.component.id == "equipment_slot"){
e.screen.container.getComponent("image_success").w = 0
e.screen.container.getComponent("image_success").h = 0
e.screen.container.getComponent("image_fail").w = 0
e.screen.container.getComponent("image_fail").h = 0
val equip = (e.component as WSlot).itemStack
val button = e.screen.container.getComponent("embedding_button") as WButton
val equipmentTipsText = e.screen.container.getComponent("equipment_tips") as WTextList
val stoneTipsText = e.screen.container.getComponent("stone_tips") as WTextList
EmbeddingTools.equipmentSlotCheck(e.player,equip,button,equipmentTipsText, stoneTipsText)
return
}
if (e.component.id == "stone_slot"){
e.screen.container.getComponent("image_success").w = 0
e.screen.container.getComponent("image_success").h = 0
e.screen.container.getComponent("image_fail").w = 0
e.screen.container.getComponent("image_fail").h = 0
val stone = (e.component as WSlot).itemStack
val button = e.screen.container.getComponent("embedding_button") as WButton
val equipmentTipsText = e.screen.container.getComponent("equipment_tips") as WTextList
val stoneTipsText = e.screen.container.getComponent("stone_tips") as WTextList
val stoneValueText = e.screen.container.getComponent("stone_value") as WTextList
EmbeddingTools.stoneSlotCheck(e.player,stone,button,equipmentTipsText,
stoneTipsText, stoneValueText)
return
}
}
if (e.screen.id == "摘除镶嵌UI") {
if(e.component.id == "equipment_slot"){
val equip = (e.component as WSlot).itemStack
EmbeddingTools.unEmbeddingCheck(equip,e.screen.container,e.player)
return
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun onPlayerLogin(e: PlayerLoginEvent) {
ClearCache.run(e.player)
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
fun onPlayerQuit(e: PlayerQuitEvent) {
val iPlayer = e.player.npcApi
pages.forEach {
if (it.value != null) {
val guiData =
DataToken("${iPlayer.name}_${it.key}_Gui", WxScreen::class.java) { null }
if (guiData[iPlayer.tempdata] != null) {
val gui = guiData[iPlayer.tempdata] as WxScreen
it.value!!.giveBackItems(e.player, gui)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e3958024f765ac13ef385e545cf80279d4c42e0e
| 8,360
|
MCGUserGUI
|
MIT License
|
glata/src/main/java/com/yalantis/glata/core/model/IndexBuffer.kt
|
Yalantis
| 165,843,008
| false
| null |
package com.yalantis.glata.core.model
import android.opengl.GLES20
import com.yalantis.glata.util.Logger
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.ShortBuffer
/**
* A wrapper class for ShortBuffer to use this as Vertex Buffer Object (VBO) for indices. We could
* use IntBuffer but we will not have so much indices so Short will be enough. Also not every video
* chip can work with int.
* TODO when unsigned short buffer will be released, migrate this class to unsigned short.
*/
class IndexBuffer(size: Int = 0) {
/**
* renderArrayType is GLES20.GL_ARRAY_BUFFER for vertices, texture coords and normals and
* GLES20.GL_ELEMENT_ARRAY_BUFFER for indices. This parameter is used when binding VBOs in
* video memory to use them for drawing.
*/
private val renderArrayType: Int = GLES20.GL_ELEMENT_ARRAY_BUFFER
/**
* drawMode and be GLES20.GL_STATIC_DRAW, GLES20.GL_DYNAMIC_DRAW or GLES20.GL_STREAM_DRAW.
* Our models will mostly be simple rectangles so simple static draw is okay for us.
*/
private val drawMode: Int = GLES20.GL_STATIC_DRAW
/**
* size of int in bytes
*/
val bytesPerElement: Int = 2
/**
* Buffer holds all needed coordinates of the model and can be uploaded to video memory.
*/
var buffer: ShortBuffer? = null
private set
/**
* As we are creating mostly rectangles, it is simplier to store them in an array at first and
* then we will load it to the buffer.
*/
private var array: ShortArray? = null
/**
* This variable holds buffer's ID in video memory.
*/
private var handle: Int = -1
/**
* Element count in array or buffer.
*/
var size: Int = 0
private set
init {
this.size = size
}
constructor(array: ShortArray) : this() {
this.size = array.size
this.array = array
}
fun allocate() {
if (size == 0) throw RuntimeException("Cannot allocate zero-sized buffer.")
buffer = ByteBuffer.allocateDirect(size * bytesPerElement)
.order(ByteOrder.nativeOrder())
.asShortBuffer()
}
fun initBuffer() {
if (buffer == null) throw RuntimeException("Buffer is null")
val buff = IntArray(1)
GLES20.glGenBuffers(1, buff, 0)
handle = buff[0]
if (handle < 0) Logger.log("Error creating index buffer object. Handle is $handle.")
buffer?.let { buffer ->
buffer.position(0)
GLES20.glBindBuffer(renderArrayType, handle)
GLES20.glBufferData(renderArrayType, size * bytesPerElement, buffer, drawMode)
} ?: throw RuntimeException("Buffer is null")
GLES20.glBindBuffer(renderArrayType, 0)
}
fun bind() {
GLES20.glBindBuffer(renderArrayType, handle)
}
fun put(array: ShortArray) {
buffer?.put(array)
}
fun put(buffer: ShortBuffer) {
this.buffer?.put(buffer)
}
fun position(index: Int) {
buffer?.position(index)
}
fun position(): Int = buffer?.position() ?: -1
fun deleteArray() {
array = null
}
fun putFromInnerArray() {
buffer?.put(array)
buffer?.position(0)
}
}
| 1
|
Kotlin
|
13
| 83
|
f022e7348afb381ac567ff6954164ef47438edf1
| 3,282
|
GLata
|
The Unlicense
|
src/main/kotlin/no/nav/familie/ba/infotrygd/feed/service/InfotrygdFeedService.kt
|
navikt
| 262,985,502
| false
| null |
package no.nav.familie.ba.infotrygd.feed.service
import no.nav.familie.ba.infotrygd.feed.database.Feed
import no.nav.familie.ba.infotrygd.feed.database.FeedRepository
import no.nav.familie.ba.infotrygd.feed.rest.dto.Type
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import java.time.LocalDate
import java.time.LocalDateTime
@Service
class InfotrygdFeedService(val feedRepository: FeedRepository) {
fun opprettNyFeed(
type: Type,
fnrBarn: String? = null,
fnrStonadsmottaker: String? = null,
datoStartNyBA: LocalDate? = null
) {
val erDuplikat = type.takeIf { it == Type.BA_Foedsel_v1 }
?.let { feedRepository.erDuplikatFoedselsmelding(type, fnrBarn!!) }
?: false
feedRepository.save(
Feed(
type = type,
fnrBarn = fnrBarn,
fnrStonadsmottaker = fnrStonadsmottaker,
datoStartNyBa = datoStartNyBA,
duplikat = erDuplikat,
opprettetDato = LocalDateTime.now()
)
)
}
fun hentMeldingerFraFeed(sistLestSekvensId: Long, maxSize: Int = 100): List<Feed> =
feedRepository.finnMeldingerMedSekvensIdStørreEnn(PageRequest.of(0, maxSize), sistLestSekvensId)
fun hentMeldingerFraFeed(fnr: String, type: Type): List<Feed> {
return feedRepository.finnMeldingerForFnr(fnr).filter { it.type == type }
}
}
| 7
| null |
1
| 2
|
7eec07c8bbe19b79aa1468f871fd685522fc44ff
| 1,479
|
familie-ba-infotrygd-feed
|
MIT License
|
tiny-event-sourcing-app/src/main/kotlin/ru/quipy/projectDemo/config/ProjectDemoConfig.kt
|
andrsuh
| 498,475,206
| false
|
{"Kotlin": 420728, "PLpgSQL": 1840, "Dockerfile": 242}
|
package ru.quipy.projectDemo.config
import org.slf4j.LoggerFactory
import ru.quipy.application.component.Component
import ru.quipy.core.AggregateRegistry
import ru.quipy.core.EventSourcingServiceFactory
import ru.quipy.projectDemo.api.ProjectAggregate
import ru.quipy.projectDemo.logic.ProjectAggregateState
import ru.quipy.projectDemo.projections.AnnotationBasedProjectEventsSubscriber
import ru.quipy.streams.AggregateEventStreamManager
import ru.quipy.streams.AggregateSubscriptionsManager
class ProjectDemoConfig(
var subscriptionsManager: AggregateSubscriptionsManager,
var projectEventSubscriber: AnnotationBasedProjectEventsSubscriber,
var eventSourcingServiceFactory: EventSourcingServiceFactory,
var eventStreamManager: AggregateEventStreamManager,
var aggregateRegistry: AggregateRegistry
) : Component {
private val logger = LoggerFactory.getLogger(ProjectDemoConfig::class.java)
override fun postConstruct() {
subscriptionsManager.subscribe<ProjectAggregate>(projectEventSubscriber)
eventStreamManager.maintenance {
onRecordHandledSuccessfully { streamName, eventName ->
logger.info("Stream $streamName successfully processed record of $eventName")
}
onBatchRead { streamName, batchSize ->
logger.info("Stream $streamName read batch size: $batchSize")
}
}
}
fun demoESService() = eventSourcingServiceFactory.create<String, ProjectAggregate, ProjectAggregateState>()
}
| 13
|
Kotlin
|
17
| 34
|
880796f04bb6e27aab615c8efccd709d5ca22193
| 1,530
|
tiny-event-sourcing
|
Apache License 2.0
|
app/src/main/java/com/moegirlviewer/util/cachedWebViews.kt
|
koharubiyori
| 449,942,456
| false
| null |
package com.moegirlviewer.util
import android.webkit.WebView
import androidx.compose.runtime.*
private typealias CachedWebViewMapContainer = MutableMap<String, WebView>
val LocalCachedWebViews = staticCompositionLocalOf<CachedWebViewsConsumer> { error("LocalCachedWebViews缺少提供者!") }
class CachedWebViews {
private val container: CachedWebViewMapContainer = mutableMapOf()
private val consumer = CachedWebViewsConsumer(container)
@Composable
fun Provider(content: @Composable () -> Unit) {
CompositionLocalProvider(
LocalCachedWebViews provides consumer
) {
content()
}
}
fun destroyAllInstance() {
container.values.toList().forEach { it.destroy() }
}
}
class CachedWebViewsConsumer(
private val container: CachedWebViewMapContainer
) {
// 如果页面中只使用一个webView,可以通过这个属性获取一个无需传入id的webView提供者
val singleCachedWebViewConsumer: SingleCachedWebViewConsumer
@Composable get() = SingleCachedWebViewConsumer(createId(), container)
@Composable
fun createId(key: String = "default"): String {
return "CachedWebViewId-$key:$currentCompositeKeyHash"
}
fun takeInstance(cachedWebViewId: String): WebView? {
return container[cachedWebViewId]
}
fun putInstance(cachedWebViewId: String, webView: WebView) {
container[cachedWebViewId] = webView
}
fun hasInstance(cachedWebViewId: String): Boolean {
return container.contains(cachedWebViewId)
}
}
class SingleCachedWebViewConsumer(
private val cachedWebViewId: String,
private val container: CachedWebViewMapContainer
) {
var webViewInstance: WebView?
get() = container[cachedWebViewId]
set(value) { container[cachedWebViewId] = value!! }
val existsInstance: Boolean
get() = container.contains(cachedWebViewId)
}
@Composable
fun rememberCachedWebViews(): CachedWebViews {
val cachedWebViews = remember { CachedWebViews() }
DisposableEffect(true) { onDispose { cachedWebViews.destroyAllInstance() } }
return cachedWebViews
}
| 1
|
Kotlin
|
5
| 16
|
e09753e76c11932d6f7344302d48f7a214cccf3a
| 1,980
|
Moegirl-plus-native
|
MIT License
|
app/src/main/java/com/jonnyhsia/memories/router/Params.kt
|
jonnyhsia
| 180,696,112
| false
| null |
package com.jonnyhsia.memories.router
object Params {
const val STORY_ID = "id"
}
| 1
| null |
1
| 2
|
c161f153bb9065274aaf03bff7c688fbdd4d7f96
| 86
|
Memories
|
MIT License
|
app/src/main/kotlin/de/digitalService/useID/ui/screens/error/IdentificationCardUnreadable.kt
|
digitalservicebund
| 486,188,046
| false
| null |
package de.digitalService.useID.ui.screens.error
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.ramcosta.composedestinations.annotation.Destination
import dagger.hilt.android.lifecycle.HiltViewModel
import de.digitalService.useID.R
import de.digitalService.useID.ui.components.ScanErrorScreen
import de.digitalService.useID.ui.coordinators.IdentificationCoordinator
import de.digitalService.useID.ui.screens.destinations.IdentificationCardUnreadableDestination
import javax.inject.Inject
@Destination(navArgsDelegate = IdentificationCardUnreadableNavArgs::class)
@Composable
fun IdentificationCardUnreadable(
viewModel: IdentificationCardUnreadableViewModel = hiltViewModel()
) {
val context = LocalContext.current
val buttonTextStringId = viewModel.redirectUrl?.let { R.string.scanError_redirect } ?: R.string.scanError_close
ScanErrorScreen(
titleResId = R.string.scanError_cardUnreadable_title,
bodyResId = R.string.scanError_cardUnreadable_body,
buttonTitleResId = buttonTextStringId,
showErrorCard = viewModel.errorCard,
onNavigationButtonClicked = { viewModel.onCancelButtonClicked(context) },
onButtonClicked = { viewModel.onCancelButtonClicked(context) }
)
}
@HiltViewModel
class IdentificationCardUnreadableViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val coordinator: IdentificationCoordinator
) : ViewModel() {
val errorCard: Boolean
val redirectUrl: String?
init {
val args = IdentificationCardUnreadableDestination.argsFrom(savedStateHandle)
errorCard = args.errorCard
redirectUrl = args.redirectUrl
}
fun onCancelButtonClicked(context: Context) {
redirectUrl?.let {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(it))
ContextCompat.startActivity(context, intent, null)
}
coordinator.cancelIdentification()
}
}
data class IdentificationCardUnreadableNavArgs(
val errorCard: Boolean,
val redirectUrl: String?
)
| 2
|
Kotlin
|
2
| 5
|
bfb1bea70b827563f80ff9828439de37197a431f
| 2,361
|
useid-app-android
|
MIT License
|
app/src/main/kotlin/clazz/im/clazz/ui/SlideOnlyActivity.kt
|
anthony0982
| 228,839,889
| false
| null |
package im.clazz.ui
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Bundle
import android.os.Handler
import com.halo.base.BaseActivity
import com.halo.util.ActivityUtil
import im.clazz.R
import im.clazz.extension.onClick
import im.clazz.extension.tint
import im.clazz.extension.unShieldTouch
import im.clazz.helper.DrawingViewHelper
import im.clazz.helper.SlideHelper
import im.clazz.lesson.LessonActivity
import im.clazz.video.ChangeOrientationHandler
import im.clazz.video.OrientationSensorListener
import kotlinx.android.synthetic.main.slide_only_activity.*
class SlideOnlyActivity : BaseActivity() {
var mBackPressed: Boolean = false
var handler: Handler? = null
var listener: OrientationSensorListener? = null
var sm: SensorManager? = null
var sensor: Sensor? = null
var slideHelper: SlideHelper? = null
var webViewCanvasHelper: DrawingViewHelper? = null
var drawingViewHelper: DrawingViewHelper? = null
companion object {
var url: String? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.slide_only_activity)
handler = ChangeOrientationHandler(this)
sm = getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensor = sm!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
listener = OrientationSensorListener(handler)
sm!!.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
initSlide()
}
override fun shouldSetStatusBarColor(): Boolean {
return false
}
fun initSlide() {
slideHelper = SlideHelper()
drawingViewHelper = DrawingViewHelper()
slideHelper?.activity = this
slideHelper?.webview = mWebView
slideHelper?.webviewLayout = mSlideLayout
slideHelper?.url = url
slideHelper?.loadingView = mLoadingView
slideHelper?.drawingViewHelper = drawingViewHelper
mDrawingView.disableTouchDraw = true
drawingViewHelper?.activity = LessonActivity.activity
drawingViewHelper?.darwingViewBelow = mDrawingView
drawingViewHelper?.darwingViewAbove = mDrawingViewAbove
drawingViewHelper?.drawingViewContainer = mSlideLayout
drawingViewHelper?.onSetDrawingView()
drawingViewHelper?.init()
slideHelper?.init()
initWebViewHelper()
}
private fun initWebViewHelper() {
slideHelper?.activity = this
slideHelper?.newContainer = mSlideLayout
slideHelper?.autoSlideButton = mBtnAutoSlide
slideHelper?.playAudioButton = mBtnPlayAudio
slideHelper?.eraseButton = mBtnErase
slideHelper?.buttonLeft = mBtnLeft
slideHelper?.buttonRight = mBtnRight
slideHelper?.buttonUp = mBtnUp
slideHelper?.buttonDown = mBtnDown
slideHelper?.onSetDirectionButton()
slideHelper?.onSetAutoSlideButton()
slideHelper?.onSetPlayAudioButton()
slideHelper?.onSetEraseButton()
mBtnFullScreen.onClick { slideHelper?.unFullscreen() }
mBtnRefresh.onClick { slideHelper?.refresh() }
mDrawingView?.unShieldTouch()
mDrawingViewAbove?.unShieldTouch()
webViewCanvasHelper?.activity = this
webViewCanvasHelper?.newContainer = mSlideLayout
mBtnDrawMode.onClick {
var drawMode = slideHelper?.phoenixChannelHelper?.drawMode
slideHelper?.phoenixChannelHelper?.drawMode = !drawMode!!
updateDrawModeState()
}
updateDrawModeState()
}
fun updateDrawModeState() {
var drawMode = slideHelper?.phoenixChannelHelper?.drawMode!!
mBtnDrawMode.tint(R.drawable.ic_pencil_slide, if (drawMode) R.color.black else R.color.gray_f0)
}
override fun onResume() {
sm!!.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
super.onResume()
ActivityUtil.hideNavigationBar(this)
slideHelper?.onResume()
webViewCanvasHelper?.onResume()
}
override fun onBackPressed() {
mBackPressed = true
slideHelper?.unFullscreen()
webViewCanvasHelper?.unFullscreen()
}
override fun onPause() {
sm!!.unregisterListener(listener)
super.onPause()
}
}
| 0
|
Kotlin
|
0
| 0
|
2002843248f81ec3d35dddee41c426d8f7b95111
| 4,368
|
android-auto-adapt-framework
|
MIT License
|
app/src/main/kotlin/clazz/im/clazz/ui/SlideOnlyActivity.kt
|
anthony0982
| 228,839,889
| false
| null |
package im.clazz.ui
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Bundle
import android.os.Handler
import com.halo.base.BaseActivity
import com.halo.util.ActivityUtil
import im.clazz.R
import im.clazz.extension.onClick
import im.clazz.extension.tint
import im.clazz.extension.unShieldTouch
import im.clazz.helper.DrawingViewHelper
import im.clazz.helper.SlideHelper
import im.clazz.lesson.LessonActivity
import im.clazz.video.ChangeOrientationHandler
import im.clazz.video.OrientationSensorListener
import kotlinx.android.synthetic.main.slide_only_activity.*
class SlideOnlyActivity : BaseActivity() {
var mBackPressed: Boolean = false
var handler: Handler? = null
var listener: OrientationSensorListener? = null
var sm: SensorManager? = null
var sensor: Sensor? = null
var slideHelper: SlideHelper? = null
var webViewCanvasHelper: DrawingViewHelper? = null
var drawingViewHelper: DrawingViewHelper? = null
companion object {
var url: String? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.slide_only_activity)
handler = ChangeOrientationHandler(this)
sm = getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensor = sm!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
listener = OrientationSensorListener(handler)
sm!!.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
initSlide()
}
override fun shouldSetStatusBarColor(): Boolean {
return false
}
fun initSlide() {
slideHelper = SlideHelper()
drawingViewHelper = DrawingViewHelper()
slideHelper?.activity = this
slideHelper?.webview = mWebView
slideHelper?.webviewLayout = mSlideLayout
slideHelper?.url = url
slideHelper?.loadingView = mLoadingView
slideHelper?.drawingViewHelper = drawingViewHelper
mDrawingView.disableTouchDraw = true
drawingViewHelper?.activity = LessonActivity.activity
drawingViewHelper?.darwingViewBelow = mDrawingView
drawingViewHelper?.darwingViewAbove = mDrawingViewAbove
drawingViewHelper?.drawingViewContainer = mSlideLayout
drawingViewHelper?.onSetDrawingView()
drawingViewHelper?.init()
slideHelper?.init()
initWebViewHelper()
}
private fun initWebViewHelper() {
slideHelper?.activity = this
slideHelper?.newContainer = mSlideLayout
slideHelper?.autoSlideButton = mBtnAutoSlide
slideHelper?.playAudioButton = mBtnPlayAudio
slideHelper?.eraseButton = mBtnErase
slideHelper?.buttonLeft = mBtnLeft
slideHelper?.buttonRight = mBtnRight
slideHelper?.buttonUp = mBtnUp
slideHelper?.buttonDown = mBtnDown
slideHelper?.onSetDirectionButton()
slideHelper?.onSetAutoSlideButton()
slideHelper?.onSetPlayAudioButton()
slideHelper?.onSetEraseButton()
mBtnFullScreen.onClick { slideHelper?.unFullscreen() }
mBtnRefresh.onClick { slideHelper?.refresh() }
mDrawingView?.unShieldTouch()
mDrawingViewAbove?.unShieldTouch()
webViewCanvasHelper?.activity = this
webViewCanvasHelper?.newContainer = mSlideLayout
mBtnDrawMode.onClick {
var drawMode = slideHelper?.phoenixChannelHelper?.drawMode
slideHelper?.phoenixChannelHelper?.drawMode = !drawMode!!
updateDrawModeState()
}
updateDrawModeState()
}
fun updateDrawModeState() {
var drawMode = slideHelper?.phoenixChannelHelper?.drawMode!!
mBtnDrawMode.tint(R.drawable.ic_pencil_slide, if (drawMode) R.color.black else R.color.gray_f0)
}
override fun onResume() {
sm!!.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
super.onResume()
ActivityUtil.hideNavigationBar(this)
slideHelper?.onResume()
webViewCanvasHelper?.onResume()
}
override fun onBackPressed() {
mBackPressed = true
slideHelper?.unFullscreen()
webViewCanvasHelper?.unFullscreen()
}
override fun onPause() {
sm!!.unregisterListener(listener)
super.onPause()
}
}
| 0
|
Kotlin
|
0
| 0
|
2002843248f81ec3d35dddee41c426d8f7b95111
| 4,368
|
android-auto-adapt-framework
|
MIT License
|
backend.native/tests/runtime/basic/empty_substring.kt
|
nakijun
| 91,489,155
| true
|
{"Markdown": 14, "Git Config": 1, "Gradle": 22, "Java Properties": 5, "Shell": 13, "Ignore List": 1, "Batchfile": 1, "XML": 12, "Kotlin": 4177, "C": 24, "Makefile": 1, "Text": 69, "Java": 2, "Protocol Buffer": 2, "C++": 25, "Groovy": 6, "INI": 6, "OpenStep Property List": 1}
|
fun main(args : Array<String>) {
val hello = "Hello world"
println(hello.subSequence(1, 1).toString())
}
| 0
|
Kotlin
|
0
| 0
|
a4eceb3e3acf4863ca85c258d657504d7d6a73f0
| 112
|
kotlin-native
|
Apache License 2.0
|
app/src/main/java/com/stanroy/playground/ui/common/ModifierExtensions.kt
|
stanroy
| 635,905,679
| false
| null |
package com.stanroy.playground.ui.common
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
val windowHorizontalSpacing = 24.dp
val windowVerticalSpacing = 24.dp
val Modifier.defaultHorizontalPadding: Modifier
get() = this.padding(horizontal = windowHorizontalSpacing)
val Modifier.defaultVerticalPadding: Modifier
get() = this.padding(vertical = windowVerticalSpacing)
val Modifier.defaultWindowPadding: Modifier
get() = this.padding(horizontal = windowHorizontalSpacing, vertical = windowVerticalSpacing)
| 0
|
Kotlin
|
0
| 0
|
8913e7db389b0c716902a308694498177c8b6cdd
| 593
|
compose-playground
|
Apache License 2.0
|
backend/src/test/kotlin/ch/zhaw/pm4/simonsays/factory/IngredientFactory.kt
|
SimonSays-PM4
| 766,576,264
| false
|
{"Kotlin": 471832, "TypeScript": 405650, "JavaScript": 1971, "CSS": 1791, "Dockerfile": 1104, "HTML": 462}
|
package ch.zhaw.pm4.simonsays.factory
import ch.zhaw.pm4.simonsays.entity.Event
import ch.zhaw.pm4.simonsays.entity.Ingredient
import ch.zhaw.pm4.simonsays.repository.IngredientRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class IngredientFactory(
@Autowired private val ingredientRepository: IngredientRepository,
@Autowired private val eventFactory: EventFactory
) {
fun createIngredient(
name: String = "Default Ingredient Name",
event: Event = eventFactory.createEvent()
): Ingredient {
val ingredient = Ingredient(
name = name,
event = event,
menuItems = null,
stations = null
)
return ingredientRepository.save(ingredient)
}
}
| 16
|
Kotlin
|
0
| 5
|
dfa6cf15770ae0749ca5062b3610c5d5da79ba07
| 829
|
simon-says
|
MIT License
|
backend/src/test/kotlin/ch/zhaw/pm4/simonsays/factory/IngredientFactory.kt
|
SimonSays-PM4
| 766,576,264
| false
|
{"Kotlin": 471832, "TypeScript": 405650, "JavaScript": 1971, "CSS": 1791, "Dockerfile": 1104, "HTML": 462}
|
package ch.zhaw.pm4.simonsays.factory
import ch.zhaw.pm4.simonsays.entity.Event
import ch.zhaw.pm4.simonsays.entity.Ingredient
import ch.zhaw.pm4.simonsays.repository.IngredientRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class IngredientFactory(
@Autowired private val ingredientRepository: IngredientRepository,
@Autowired private val eventFactory: EventFactory
) {
fun createIngredient(
name: String = "Default Ingredient Name",
event: Event = eventFactory.createEvent()
): Ingredient {
val ingredient = Ingredient(
name = name,
event = event,
menuItems = null,
stations = null
)
return ingredientRepository.save(ingredient)
}
}
| 16
|
Kotlin
|
0
| 5
|
dfa6cf15770ae0749ca5062b3610c5d5da79ba07
| 829
|
simon-says
|
MIT License
|
app/src/main/java/hu/mostoha/mobile/android/huki/ui/home/gpx/GpxDetailsBottomSheetDialog.kt
|
RolandMostoha
| 386,949,428
| false
| null |
package hu.mostoha.mobile.android.huki.ui.home.gpx
import android.os.Handler
import android.os.Looper
import hu.mostoha.mobile.android.huki.R
import hu.mostoha.mobile.android.huki.databinding.LayoutBottomSheetGpxDetailsBinding
import hu.mostoha.mobile.android.huki.extensions.resolve
import hu.mostoha.mobile.android.huki.extensions.setMessage
import hu.mostoha.mobile.android.huki.extensions.setMessageOrGone
import hu.mostoha.mobile.android.huki.extensions.startGoogleMapsDirectionsIntent
import hu.mostoha.mobile.android.huki.extensions.visibleOrGone
import hu.mostoha.mobile.android.huki.model.ui.GpxDetailsUiModel
import hu.mostoha.mobile.android.huki.views.BottomSheetDialog
class GpxDetailsBottomSheetDialog(
private val binding: LayoutBottomSheetGpxDetailsBinding
) : BottomSheetDialog(binding) {
fun initBottomSheet(gpxDetails: GpxDetailsUiModel, onCloseClick: () -> Unit) {
Handler(Looper.getMainLooper()).post {
with(binding) {
val hasAltitudeValues = gpxDetails.gpxAltitudeUiModel != null
gpxDetailsPrimaryText.text = gpxDetails.name
gpxDetailsAltitudeRangeContainer.visibleOrGone(hasAltitudeValues)
gpxDetailsUphillTextSeparator.visibleOrGone(hasAltitudeValues)
gpxDetailsDownhillTextSeparator.visibleOrGone(hasAltitudeValues)
if (hasAltitudeValues) {
gpxDetailsDistanceText.setMessage(gpxDetails.distanceText)
} else {
gpxDetailsDistanceText.text = context.getString(
R.string.gpx_details_bottom_sheet_distance,
gpxDetails.distanceText.resolve(context)
)
}
gpxDetailsUphillText.setMessageOrGone(gpxDetails.gpxAltitudeUiModel?.uphillText)
gpxDetailsDownhillText.setMessageOrGone(gpxDetails.gpxAltitudeUiModel?.downhillText)
gpxDetailsAltitudeRangeStartText.setMessageOrGone(gpxDetails.gpxAltitudeUiModel?.minAltitudeText)
gpxDetailsAltitudeRangeEndText.setMessageOrGone(gpxDetails.gpxAltitudeUiModel?.maxAltitudeText)
gpxDetailsCloseButton.setOnClickListener {
onCloseClick.invoke()
hide()
}
gpxDetailsNavigateStartButton.setOnClickListener {
context.startGoogleMapsDirectionsIntent(gpxDetails.start)
}
}
show()
}
}
}
| 0
|
Kotlin
|
1
| 4
|
296bcd8baca32a743d9d326f19bf8cd85cae7a7f
| 2,525
|
HuKi-Android
|
The Unlicense
|
service/src/main/kotlin/nl/pvanassen/sensorhub/app/service/SensorReceivedService.kt
|
pvanassen
| 340,315,997
| false
| null |
package nl.pvanassen.sensorhub.app.service
import nl.pvanassen.sensorhub.app.client.DomoticsClient
import nl.pvanassen.sensorhub.app.client.StatsdClient
import nl.pvanassen.sensorhub.app.model.NamedSensor
import nl.pvanassen.sensorhub.app.model.SensorId
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
class SensorReceivedService(private val domoticsClient: DomoticsClient,
private val statsdClient: StatsdClient,
private val graphiteService: GraphiteService) {
fun sensorReceived(namedSensor: Mono<NamedSensor<SensorId>>): Mono<Boolean> {
return namedSensor.flatMap {
if (it.name == it.sensor.id) {
Mono.empty()
} else {
Mono.just(it)
}
}
.flux()
.flatMap {
Flux.merge(domoticsClient.sendTemperature(namedSensor),
statsdClient.sendSensor(namedSensor),
graphiteService.storeStats(namedSensor))
}
.collectList()
.map { isSuccess(it) }
.switchIfEmpty(Mono.just(true))
}
private fun isSuccess(results: List<Boolean>) =
results.stream()
.distinct()
.filter { result -> !result }
.findFirst()
.orElse(false)
}
| 0
|
Kotlin
|
0
| 0
|
9413d86ab1eacd5f597a8dd81d92c7942366a760
| 1,447
|
sensorhub
|
Apache License 2.0
|
console-framework-client/src/main/java/io/axoniq/console/framework/client/ClientSettingsService.kt
|
AxonIQ
| 682,516,729
| false
|
{"Kotlin": 152634, "Java": 24388}
|
package io.axoniq.console.framework.client
import io.axoniq.console.framework.api.ClientSettings
import java.util.concurrent.CopyOnWriteArrayList
/**
* Service that holds the client settings. See [ClientSettingsObserver] for more information.
*/
class ClientSettingsService {
private val observers = CopyOnWriteArrayList<ClientSettingsObserver>()
private var settings: ClientSettings? = null
fun clearSettings() {
if(settings != null) {
settings = null
observers.forEach { it.onDisconnected() }
}
}
fun subscribeToSettings(observer: ClientSettingsObserver) {
this.observers.add(observer)
if(settings != null) {
observer.onConnectedWithSettings(settings!!)
}
}
fun updateSettings(settings: ClientSettings) {
clearSettings()
this.settings = settings
observers.forEach { it.onConnectedWithSettings(settings) }
}
}
| 1
|
Kotlin
|
0
| 0
|
c9a425a129c3595a25dd5713343a5248019ea8f1
| 949
|
console-framework-client
|
Apache License 2.0
|
ExamplesKotlin/FragmentStaticLayout/app/src/main/java/course/examples/fragments/staticlayout/TitlesFragment.kt
|
aporter
| 15,648,899
| false
| null |
package course.examples.fragments.staticlayout
import android.content.Context
import android.os.Bundle
import android.support.v4.app.ListFragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
//Several Activity and Fragment lifecycle methods are instrumented to emit LogCat output
//so you can follow the class' lifecycle
// Note: This implementation does not handle reconfigurations
class TitlesFragment : ListFragment() {
companion object {
private const val TAG = "TitlesFragment"
}
private var mCurrIdx = ListView.INVALID_POSITION
private lateinit var mListener: ListSelectionListener
// Called when the user selects an item from the List
override fun onListItemClick(l: ListView?, v: View?, pos: Int, id: Long) {
if (pos != mCurrIdx) {
// Indicates the selected item has been checked
listView.setItemChecked(pos, true)
mCurrIdx = pos
// Inform the QuoteViewerActivity that the item in position pos has been selected
mListener.onListSelection(pos)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
Log.i(TAG, "${javaClass.simpleName}: entered onAttach()")
try {
// Set the ListSelectionListener for communicating with the QuoteViewerActivity
mListener = context as ListSelectionListener
} catch (e: ClassCastException) {
throw ClassCastException("$context must implement OnArticleSelectedListener")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
Log.i(TAG, "${javaClass.simpleName}: entered onCreate()")
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.i(TAG, "${javaClass.simpleName}: entered onCreateView()")
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onActivityCreated(savedState: Bundle?) {
super.onActivityCreated(savedState)
Log.i(TAG, "${javaClass.simpleName}: entered onActivityCreated()")
// Set the list choice mode to allow only one selection at a time
listView.choiceMode = ListView.CHOICE_MODE_SINGLE
// Set the list adapter for the ListView
// Discussed in more detail in the user interface classes lesson
listAdapter = ArrayAdapter(
activity as Context,
R.layout.title_item,
QuoteViewerActivity.mTitleArray
)
}
override fun onStart() {
Log.i(TAG, "${javaClass.simpleName}: entered onStart()")
super.onStart()
}
override fun onResume() {
Log.i(TAG, "${javaClass.simpleName}: entered onResume()")
super.onResume()
}
override fun onPause() {
Log.i(TAG, "${javaClass.simpleName}: entered onPause()")
super.onPause()
}
override fun onStop() {
Log.i(TAG, "${javaClass.simpleName}: entered onStop()")
super.onStop()
}
override fun onDetach() {
Log.i(TAG, "${javaClass.simpleName}: entered onDetach()")
super.onDetach()
}
override fun onDestroy() {
Log.i(TAG, "${javaClass.simpleName}: entered onDestroy()")
super.onDestroy()
}
override fun onDestroyView() {
Log.i(TAG, "${javaClass.simpleName}: entered onDestroyView()")
super.onDestroyView()
}
}
| 65
| null |
5469
| 4,289
|
157373885fbfa18b83fa97cd46f6a003905970ea
| 3,633
|
coursera-android
|
MIT License
|
observable/src/commonTest/kotlin/world/phantasmal/observable/ObservableTests.kt
|
DaanVandenBosch
| 189,066,992
| false
| null |
package world.phantasmal.observable
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Test suite for all [Observable] implementations. There is a subclass of this suite for every
* [Observable] implementation.
*/
interface ObservableTests : DependencyTests {
override fun createProvider(): Provider
@Test
fun calls_observers_when_events_are_emitted() = test {
val p = createProvider()
var changes = 0
disposer.add(
p.observable.observeChange {
changes++
}
)
p.emit()
assertEquals(1, changes)
p.emit()
p.emit()
p.emit()
assertEquals(4, changes)
}
@Test
fun does_not_call_observers_after_they_are_disposed() = test {
val p = createProvider()
var changes = 0
val observer = p.observable.observeChange {
changes++
}
p.emit()
assertEquals(1, changes)
observer.dispose()
p.emit()
p.emit()
p.emit()
assertEquals(1, changes)
}
interface Provider : DependencyTests.Provider {
val observable: Observable<*>
override val dependency: Dependency get() = observable
}
}
| 1
|
Kotlin
|
5
| 17
|
89ea739c65fda32cda1caaf159cad022469e2663
| 1,260
|
phantasmal-world
|
MIT License
|
domain/src/main/kotlin/no/nav/su/se/bakover/domain/vilkår/uføre/LeggTilUførevurderingerRequest.kt
|
navikt
| 227,366,088
| false
|
{"Kotlin": 10063999, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209}
|
package no.nav.su.se.bakover.domain.vilkår.uføre
import arrow.core.Either
import arrow.core.Nel
import arrow.core.getOrElse
import arrow.core.left
import no.nav.su.se.bakover.common.domain.BehandlingsId
import no.nav.su.se.bakover.common.tid.periode.Periode
import vilkår.uføre.domain.UføreVilkår
import java.time.Clock
data class LeggTilUførevurderingerRequest(
/** Dekker både søknadsbehandlingId og revurderingId */
val behandlingId: BehandlingsId,
val vurderinger: Nel<LeggTilUførevilkårRequest>,
) {
sealed interface UgyldigUførevurdering {
data object UføregradOgForventetInntektMangler : UgyldigUførevurdering
data object PeriodeForGrunnlagOgVurderingErForskjellig : UgyldigUførevurdering
data object OverlappendeVurderingsperioder : UgyldigUførevurdering
data object VurderingsperiodenKanIkkeVæreUtenforBehandlingsperioden : UgyldigUførevurdering
data object AlleVurderingeneMåHaSammeResultat : UgyldigUførevurdering
data object HeleBehandlingsperiodenMåHaVurderinger : UgyldigUførevurdering
}
fun toVilkår(
behandlingsperiode: Periode,
clock: Clock,
): Either<UgyldigUførevurdering, UføreVilkår.Vurdert> {
return vurderinger.map { vurdering ->
vurdering.toVurderingsperiode(clock).getOrElse {
return when (it) {
LeggTilUførevilkårRequest.UgyldigUførevurdering.UføregradOgForventetInntektMangler -> {
UgyldigUførevurdering.UføregradOgForventetInntektMangler
}
LeggTilUførevilkårRequest.UgyldigUførevurdering.PeriodeForGrunnlagOgVurderingErForskjellig -> {
UgyldigUførevurdering.PeriodeForGrunnlagOgVurderingErForskjellig
}
LeggTilUførevilkårRequest.UgyldigUførevurdering.OverlappendeVurderingsperioder -> {
UgyldigUførevurdering.OverlappendeVurderingsperioder
}
LeggTilUførevilkårRequest.UgyldigUførevurdering.VurderingsperiodenKanIkkeVæreUtenforBehandlingsperioden -> {
UgyldigUførevurdering.VurderingsperiodenKanIkkeVæreUtenforBehandlingsperioden
}
}.left()
}
}.let { vurderingsperioder ->
UføreVilkår.Vurdert.tryCreate(
vurderingsperioder.toNonEmptyList(),
)
.mapLeft {
when (it) {
UføreVilkår.Vurdert.UgyldigUførevilkår.OverlappendeVurderingsperioder -> {
UgyldigUførevurdering.OverlappendeVurderingsperioder
}
}
}.map {
// Denne sjekken vil og fange opp: VurderingsperiodenKanIkkeVæreUtenforBehandlingsperioden, derfor kjører vi den etterpå.
if (!(behandlingsperiode fullstendigOverlapp vurderinger.map { it.periode })) {
return UgyldigUførevurdering.HeleBehandlingsperiodenMåHaVurderinger.left()
}
it
}
}.also {
if (vurderinger.any { it.oppfylt != vurderinger.first().oppfylt }) {
return UgyldigUførevurdering.AlleVurderingeneMåHaSammeResultat.left()
}
}
}
}
| 6
|
Kotlin
|
1
| 1
|
fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda
| 3,368
|
su-se-bakover
|
MIT License
|
src/main/kotlin/com/openuniquesolution/ResumeBuilder/model/model.kt
|
Ayushnita
| 331,679,023
| false
| null |
package com.openuniquesolution.ResumeBuilder.model
import java.time.LocalDate
import java.util.*
data class Skill(val type: String, val skillName: String, val ratting: Float)
data class AreaOfInterests(val areaOfInterests: MutableList<String>){
fun addInterest(interest: String){
this.areaOfInterests.add(interest)
}
fun deleteInterest(interest: String){
this.areaOfInterests.remove(interest)
}
}
data class ExtrasAndAwards(val extrasAndAwards: MutableList<String>){
fun addExtraAndAward(text: String){
this.extrasAndAwards.add(text)
}
fun deleteExtraAndAward(text: String){
this.extrasAndAwards.remove(text)
}
}
data class Education(val degree: String,
val schoolName: String,
val specification: String,
val location: String,
val from: LocalDate,
val to: LocalDate,
val per_ctc: Float
)
data class Experience(val company: String,
val designation: String,
val toDate: LocalDate,
val fromDate: LocalDate,
val description: String,
val technologies: MutableList<String>){
fun addTechnology(text: String){
this.technologies.add(text)
}
fun deleteTechnology(text: String){
this.technologies.remove(text)
}
}
data class ContactDetails(val name: String, val email: String, val mobileNumber: String, val location: String)
data class Project(val title: String, val company: String, val teamSize: Int, val technologies: MutableList<String>, val notes: MutableList<String>, val duration: Int)
| 0
|
Kotlin
|
0
| 0
|
ba022ee810472fdc973cecadabeaeb6ff30a5088
| 1,760
|
Resume_Builder_Kotlin
|
MIT License
|
app/src/main/kotlin/com/jpb/libchecker/ui/app/CheckPackageOnResumingActivity.kt
|
jpbandroid
| 471,680,216
| false
| null |
package com.jpb.libchecker.ui.app
import androidx.viewbinding.ViewBinding
import com.jpb.libchecker.base.BaseActivity
import com.jpb.libchecker.constant.Constants
import com.jpb.libchecker.utils.PackageUtils
abstract class CheckPackageOnResumingActivity<VB : ViewBinding> : BaseActivity<VB>() {
abstract fun requirePackageName(): String?
protected var isPackageReady: Boolean = false
override fun onResume() {
super.onResume()
if (isPackageReady) {
requirePackageName()?.let { pkgName ->
runCatching {
if (pkgName.endsWith(Constants.TEMP_PACKAGE)) {
packageManager.getPackageArchiveInfo(pkgName, 0)
} else {
PackageUtils.getPackageInfo(pkgName)
}
}.onFailure {
finish()
}
}
}
}
}
| 24
| null |
126
| 2
|
bba40d6aeea213790841db54c5f657b738a8f0c6
| 803
|
LibChecker
|
Apache License 2.0
|
app/src/main/java/com/github/malitsplus/pandaemonium/MainActivity.kt
|
MalitsPlus
| 507,558,801
| false
|
{"Kotlin": 9143, "Java": 4210}
|
package com.github.malitsplus.pandaemonium
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.ui.setupWithNavController
import com.github.malitsplus.pandaemonium.databinding.ActivityMainBinding
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_home, R.id.nav_cell_info, R.id.nav_file_observer
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
// Request su privileges
requestSuPrivileges()
}
private fun requestSuPrivileges() {
Runtime.getRuntime().exec("su")
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
| 0
|
Kotlin
|
0
| 0
|
813e03a0e82e53e487f6ca7a4276aaec0b5954a9
| 2,724
|
Pandaemonium
|
Do What The F*ck You Want To Public License
|
android/src/main/kotlin/com/hiennv/flutter_callkit_incoming/CallkitSoundPlayerService.kt
|
hiennguyen92
| 410,387,374
| false
| null |
package com.hiennv.flutter_callkit_incoming
import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.net.Uri
import android.os.*
import android.text.TextUtils
class CallkitSoundPlayerService : Service() {
private var vibrator: Vibrator? = null
private var audioManager: AudioManager? = null
private var mediaPlayer: MediaPlayer? = null
private var data: Bundle? = null
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
this.prepare()
this.playSound(intent)
this.playVibrator()
return START_STICKY;
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer?.stop()
mediaPlayer?.release()
vibrator?.cancel()
}
private fun prepare() {
mediaPlayer?.stop()
mediaPlayer?.release()
vibrator?.cancel()
}
private fun playVibrator() {
vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vibratorManager =
this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
vibratorManager.defaultVibrator
} else {
getSystemService(VIBRATOR_SERVICE) as Vibrator
}
audioManager = this.getSystemService(AUDIO_SERVICE) as AudioManager
when (audioManager?.ringerMode) {
AudioManager.RINGER_MODE_SILENT -> {
}
else -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator?.vibrate(
VibrationEffect.createWaveform(
longArrayOf(0L, 1000L, 1000L),
0
)
)
} else {
vibrator?.vibrate(longArrayOf(0L, 1000L, 1000L), 0)
}
}
}
}
private fun playSound(intent: Intent?) {
this.data = intent?.extras
val sound = this.data?.getString(
CallkitConstants.EXTRA_CALLKIT_RINGTONE_PATH,
""
)
var uri = sound?.let { getRingtoneUri(it) }
if (uri == null) {
uri = RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
}
try {
mediaPlayer(uri!!)
} catch (e: Exception) {
try {
uri = getRingtoneUri("ringtone_default")
mediaPlayer(uri!!)
} catch (e2: Exception) {
e2.printStackTrace()
}
}
}
private fun mediaPlayer(uri: Uri) {
mediaPlayer = MediaPlayer()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val attribution = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setLegacyStreamType(AudioManager.STREAM_RING)
.build()
mediaPlayer?.setAudioAttributes(attribution)
} else {
mediaPlayer?.setAudioStreamType(AudioManager.STREAM_RING)
}
setDataSource(uri)
mediaPlayer?.prepare()
mediaPlayer?.isLooping = true
mediaPlayer?.start()
}
private fun setDataSource(uri: Uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val assetFileDescriptor =
applicationContext.contentResolver.openAssetFileDescriptor(uri, "r")
if (assetFileDescriptor != null) {
mediaPlayer?.setDataSource(assetFileDescriptor)
}
return
}
mediaPlayer?.setDataSource(applicationContext, uri)
}
private fun getRingtoneUri(fileName: String) = try {
if (TextUtils.isEmpty(fileName)) {
RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
}
val resId = resources.getIdentifier(fileName, "raw", packageName)
if (resId != 0) {
Uri.parse("android.resource://${packageName}/$resId")
} else {
if (fileName.equals("system_ringtone_default", true)) {
RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
} else {
RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
}
}
} catch (e: Exception) {
try {
if (fileName.equals("system_ringtone_default", true)) {
RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
} else {
RingtoneManager.getActualDefaultRingtoneUri(
this@CallkitSoundPlayerService,
RingtoneManager.TYPE_RINGTONE
)
}
} catch (e: Exception) {
null
}
}
}
| 65
| null |
31
| 99
|
c44da3b5083fb9986e31f39631769ccfa8fdc9ce
| 5,658
|
flutter_callkit_incoming
|
MIT License
|
src/test/resources/projForTest/src/formatting/indentInWhenEntry.kt
|
javatlacati
| 92,708,152
| true
|
{"Text": 2, "Maven POM": 1, "Ignore List": 1, "Markdown": 1, "Java": 93, "Kotlin": 355, "Ant Build System": 1, "Java Properties": 7, "XML": 8, "HTML": 20}
|
package formatting
fun a() {
when (1) {
is Int {
println()
}
}
}
| 0
|
Kotlin
|
0
| 2
|
d24a0fd982df001cd5bb3c7364567ee7503e5b17
| 97
|
kotlin-netbeans
|
Apache License 2.0
|
app/src/main/java/com/king/template/api/ApiService.kt
|
jenly1314
| 248,971,077
| false
| null |
package com.king.template.api
import com.king.template.bean.Bean
import com.king.template.bean.Result
import retrofit2.Call
import retrofit2.http.*
/**
* @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
*/
@JvmSuppressWildcards
interface ApiService {
@GET("api/getRequest")
fun getRequest(@Header("token") token: String): Call<Result<Any>>
@FormUrlEncoded
@POST("api/postRequest")
fun postRequest(@Header("token") token: String, @Field("username") username: String): Call<Result<Any>>
@POST("api/postRequest")
fun postRequest(@Header("token") token: String, @Body bean: Bean): Call<Result<Any>>
@PUT("api/putRequest")
fun putRequest(@Header("token") token: String, @Body bean: Bean): Call<Result<Any>>
@PATCH("api/patchRequest")
fun patchRequest(@Header("token") token: String, @Body bean: Bean): Call<Result<Any>>
@DELETE("api/deleteRequest/{id}")
fun deleteRequest(@Header("token") token: String, @Path("id") id: Long): Call<Result<Any>>
@GET("api/getListBean")
fun getListBean(@Header("token") token: String): Call<Result<MutableList<Bean>>>
}
| 1
|
Kotlin
|
7
| 17
|
f1ffdc6d55c936141a385a18740d2f53269b2c49
| 1,125
|
AppTemplate
|
MIT License
|
app/src/main/java/com/drs/dseller/DSellerActivity.kt
|
raaja-sn
| 704,140,729
| false
|
{"Kotlin": 149967}
|
package com.drs.dseller
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navigation
import com.amplifyframework.auth.AuthUserAttribute
import com.amplifyframework.auth.AuthUserAttributeKey
import com.amplifyframework.auth.cognito.AWSCognitoAuthSession
import com.amplifyframework.auth.options.AuthFetchSessionOptions
import com.amplifyframework.auth.options.AuthSignUpOptions
import com.amplifyframework.kotlin.core.Amplify
import com.drs.dseller.feature_home.presentation.HomeViewModel
import com.drs.dseller.feature_home.presentation.screens.HomeScreen
import com.drs.dseller.feature_onboarding.presentation.screens.confirm_code.ConfirmationCodeScreen
import com.drs.dseller.feature_onboarding.presentation.screens.login.SignInScreen
import com.drs.dseller.feature_onboarding.presentation.screens.signup.SignUpScreen
import com.drs.dseller.feature_onboarding.presentation.toOnboard
import com.drs.dseller.feature_onboarding.presentation.viewmodels.OnBoardingViewModel
import com.drs.dseller.feature_user_session.presentation.screens.SplashScreen
import com.drs.dseller.feature_user_session.presentation.viewmodels.SplashScreenViewModel
import com.drs.dseller.ui.theme.DSellerTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@AndroidEntryPoint
class DSellerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DSellerTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavHost(navController, startDestination = "splash"){
composable("splash"){
val vm:SplashScreenViewModel = it.getViewModel(navController = navController)
SplashScreen(
state = vm.splashState.value,
vm = vm , navController = navController)
}
toOnboard(navController = navController)
composable("home"){
val vm:HomeViewModel = it.getViewModel(navController = navController)
HomeScreen(
state = vm.homeState.value,
vm,
navController
)
}
}
}
}
}
}
}
@Composable
inline fun <reified V:ViewModel> NavBackStackEntry.getViewModel(navController: NavHostController):V{
val parentRoute = destination.parent?.route?:return hiltViewModel()
val pEntry = remember(this){
navController.getBackStackEntry(parentRoute)
}
return hiltViewModel(pEntry)
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
DSellerTheme {
Greeting("Android")
}
}
| 0
|
Kotlin
|
0
| 0
|
6fa26d3c90205bcf31fa8aebba26b3659799fbda
| 4,264
|
DSeller-Android
|
MIT License
|
application/module/module_person/src/main/java/afkt_replace/module/person/data/api/PersonAPI.kt
|
afkT
| 343,177,221
| false
| null |
package afkt_replace.module.person.data.api
import afkt_replace.core.app.AppContext
import afkt_replace.core.lib.network.HttpCoreUtils
import afkt_replace.module.person.BuildConfig
import dev.DevHttpManager
import dev.environment.DevEnvironment
import dev.http.manager.RetrofitBuilder
import dev.http.manager.RetrofitOperation
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
/**
* detail: Person API
* @author Ttt
*/
class PersonAPI private constructor() {
companion object {
private val instance: PersonAPI by lazy { PersonAPI() }
fun api(): PersonService {
return instance.api()
}
fun operation(): RetrofitOperation {
return instance.operation()
}
}
// =================
// = PersonService =
// =================
@Volatile
private var mPersonService: PersonService? = null
fun api(): PersonService {
if (mPersonService == null) {
synchronized(PersonService::class.java) {
if (mPersonService == null) {
createAPI()
}
}
}
return mPersonService as PersonService
}
private fun createAPI() {
mPersonService = operation().create(
PersonService::class.java
)
}
// ==================
// = DevEnvironment =
// ==================
private fun apiBaseUrl(): HttpUrl {
return DevEnvironment.getPersonEnvironmentValue(
AppContext.context()
).toHttpUrl()
}
// =====================
// = RetrofitOperation =
// =====================
/**
* 对外提供操作对象
* @return RetrofitOperation
*/
fun operation(): RetrofitOperation {
return mOperation
}
// Retrofit Operation
private val mOperation: RetrofitOperation by lazy {
DevHttpManager.RM.putRetrofitBuilder(
BuildConfig.MODULE_NAME, mRetrofitBuilder
)
}
// ===================
// = RetrofitBuilder =
// ===================
// Retrofit Builder 接口
private val mRetrofitBuilder: RetrofitBuilder by lazy {
object : RetrofitBuilder {
/**
* 创建 Retrofit Builder
* @param oldRetrofit 上一次构建的 Retrofit
* @param httpUrl 构建使用指定 baseUrl
* @param okHttp OkHttpClient 构建全局复用
* @return Retrofit.Builder
*/
override fun createRetrofitBuilder(
oldRetrofit: Retrofit?,
httpUrl: HttpUrl?,
okHttp: OkHttpClient.Builder?
): Retrofit.Builder {
return HttpCoreUtils.createRetrofitBuilder(
httpUrl = httpUrl ?: apiBaseUrl(),
okHttp = okHttp ?: OkHttpClient.Builder()
)
}
// ==========
// = 通知事件 =
// ==========
/**
* 重新构建前调用
* @param key String
* @param oldRetrofit 上一次构建的 Retrofit
* 在 [createRetrofitBuilder] 之前调用
*/
override fun onResetBefore(
key: String,
oldRetrofit: Retrofit?
) {
}
/**
* 重新构建后调用
* @param key String
* @param newRetrofit 重新构建的 Retrofit 对象
* 在 [createRetrofitBuilder] 之后调用
*/
override fun onReset(
key: String,
newRetrofit: Retrofit?
) {
// 重新构建后创建新的代理对象
createAPI()
}
}
}
}
| 2
| null |
17
| 72
|
710033ee53928e30f8dc7b37aacdbde7283a7841
| 3,708
|
DevComponent
|
Apache License 2.0
|
typescript-kotlin/src/jsMain/kotlin/typescript/CustomTransformers.kt
|
karakum-team
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
package typescript
sealed external interface CustomTransformers {
/** Custom transformers to evaluate before built-in .js transformations. */
var before: Any? /* (TransformerFactory<SourceFile> | CustomTransformerFactory)[] */
/** Custom transformers to evaluate after built-in .js transformations. */
var after: Any? /* (TransformerFactory<SourceFile> | CustomTransformerFactory)[] */
/** Custom transformers to evaluate after built-in .d.ts transformations. */
var afterDeclarations: Any? /* (TransformerFactory<Bundle | SourceFile> | CustomTransformerFactory)[] */
}
| 38
| null |
7
| 31
|
79f2034ed9610e4416dfde5b70a0ff06f88210b5
| 642
|
types-kotlin
|
Apache License 2.0
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/serenitea_pot/furniture/FurnitureMakeCancelRsp.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.serenitea_pot.furniture
import org.anime_game_servers.core.base.Version.GI_1_5_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
import org.anime_game_servers.multi_proto.gi.data.general.Retcode
@AddedIn(GI_1_5_0)
@ProtoCommand(RESPONSE)
internal interface FurnitureMakeCancelRsp {
var retcode: Retcode
var furnitureMakeSlot: FurnitureMakeSlot
var makeId: Int
}
| 0
|
Kotlin
|
2
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 582
|
anime-game-multi-proto
|
MIT License
|
pandora/src/main/java/com/lodz/android/pandora/mvvm/base/fragment/BaseSandwichVmFragment.kt
|
LZ9
| 137,967,291
| false
|
{"Kotlin": 2174504}
|
package com.lodz.android.pandora.mvvm.base.fragment
import android.view.View
import androidx.lifecycle.Observer
import com.lodz.android.corekt.anko.toastLong
import com.lodz.android.corekt.anko.toastShort
import com.lodz.android.pandora.base.fragment.BaseSandwichFragment
import com.lodz.android.pandora.mvvm.vm.BaseSandwichViewModel
/**
* ViewModel基类Fragment(带基础状态控件、中部刷新控件和顶部/底部扩展的)
* @author zhouL
* @date 2019/12/9
*/
abstract class BaseSandwichVmFragment : BaseSandwichFragment() {
abstract fun getViewModel(): BaseSandwichViewModel
override fun setListeners(view: View) {
super.setListeners(view)
setViewModelObserves()
}
protected open fun setViewModelObserves() {
getViewModel().mPdrShortToastMsg.observe(this, Observer { value ->
if (value.isNullOrEmpty()) {
return@Observer
}
toastShort(value)
})
getViewModel().mPdrLongToastMsg.observe(this, Observer { value ->
if (value.isNullOrEmpty()) {
return@Observer
}
toastLong(value)
})
getViewModel().isPdrShowNoData.observe(this, Observer { value ->
if (value) { showStatusNoData() }
})
getViewModel().isPdrShowError.observe(this, Observer { value ->
if (value.first) { showStatusError(value.second) }
})
getViewModel().isPdrShowLoading.observe(this, Observer { value ->
if (value) { showStatusLoading() }
})
getViewModel().isPdrShowCompleted.observe(this, Observer { value ->
if (value) { showStatusCompleted() }
})
getViewModel().isPdrRefreshEnabled.observe(this, Observer { value ->
setSwipeRefreshEnabled(value)
})
getViewModel().isPdrRefreshFinish.observe(this, Observer { value ->
if (value){ setSwipeRefreshFinish() }
})
}
}
| 0
|
Kotlin
|
3
| 11
|
088adccfefef3578437df48ed114fc0eb142d3f3
| 1,942
|
AgileDevKt
|
Apache License 2.0
|
app/src/main/java/co/candyhouse/app/NfcHandler.kt
|
CANDY-HOUSE
| 280,844,064
| false
|
{"Kotlin": 675713, "Shell": 406}
|
package co.candyhouse.app
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.nfc.tech.NfcA
import android.provider.Settings
import co.utils.L
object NfcHandler {
fun ishasNfc(context:Context){
val b= context.packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
L.d("hcia", "Nfc功能:$b")
isEnableNfc(context)
}
fun isEnableNfc(context:Context){
var defaultAdapter = NfcAdapter.getDefaultAdapter(context)
val b= defaultAdapter.isEnabled
L.d("hcia", "Nfc开启状态:$b")
if (!b){
context.startActivity(Intent(Settings.ACTION_NFC_SETTINGS))
}
}
fun nfcCheckInetent(intent: Intent?) {
L.d("hcia", "intent.action:" + intent?.action + " extras:" + intent?.extras)
if (intent?.action == NfcAdapter.ACTION_TAG_DISCOVERED) {
// 寫入 candynfc 這個無用字段到nfc 貼紙裡面。背景感應會沒有作用
val tag: Tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)!!
val ndef = Ndef.get(tag)
if (ndef != null) {
ndef.connect()
val ndefRecord = NdefRecord.createTextRecord(null, "candynfc")
val records = arrayOf(ndefRecord)
val ndefMessage = NdefMessage(records)
try {
L.d("hcia", "寫入 candynfc:")
ndef.writeNdefMessage(ndefMessage)
} catch (e: Exception) {
L.d("hcia", "寫入失敗 decode exception" + e)
}
} else {
L.d("hcia", "intent:" + intent)
L.d("hcia", "tag:" + tag)
val ndefFormatable = NdefFormatable.get(tag)
L.d("hcia", "ndefFormatable:" + ndefFormatable)
try {
ndefFormatable.connect()
val ndefRecord = NdefRecord.createTextRecord(null, "candynfc")
val records = arrayOf(ndefRecord)
val newNdefMessage = NdefMessage(records)
ndefFormatable.format(newNdefMessage)
L.d("hcia", "格式化 Ndef:F")
} catch (err: Exception) {
L.d("hcia", "格式化 Ndef:F 失敗 err:" + err)
} finally {
try {
ndefFormatable.close()
} catch (e: java.lang.Exception) {
}
}
}
// nfc 格式化 不然有些廠商的nfc 貼紙會不作用
val nfcA = NfcA.get(tag)
if (nfcA != null) {
try {
nfcA.connect()
nfcA.transceive(
byteArrayOf(
0xA2.toByte(), // WRITE
0x03.toByte(), // page = 3
0xE1.toByte(),
0x10.toByte(),
0x06.toByte(),
0x00.toByte() // capability container (mapping version 1.0, 48 bytes for data available, read/write allowed)
)
)
nfcA.transceive(
byteArrayOf(
0xA2.toByte(), // WRITE
0x04.toByte(), // page = 4
0x03.toByte(),
0x00.toByte(),
0xFE.toByte(),
0x00.toByte() // empty NDEF TLV, Terminator TLV
)
)
L.d("hcia", "格式化 Nfca:A")
} catch (err: java.lang.Exception) {
L.d("hcia", "格式化 Nfca:A 失敗 err:" + err)
} finally {
try {
nfcA.close()
} catch (e: java.lang.Exception) {
}
}
}
}
}
}
| 14
|
Kotlin
|
11
| 24
|
e1cf834bc30b619751566542034079ee45239ba5
| 4,145
|
SesameSDK_Android_with_DemoApp
|
MIT License
|
platform/platform-api/src/com/intellij/ui/tabs/newImpl/JBDefaultTabPainter.kt
|
lots0logs
| 177,212,454
| false
| null |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.newImpl
import com.intellij.ui.paint.LinePainter2D
import com.intellij.ui.tabs.JBTabPainter
import com.intellij.ui.tabs.JBTabsPosition
import com.intellij.ui.tabs.TabTheme
import com.jetbrains.rd.swing.fillRect
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Point
import java.awt.Rectangle
open class JBDefaultTabPainter(val theme : TabTheme = TabTheme()) : JBTabPainter {
override fun getBackgroundColor(): Color = theme.background ?: theme.borderColor
override fun fillBackground(g: Graphics2D, rect: Rectangle) {
theme.background?.let{
g.fillRect(rect, theme.background)
}
}
override fun paintTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, hovered: Boolean) {
tabColor?.let {
g.fillRect(rect, tabColor)
}
if(hovered) {
g.fillRect(rect, if(tabColor != null) theme.hoverMaskColor else theme.borderColor)
return
}
tabColor ?: return
g.fillRect(rect, theme.inactiveMaskColor)
}
override fun paintSelectedTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, tabColor: Color?, active: Boolean, hovered: Boolean) {
val color = tabColor ?: theme.background
/**
* background filled for editors tab dragging
*/
color?.let {
g.fillRect(rect, color)
}
if(hovered) {
g.fillRect(rect, if(tabColor != null) theme.hoverMaskColor else theme.borderColor)
}
val underline = underlineRectangle(position, rect, theme.underlineHeight)
g.fillRect(underline, if(active) theme.underlineColor else theme.inactiveUnderlineColor)
}
override fun paintBorderLine(g: Graphics2D, thickness: Int, from: Point, to: Point) {
g.color = theme.borderColor
/**
* unexpected behaviour of {@link #LinePainter2D.paint(java.awt.Graphics2D, double, double, double, double, com.intellij.ui.paint.LinePainter2D.StrokeType, double)}
*/
if (thickness == 1) {
LinePainter2D.paint(g, from.getX(), from.getY(), to.getX(), to.getY())
return
}
LinePainter2D.paint(g, from.getX(), from.getY(), to.getX(), to.getY(), LinePainter2D.StrokeType.INSIDE,
thickness.toDouble())
}
protected open fun underlineRectangle(position: JBTabsPosition,
rect: Rectangle,
thickness: Int): Rectangle {
return Rectangle(rect.x, rect.y + rect.height - thickness, rect.width, thickness)
}
}
| 1
| null |
1
| 1
|
c31c45f8094cfeeaba61d797b39374d2946f3273
| 2,666
|
intellij-community
|
Apache License 2.0
|
src/main/kotlin/com/msg/gcms/domain/user/presentaion/data/response/UserResponseDto.kt
|
GSM-MSG
| 592,816,374
| false
| null |
package com.msg.gcms.domain.user.presentaion.data.response
import com.msg.gcms.domain.club.enums.ClubType
import java.util.*
data class UserResponseDto(
val uuid: UUID,
val email: String,
val name: String,
val grade: Int,
val classNum: Int,
val number: Int,
val profileImg: String?,
val clubs: List<ClubResponseDto>
) {
data class ClubResponseDto(
val id: Long,
val type: ClubType,
val name: String,
val bannerImg: String
)
}
| 8
| null |
0
| 8
|
6337a7a10921145e043162c8703a29aed6cadb44
| 488
|
GCMS-BackEnd
|
MIT License
|
src/main/kotlin/com/salesforce/revoman/internal/json/factories/CaseInsensitiveEnumAdapter.kt
|
salesforce-misc
| 677,000,343
| false
|
{"Kotlin": 113938, "Java": 41724, "HTML": 772, "Starlark": 283}
|
/**
* ************************************************************************************************
* Copyright (c) 2023, Salesforce, Inc. All rights reserved. SPDX-License-Identifier: Apache License
* Version 2.0 For full license text, see the LICENSE file in the repo root or
* http://www.apache.org/licenses/LICENSE-2.0
* ************************************************************************************************
*/
package com.salesforce.revoman.internal.json.factories
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonReader.Token.STRING
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.internal.Util
import java.lang.reflect.Type
internal class CaseInsensitiveEnumAdapter<T : Enum<T>>(val enumType: Class<T>) : JsonAdapter<T>() {
private val nameStrings =
enumType.getEnumConstants().map { Util.jsonName(it.name, enumType.getField(it.name)) }
private val options = JsonReader.Options.of(*nameStrings.toTypedArray())
override fun fromJson(reader: JsonReader): T {
val index = reader.selectString(options)
return if (index != -1) {
enumType.getEnumConstants()[index]
} else if (reader.peek() != STRING) {
throw JsonDataException("Expected a string but was ${reader.peek()} at path ${reader.path}")
} else {
val value = reader.nextString()
enumType.enumConstants.firstOrNull { it.name.compareTo(value, ignoreCase = true) == 0 }
?: throw JsonDataException(
"Expected one of $nameStrings but was $value at path ${reader.path}"
)
}
}
override fun toJson(writer: JsonWriter, value: T?) {
value?.also { writer.value(nameStrings[it.ordinal]) } ?: writer.nullValue()
}
companion object {
@JvmField
val FACTORY =
object : Factory {
override fun create(
type: Type,
annotations: Set<Annotation>,
moshi: Moshi
): JsonAdapter<*>? {
val rawType: Class<*> = Types.getRawType(type)
if (!rawType.isEnum()) {
return null
}
return CaseInsensitiveEnumAdapter(rawType as Class<out Enum<*>>)
}
}
}
}
| 9
|
Kotlin
|
5
| 6
|
b871b1bbc64b9cf9a66997d3203e9dc30484029b
| 2,301
|
ReVoman
|
Apache License 2.0
|
lib/src/main/java/com/kirkbushman/araw/models/WikiPage.kt
|
KirkBushman
| 182,531,355
| false
| null |
package com.kirkbushman.araw.models
import android.os.Parcelable
import com.kirkbushman.araw.http.base.EnvelopeKind
import com.kirkbushman.araw.utils.MILLIS
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
import java.util.*
@JsonClass(generateAdapter = true)
@Parcelize
data class WikiPage(
@Json(name = "content_md")
val contentMkdn: String,
@Json(name = "content_html")
val contentHtml: String,
@Json(name = "revision_date")
val revisionRaw: Long?
) : Parcelable {
val revisionDate: Date
get() {
if (revisionRaw != null) {
val milliseconds = revisionRaw / MILLIS
return Date(milliseconds)
}
return Date()
}
}
/**
* An enveloped list of strings, that represents the wiki page titles.
*/
@JsonClass(generateAdapter = true)
@Parcelize
data class WikiPageList(
@Json(name = "kind")
val kind: EnvelopeKind,
@Json(name = "data")
val data: List<String>
) : Parcelable
| 9
| null |
9
| 84
|
aeae071fa8d2a4e378de4a71420dc2a9792591f3
| 1,060
|
ARAW
|
MIT License
|
src/en/flixscans/src/eu/kanade/tachiyomi/extension/en/flixscans/FlixScansNet.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6409055, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.en.flixscans
import eu.kanade.tachiyomi.multisrc.flixscans.FlixScans
class FlixScansNet : FlixScans(
"Flix Scans",
"https://flixscans.org",
"en",
"https://flixscans.site/api/v1",
)
| 8
|
Kotlin
|
2
| 19
|
88bafd3e5fb05cd4690fc46e4a7d624a2595e7f3
| 237
|
komikku-extensions
|
Apache License 2.0
|
app/src/main/kotlin/app/seen/SeenFragment.kt
|
anirudh8860
| 144,851,679
| true
|
{"Kotlin": 257579, "Shell": 5304, "IDL": 1080}
|
package app.seen
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
internal class SeenFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?) =
FrameLayout(context).also {
it.background = ColorDrawable(Color.GREEN)
}
companion object {
fun newInstance() = SeenFragment()
}
}
| 0
|
Kotlin
|
0
| 1
|
ba8ead38f5bcefc857a6dc9cc344cd030ca5b22d
| 660
|
dinger
|
MIT License
|
library/src/test/java/com/github/gfx/static_gson/KotlinGracefulFailureTest.kt
|
topeterhonz
| 92,335,584
| true
|
{"Gradle": 6, "Markdown": 3, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Makefile": 1, "YAML": 1, "Java Properties": 2, "Proguard": 2, "Java": 42, "Kotlin": 6, "XML": 9}
|
package com.github.gfx.static_gson
import com.github.gfx.static_gson.annotation.JsonSerializable
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.*
import org.hamcrest.Matcher
import org.hamcrest.MatcherAssert.assertThat
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Before
import org.junit.Test
class KotlinGracefulFailureTest {
lateinit var gson: Gson
@Before
fun setUp() {
gson = GsonBuilder()
.registerTypeAdapterFactory(StaticGsonTypeAdapterFactory.newInstance())
.registerTypeAdapterFactory(CollectionTypeAdapterFactory())
.registerTypeAdapterFactory(ArrayTypeAdapter.FACTORY)
.serializeNulls()
.create()
}
@Test
fun deserializeNullableString() {
// incorrect type
jsonString("value" to JSONObject())
.toModel<NullableStringModel>()
.value
.assert(nullValue())
// correct type
jsonString("value" to "string")
.toModel<NullableStringModel>()
.value
.assert(equalTo("string"))
// null
jsonString("value" to null)
.toModel<NullableStringModel>()
.value
.assert(nullValue())
// not set
jsonString()
.toModel<NullableStringModel>()
.value
.assert(nullValue())
}
@JsonSerializable
data class NullableStringModel(val value: String?)
@Test
fun deserializeString() {
assertThat(throwsException { fromJson<StringModel>(jsonString("value" to JSONObject())) },
instanceOf<JsonGracefulException>())
assertThat(throwsException { fromJson<StringModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
assertThat(throwsException { fromJson<StringModel>(jsonString()) },
instanceOf<JsonGracefulException>())
assertThat<String>(fromJson<StringModel>(jsonString("value" to "string")).value, equalTo("string"))
}
@JsonSerializable
data class StringModel(var value: String)
@Test
fun deserializeMixedString() {
val correct = "string"
val incorrect = JSONObject()
val correctMatcher = equalTo("string")
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedStringModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrect,
"nonNull" to correct)
.toModel<MixedStringModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedStringModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedStringModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
Logger.setDelegate(null)
}
@JsonSerializable
data class MixedStringModel(val nullable: String?, var nonNull: String)
@Test
fun deserializeNullableObject() {
// incorrect type
assertThat<StringModel>(fromJson<NullableObjectModel>(jsonString("value" to "string")).value, nullValue())
// correct type
assertThat<StringModel>(fromJson<NullableObjectModel>(jsonString("value" to json("value" to "string"))).value, equalTo(StringModel("string")))
// null
assertThat<StringModel>(fromJson<NullableObjectModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<StringModel>(fromJson<NullableObjectModel>(jsonString()).value, nullValue())
}
@JsonSerializable
data class NullableObjectModel(var value: StringModel?)
@Test
fun deserializeObject() {
// incorrect type
assertThat(throwsException { fromJson<ObjectModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<ObjectModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<ObjectModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<StringModel>(fromJson<ObjectModel>(jsonString("value" to json("value" to "string"))).value, equalTo(StringModel("string")))
}
@JsonSerializable
data class ObjectModel(var value: StringModel)
@Test
fun deserializeMixedObject() {
val correct = json("value" to "string")
val incorrect = "string"
val correctMatcher = equalTo(StringModel("string"))
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedObjectModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrect,
"nonNull" to correct)
.toModel<MixedObjectModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedObjectModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedObjectModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedObjectModel(val nullable: StringModel?, var nonNull: StringModel)
@Test
fun deserializeNullableList() {
// incorrect type
assertThat<List<StringModel>>(fromJson<NullableListModel>(jsonString("value" to "string")).value, nullValue())
// null
assertThat<List<StringModel>>(fromJson<NullableListModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<List<StringModel>>(fromJson<NullableListModel>(jsonString()).value, nullValue())
// correct type
assertThat<List<StringModel>>(fromJson<NullableListModel>(jsonString("value" to jsonArray(json("value" to "string")))).value, equalTo(listOf<StringModel>(StringModel("string"))))
}
@JsonSerializable
data class NullableListModel(var value: List<StringModel>?)
@Test
fun deserializeList() {
// incorrect type
assertThat(throwsException { fromJson<ListModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<ListModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<ListModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<List<StringModel>>(fromJson<ListModel>(jsonString("value" to jsonArray(json("value" to "string")))).value, equalTo(listOf<StringModel>(StringModel("string"))))
}
@JsonSerializable
data class ListModel(var value: List<StringModel>)
@Test
fun deserializeMixedList() {
// correct type
val correct = jsonArray(json("value" to "string"))
val incorrect = "string"
val correctMatcher = equalTo(listOf<StringModel>(StringModel("string")))
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedListModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrect,
"nonNull" to correct)
.toModel<MixedListModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedListModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedListModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedListModel(val nullable: List<StringModel>?, var nonNull: List<StringModel>)
@Test
fun deserializeNullableMap() {
// incorrect type
assertThat<Map<String, String>>(fromJson<NullableMapModel>(jsonString("value" to "string")).value, nullValue())
// null
assertThat<Map<String, String>>(fromJson<NullableMapModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Map<String, String>>(fromJson<NullableMapModel>(jsonString()).value, nullValue())
// correct type
assertThat<Map<String, String>>(fromJson<NullableMapModel>(jsonString("value" to json("value" to "string"))).value, equalTo(mapOf("value" to "string")))
}
@JsonSerializable
data class NullableMapModel(var value: Map<String, String>?)
@Test
@Throws(Exception::class)
fun deserializeMap() {
// incorrect type
assertThat(throwsException { fromJson<MapModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<MapModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<MapModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Map<String, String>>(fromJson<MapModel>(jsonString("value" to json("value" to "string"))).value, equalTo(mapOf("value" to "string")))
}
@JsonSerializable
data class MapModel(var value: Map<String, String>)
@Test
fun deserializeMixedMap() {
// correct type
val correct = json("value" to "string")
val incorrect = "string"
val correctMatcher = equalTo(mapOf("value" to "string"))
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedMapModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrect,
"nonNull" to correct)
.toModel<MixedMapModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedMapModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedMapModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedMapModel(val nullable: Map<String, String>?, var nonNull: Map<String, String>)
@Test
fun deserializeNullableInt() {
// incorrect type
assertThat<Int>(fromJson<NullableIntModel>(jsonString("value" to "string")).value, nullValue())
assertThat<Int>(fromJson<NullableIntModel>(jsonString("value" to json())).value, nullValue())
// null
assertThat<Int>(fromJson<NullableIntModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Int>(fromJson<NullableIntModel>(jsonString()).value, nullValue())
// correct type
assertThat<Int>(fromJson<NullableIntModel>(jsonString("value" to 1)).value, equalTo(1))
}
@JsonSerializable
data class NullableIntModel(val value: Int?)
@Test
fun deserializeInt() {
// incorrect type
assertThat(throwsException { fromJson<IntModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<IntModel>(jsonString("value" to json())) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<IntModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<IntModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Int>(fromJson<IntModel>(jsonString("value" to 1)).value, equalTo(1))
}
@JsonSerializable
data class IntModel(val value: Int)
@Test
fun deserializeMixedInt() {
val correct = 1
val incorrectObject = JSONObject()
val incorrectString = "string"
val correctMatcher = equalTo(1)
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedIntModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectObject,
"nonNull" to correct)
.toModel<MixedIntModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectString,
"nonNull" to correct)
.toModel<MixedIntModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedIntModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedIntModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedIntModel(val nullable: Int?, var nonNull: Int?)
@Test
fun deserializeNullableLong() {
// incorrect type
assertThat<Long>(fromJson<NullableLongModel>(jsonString("value" to "string")).value, nullValue())
assertThat<Long>(fromJson<NullableLongModel>(jsonString("value" to json())).value, nullValue())
// null
assertThat<Long>(fromJson<NullableLongModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Long>(fromJson<NullableLongModel>(jsonString()).value, nullValue())
// correct type
assertThat<Long>(fromJson<NullableLongModel>(jsonString("value" to 1L)).value, equalTo(1L))
}
@JsonSerializable
data class NullableLongModel(val value: Long?)
@Test
fun deserializeLong() {
// incorrect type
assertThat(throwsException { fromJson<LongModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<LongModel>(jsonString("value" to json())) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<LongModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<LongModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Long>(fromJson<LongModel>(jsonString("value" to 1L)).value, equalTo(1L))
}
@JsonSerializable
data class LongModel(val value: Long)
@Test
fun deserializeMixedLong() {
val correct = 1L
val incorrectObject = JSONObject()
val incorrectString = "string"
val correctMatcher = equalTo(1L)
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedLongModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectObject,
"nonNull" to correct)
.toModel<MixedLongModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectString,
"nonNull" to correct)
.toModel<MixedLongModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedLongModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedLongModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedLongModel(val nullable: Long?, var nonNull: Long?)
@Test
fun deserializeNullableFloat() {
// incorrect type
assertThat<Float>(fromJson<NullableFloatModel>(jsonString("value" to "string")).value, nullValue())
assertThat<Float>(fromJson<NullableFloatModel>(jsonString("value" to json())).value, nullValue())
// null
assertThat<Float>(fromJson<NullableFloatModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Float>(fromJson<NullableFloatModel>(jsonString()).value, nullValue())
// correct type
assertThat<Float>(fromJson<NullableFloatModel>(jsonString("value" to 1F)).value, equalTo(1F))
}
@JsonSerializable
data class NullableFloatModel(val value: Float?)
@Test
fun deserializeFloat() {
// incorrect type
assertThat(throwsException { fromJson<FloatModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<FloatModel>(jsonString("value" to json())) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<FloatModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<FloatModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Float>(fromJson<FloatModel>(jsonString("value" to 1F)).value, equalTo(1F))
}
@JsonSerializable
data class FloatModel(val value: Float)
@Test
fun deserializeMixedFloat() {
val correct = 1f
val incorrectObject = JSONObject()
val incorrectString = "string"
val correctMatcher = equalTo(1f)
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedFloatModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectObject,
"nonNull" to correct)
.toModel<MixedFloatModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectString,
"nonNull" to correct)
.toModel<MixedFloatModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedFloatModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedFloatModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedFloatModel(val nullable: Float?, var nonNull: Float?)
@Test
fun deserializeNullableDouble() {
// incorrect type
assertThat<Double>(fromJson<NullableDoubleModel>(jsonString("value" to "string")).value, nullValue())
assertThat<Double>(fromJson<NullableDoubleModel>(jsonString("value" to json())).value, nullValue())
// null
assertThat<Double>(fromJson<NullableDoubleModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Double>(fromJson<NullableDoubleModel>(jsonString()).value, nullValue())
// correct type
assertThat<Double>(fromJson<NullableDoubleModel>(jsonString("value" to 1.0)).value, equalTo(1.0))
}
@JsonSerializable
data class NullableDoubleModel(val value: Double?)
@Test
fun deserializeDouble() {
// incorrect type
assertThat(throwsException { fromJson<DoubleModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<DoubleModel>(jsonString("value" to json())) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<DoubleModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<DoubleModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Double>(fromJson<DoubleModel>(jsonString("value" to 1.0)).value, equalTo(1.0))
}
@JsonSerializable
data class DoubleModel(val value: Double)
@Test
fun deserializeMixedDouble() {
val correct = 1.0
val incorrectObject = JSONObject()
val incorrectString = "string"
val correctMatcher = equalTo(1.0)
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedDoubleModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectObject,
"nonNull" to correct)
.toModel<MixedDoubleModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectString,
"nonNull" to correct)
.toModel<MixedDoubleModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedDoubleModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedDoubleModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedDoubleModel(val nullable: Double?, var nonNull: Double?)
@Test
fun deserializeNullableBoolean() {
// incorrect type
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to "string")).value, nullValue())
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to json())).value, nullValue())
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to 3)).value, nullValue())
// null
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to null)).value, nullValue())
// not set
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString()).value, nullValue())
// correct type
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to true)).value, equalTo(true))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to false)).value, equalTo(false))
// flexible types
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to "true")).value, equalTo(true))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to "false")).value, equalTo(false))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to "True")).value, equalTo(true))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to "False")).value, equalTo(false))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to 1)).value, equalTo(true))
assertThat<Boolean>(fromJson<NullableBooleanModel>(jsonString("value" to 0)).value, equalTo(false))
}
@JsonSerializable
data class NullableBooleanModel(val value: Boolean?)
@Test
fun deserializeBoolean() {
// incorrect type
assertThat(throwsException { fromJson<BooleanModel>(jsonString("value" to "string")) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<BooleanModel>(jsonString("value" to json())) },
instanceOf<JsonGracefulException>())
// incorrect type
assertThat(throwsException { fromJson<BooleanModel>(jsonString("value" to 3)) },
instanceOf<JsonGracefulException>())
// null
assertThat(throwsException { fromJson<BooleanModel>(jsonString("value" to null)) },
instanceOf<JsonGracefulException>())
// not set
assertThat(throwsException { fromJson<BooleanModel>(jsonString()) },
instanceOf<JsonGracefulException>())
// correct type
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to true)).value, equalTo(true))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to false)).value, equalTo(false))
// flexible types
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to "true")).value, equalTo(true))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to "false")).value, equalTo(false))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to "True")).value, equalTo(true))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to "False")).value, equalTo(false))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to 1)).value, equalTo(true))
assertThat<Boolean>(fromJson<BooleanModel>(jsonString("value" to 0)).value, equalTo(false))
}
@JsonSerializable
data class BooleanModel(val value: Boolean)
@Test
fun deserializeMixedBoolean() {
val correct = true
val incorrectObject = JSONObject()
val incorrectString = "string"
val correctMatcher = equalTo(true)
// correct
jsonString("nullable" to correct,
"nonNull" to correct)
.toModel<MixedBooleanModel>()
.also {
it.nullable.assert(correctMatcher)
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectObject,
"nonNull" to correct)
.toModel<MixedBooleanModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// incorrect type
jsonString("nullable" to incorrectString,
"nonNull" to correct)
.toModel<MixedBooleanModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// null
jsonString("nullable" to null,
"nonNull" to correct)
.toModel<MixedBooleanModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
// not set
jsonString("nonNull" to correct)
.toModel<MixedBooleanModel>()
.also {
it.nullable.assert(nullValue())
it.nonNull.assert(correctMatcher)
}
}
@JsonSerializable
data class MixedBooleanModel(
val nullable: Boolean?,
var nonNull: Boolean?)
@Test
fun deserializeNested() {
val json = jsonString("parent" to json("child" to null))
// Strict parent with strict child.
// Parsing should fail
assertThat(throwsException { fromJson<StrictParentStrictChild>(json) },
instanceOf<JsonGracefulException>())
// Strict parent with graceful child
// Child should fail gracefully but leaving parent continue to work
val result2 = fromJson<StrictParentGracefulChild>(json)
assertThat(result2, notNullValue())
assertThat<StrictParentGracefulChild.Parent>(result2.parent, notNullValue())
assertThat<String>(result2.parent.child, nullValue())
// Graceful parent with strict child
// The failure of child should result in the parent failing gracefully
val result3 = fromJson<GracefulParentStrictChild>(json)
assertThat(result3, notNullValue())
assertThat<GracefulParentStrictChild.Parent>(result3.parent, nullValue())
// Graceful parent with graceful child
// Child should fail gracefully but leaving parent continue to work
val result4 = fromJson<GracefulParentGracefulChild>(json)
assertThat(result4, notNullValue())
assertThat<GracefulParentGracefulChild.Parent>(result4.parent, notNullValue())
assertThat<String>(result4.parent!!.child, nullValue())
}
@JsonSerializable
class StrictParentStrictChild(val parent: Parent) {
@JsonSerializable
class Parent(val child: String)
}
@JsonSerializable
class StrictParentGracefulChild(val parent: Parent) {
@JsonSerializable
class Parent(val child: String?)
}
@JsonSerializable
class GracefulParentStrictChild(val parent: Parent?) {
@JsonSerializable
class Parent(val child: String)
}
@JsonSerializable
class GracefulParentGracefulChild(val parent: Parent?) {
@JsonSerializable
class Parent(val child: String?)
}
@Test
fun deserializePartialObjectList() {
// second item is bad
val json = jsonString(
"list" to jsonArray(
json("value2" to json("value" to 1), "value" to 1),
json("value2" to json("value" to "bad"), "value" to 2),
json("value2" to json("value" to 3), "value" to 3)
)
)
val result = fromJson<PartialObjectList>(json)
// gracefully skips the second item
assertThat(result.list.size, equalTo(2))
assertThat(result.list[0].value, equalTo(1))
assertThat(result.list[0].value2.value, equalTo(1))
assertThat(result.list[1].value, equalTo(3))
assertThat(result.list[1].value2.value, equalTo(3))
}
@JsonSerializable
class PartialObjectList(val list: List<ListItem>) {
@JsonSerializable
class ListItem(val value: Int, val value2: IntModel)
}
@Test
fun deserializeFieldWithDeclaredDefault() {
val json = jsonString(
"intValue" to 2,
"stringValue" to "bar",
"boolValue" to true,
"listValue" to jsonArray(2)
)
val result = fromJson<FieldWithDeclaredDefault>(json)
assertThat(result.intValue, equalTo(2))
assertThat(result.stringValue, equalTo("bar"))
assertThat(result.boolValue, equalTo(true))
assertThat(result.listValue, equalTo(listOf(2)))
assertThat(result.defaultIntValue, equalTo(2))
assertThat(result.defaultStringValue, equalTo("bar"))
assertThat(result.defaultBoolValue, equalTo(true))
assertThat(result.listValue, equalTo(listOf(2)))
}
@JsonSerializable
data class FieldWithDeclaredDefault(
val intValue: Int = 1,
val stringValue: String = "foo",
val boolValue: Boolean = false,
var listValue: List<Int> = listOf(2),
val defaultIntValue: Int = 2,
val defaultStringValue: String = "bar",
val defaultBoolValue: Boolean = true,
val defaultListValue: List<Int> = listOf(2)
)
/*
This allow asserting multiple exceptions within a test
*/
private inline fun throwsException(call: () -> Any): Exception? {
var e: Exception? = null
try {
call()
} catch (ex: Exception) {
e = ex
}
return e
}
inline fun <reified T : Any?> T.assert(matcher: Matcher<T>, reason: String? = null) = assertThat(reason
?: "", this, matcher)
inline fun <reified T : Any> fromJson(json: String) = gson.fromJson<T>(json, T::class.java)
inline fun <reified T : Any> instanceOf() = CoreMatchers.instanceOf<Any>(T::class.java)
inline fun <reified T : Any> String.toModel() = fromJson<T>(this)
fun jsonArray(vararg objects: Any) = JSONArray(listOf(*objects))
fun json(vararg properties: Pair<String, Any?>) = JSONObject(mapOf(*properties))
fun jsonString(vararg properties: Pair<String, Any?>) = json(*properties).toString()
}
| 0
|
Java
|
0
| 0
|
a09a500ae68d10dca5610a7ada19f04290489e7f
| 36,501
|
StaticGson
|
Apache License 2.0
|
app/src/main/java/com/example/tracker/WaterDatabase.kt
|
Dcar0803
| 794,890,008
| false
|
{"Kotlin": 12529}
|
package com.example.tracker
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [WaterEntry::class], version = 1)
abstract class WaterDatabase : RoomDatabase() {
abstract fun waterEntryDao(): WaterEntryDao
companion object {
@Volatile
private var INSTANCE: WaterDatabase? = null
fun getInstance(context: Context): WaterDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
WaterDatabase::class.java,
"water_database"
).build()
INSTANCE = instance
}
return instance
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d6260b56dd779d5a1ea5ee59fb63750f4e30f6fb
| 918
|
Tracker
|
Apache License 2.0
|
bindings/gtk/gtk4/src/nativeMain/kotlin/org/gtkkn/bindings/gtk/ButtonsType.kt
|
gtk-kn
| 609,191,895
| false
|
{"Kotlin": 10448515, "Shell": 2740}
|
// This is a generated file. Do not modify.
package org.gtkkn.bindings.gtk
import org.gtkkn.native.gtk.GtkButtonsType
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_CANCEL
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_CLOSE
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_NONE
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_OK
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_OK_CANCEL
import org.gtkkn.native.gtk.GtkButtonsType.GTK_BUTTONS_YES_NO
/**
* Prebuilt sets of buttons for `GtkDialog`.
*
* If none of these choices are appropriate, simply use
* %GTK_BUTTONS_NONE and call [method@Gtk.Dialog.add_buttons].
*
* > Please note that %GTK_BUTTONS_OK, %GTK_BUTTONS_YES_NO
* > and %GTK_BUTTONS_OK_CANCEL are discouraged by the
* > [GNOME Human Interface Guidelines](http://library.gnome.org/devel/hig-book/stable/).
*/
public enum class ButtonsType(
public val nativeValue: GtkButtonsType,
) {
/**
* no buttons at all
*/
NONE(GTK_BUTTONS_NONE),
/**
* an OK button
*/
OK(GTK_BUTTONS_OK),
/**
* a Close button
*/
CLOSE(GTK_BUTTONS_CLOSE),
/**
* a Cancel button
*/
CANCEL(GTK_BUTTONS_CANCEL),
/**
* Yes and No buttons
*/
YES_NO(GTK_BUTTONS_YES_NO),
/**
* OK and Cancel buttons
*/
OK_CANCEL(GTK_BUTTONS_OK_CANCEL),
;
public companion object {
public fun fromNativeValue(nativeValue: GtkButtonsType): ButtonsType =
when (nativeValue) {
GTK_BUTTONS_NONE -> NONE
GTK_BUTTONS_OK -> OK
GTK_BUTTONS_CLOSE -> CLOSE
GTK_BUTTONS_CANCEL -> CANCEL
GTK_BUTTONS_YES_NO -> YES_NO
GTK_BUTTONS_OK_CANCEL -> OK_CANCEL
else -> error("invalid nativeValue")
}
}
}
| 0
|
Kotlin
|
0
| 13
|
c033c245f1501134c5b9b46212cd153c61f7efea
| 1,865
|
gtk-kn
|
Creative Commons Attribution 4.0 International
|
matrix/src/main/java/com/github/ch8n/matrix/matrix.kt
|
ch8n
| 557,463,156
| false
| null |
package com.github.ch8n.matrix
import java.util.function.Consumer
/***
* Fixed array doesn't have ability to add or remove elements
* it can only set and get data from array
*/
interface MatrixOperations<T> : Iterable<T> {
val rowsCount: Int
val columnsCount: Int
fun rows(row: Int): Array<T>
fun columns(columns: Int): Array<T>
fun get(row: Int, col: Int): T
fun set(row: Int, col: Int, value: T)
}
interface MatrixOpsAdvance<T> : MatrixOperations<T> {
// advance
fun plus(matrix: Matrix<T>)
fun minus(matrix: Matrix<T>)
fun cross(matrix: Matrix<T>)
fun dot(matrix: Matrix<T>)
fun transpose(matrix: Matrix<T>)
fun inverse(matrix: Matrix<T>)
}
val <T> MatrixOperations<T>.size get() = Pair(rowsCount, columnsCount)
class Matrix<T> private constructor(
override val rowsCount: Int,
override val columnsCount: Int,
initializer: (row: Int, col: Int) -> T
) : MatrixOperations<T> {
private val matrix = Array(rowsCount) { rowIndex ->
Array(columnsCount) { columnIndex ->
initializer.invoke(rowIndex, columnIndex) as Any
}
}
companion object {
fun <T> of(rows: Int, columns: Int, initializer: (row: Int, col: Int) -> T): Matrix<T> =
Matrix(rows, columns, initializer)
}
@Suppress("UNCHECKED_CAST")
override fun rows(row: Int): Array<T> {
return matrix.get(row) as Array<T>
}
@Suppress("UNCHECKED_CAST")
override fun columns(columns: Int): Array<T> {
return (0 until rowsCount)
.map { it to columns }
.map { matrix.get(it.first).get(it.second) }
.toTypedArray() as Array<T>
}
@Suppress("UNCHECKED_CAST")
override fun get(row: Int, col: Int): T {
return matrix.get(row).get(col) as T
}
override fun iterator(): Iterator<T> {
return MatrixIterator(
rows = rowsCount,
columns = columnsCount,
getItemAt = ::get
)
}
inline fun onEachIndexed(action: (rowIndex: Int, columnIndex: Int, value: T) -> Unit) {
(0 until rowsCount).forEach { rowIndex ->
(0 until columnsCount).forEach { columnIndex ->
action.invoke(rowIndex, columnIndex, get(rowIndex, columnIndex))
}
}
}
override fun set(row: Int, col: Int, value: T) {
matrix.get(row).set(col, value as Any)
}
override fun toString(): String {
return buildString {
matrix.forEach { column ->
column.forEach { element ->
append(" ~ $element ~")
}
append("\n")
}
}
}
}
fun <T> matrixOf(rows: Int, columns: Int, initializer: (row: Int, col: Int) -> T): Matrix<T> =
Matrix.of(rows, columns, initializer)
| 0
|
Kotlin
|
0
| 1
|
caddad1d31de1b49cc6c1e606d161b0639988be7
| 2,837
|
DataStructureKT
|
Adobe Glyph List License
|
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/components/KtPsiTypeProvider.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 78943108, "Java": 6823266, "Swift": 4063298, "C": 2609288, "C++": 1970234, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32312, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11748, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.components
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.types.KaType
import org.jetbrains.kotlin.analysis.api.types.KaTypeMappingMode
public abstract class KaPsiTypeProvider : KaSessionComponent() {
public abstract fun asPsiType(
type: KaType,
useSitePosition: PsiElement,
allowErrorTypes: Boolean,
mode: KaTypeMappingMode,
isAnnotationMethod: Boolean,
suppressWildcards: Boolean?,
preserveAnnotations: Boolean,
): PsiType?
public abstract fun asKaType(
psiType: PsiType,
useSitePosition: PsiElement,
): KaType?
}
public typealias KtPsiTypeProvider = KaPsiTypeProvider
public interface KaPsiTypeProviderMixIn : KaSessionMixIn {
/**
* Converts the given [KaType] to [PsiType] under [useSitePosition] context.
*
* Note: [PsiType] is JVM conception, so this method will return `null` for non-JVM platforms.
*
* @receiver type to convert
*
* @param useSitePosition is used to determine if the given [KaType] needs to be approximated.
* For instance, if the given type is local yet available in the same scope of use site,
* we can still use such a local type.
* Otherwise, e.g., exposed to public as a return type, the resulting type will be approximated accordingly.
*
* @param allowErrorTypes if **false** the result will be null in the case of an error type inside the [type][this].
* Erroneous types will be replaced with `error.NonExistentClass` type.
*
* @param suppressWildcards indicates whether wild cards in type arguments need to be suppressed or not,
* e.g., according to the annotation on the containing declarations.
* - `true` means they should be suppressed.
* - `false` means they should appear.
* - `null` is no-op by default, i.e., their suppression/appearance is determined by type annotations.
*
* @param preserveAnnotations if **true** the result [PsiType] will have converted annotations from the original [type][this]
*/
public fun KaType.asPsiType(
useSitePosition: PsiElement,
allowErrorTypes: Boolean,
mode: KaTypeMappingMode = KaTypeMappingMode.DEFAULT,
isAnnotationMethod: Boolean = false,
suppressWildcards: Boolean? = null,
preserveAnnotations: Boolean = true,
): PsiType? = withValidityAssertion {
analysisSession.psiTypeProvider.asPsiType(
type = this,
useSitePosition = useSitePosition,
allowErrorTypes = allowErrorTypes,
mode = mode,
isAnnotationMethod = isAnnotationMethod,
suppressWildcards = suppressWildcards,
preserveAnnotations = preserveAnnotations,
)
}
/**
* Converts given [PsiType] to [KaType].
*
* [useSitePosition] may be used to clarify how to resolve some parts of [PsiType].
* For instance, it can be used to collect type parameters and use them during the conversion.
*
* @receiver [PsiType] to be converted.
* @return The converted [KaType], or null if conversion is not possible e.g., [PsiType] is not resolved
*/
public fun PsiType.asKaType(useSitePosition: PsiElement): KaType? = withValidityAssertion {
analysisSession.psiTypeProvider.asKaType(this, useSitePosition)
}
public fun PsiType.asKtType(useSitePosition: PsiElement): KaType? = asKaType(useSitePosition)
}
public typealias KtPsiTypeProviderMixIn = KaPsiTypeProviderMixIn
| 180
|
Kotlin
|
5642
| 48,082
|
2742b94d9f4dbdb1064e65e05682cb2b0badf2fc
| 3,902
|
kotlin
|
Apache License 2.0
|
rxdownload3/src/main/java/zlc/season/rxdownload3/helper/HttpUtil.kt
|
dalmif
| 205,262,339
| false
| null |
package zlc.season.rxdownload3.helper
import okhttp3.internal.http.HttpHeaders
import retrofit2.Response
import java.util.regex.Pattern
fun isChunked(response: Response<*>): Boolean {
return "chunked" == transferEncoding(response)
}
fun isSupportRange(resp: Response<*>): Boolean {
if (!resp.isSuccessful) {
return false
}
if (resp.code() == 206 || contentRange(resp).isNotEmpty() || acceptRanges(resp).isNotEmpty()) {
return true
}
return false
}
fun fileName(saveName: String, url: String, response: Response<*>): String {
if (saveName.isNotEmpty()) {
return saveName
}
var fileName = contentDisposition(response)
if (fileName.isEmpty()) {
fileName = substringUrl(url)
}
return fileName
}
fun substringUrl(url: String): String {
return url.substring(url.lastIndexOf('/') + 1)
}
fun contentDisposition(response: Response<*>): String {
val disposition = response.headers().get("Content-Disposition")
if (disposition == null || disposition.isEmpty()) {
return ""
}
val matcher = Pattern.compile(".*filename=(.*)").matcher(disposition.toLowerCase())
if (!matcher.find()) {
return ""
}
var result = matcher.group(1)
if (result.startsWith("\"")) {
result = result.substring(1)
}
if (result.endsWith("\"")) {
result = result.substring(0, result.length - 1)
}
result = result.replace("/", "_", false)
return result
}
fun contentLength(response: Response<*>): Long {
return HttpHeaders.contentLength(response.headers())
}
private fun transferEncoding(response: Response<*>): String? {
var header = response.headers().get("Transfer-Encoding")
if (header == null) {
header = ""
}
return header
}
fun getTotalSize(response: Response<*>): Long {
val contentRange = contentRange(response)
val tmp = contentRange.substringAfterLast('/')
return tmp.toLong()
}
private fun contentRange(response: Response<*>): String {
var header = response.headers().get("Content-Range")
if (header == null) {
header = ""
}
return header
}
private fun acceptRanges(response: Response<*>): String {
var header = response.headers().get("Accept-Ranges")
if (header == null) {
header = ""
}
return header
}
| 1
| null |
1
| 2
|
fd6ccfc144008a145aba6a37bcc1d045a2ba0c93
| 2,347
|
RxDownload
|
Apache License 2.0
|
hideout-core/src/main/kotlin/dev/usbharu/hideout/core/config/FlywayConfig.kt
|
usbharu
| 627,026,893
| false
|
{"Kotlin": 1314674, "Mustache": 111758, "HTML": 22697, "Dockerfile": 121}
|
/*
* Copyright (C) 2024 usbharu
*
* 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 dev.usbharu.hideout.core.config
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class FlywayConfig {
@Bean
fun cleanMigrateStrategy(): FlywayMigrationStrategy {
return FlywayMigrationStrategy { migrate ->
migrate.repair()
migrate.migrate()
}
}
}
| 18
|
Kotlin
|
0
| 13
|
32483abfe0e8e0458b5339887489c31bb62ad111
| 1,060
|
Hideout
|
Apache License 2.0
|
src/main/kotlin/dev/vini2003/hammer/common/timer/Timer.kt
|
vini2003
| 377,156,946
| false
| null |
package dev.vini2003.hammer.common.timer
class Timer(private val totalDuration: Long) {
private var remainingDuration: Long = totalDuration
private val action: (() -> Unit)? = null
fun update() {
if (remainingDuration > 0) {
remainingDuration -= 1
} else {
action?.invoke()
remainingDuration = totalDuration
}
}
fun reset() {
remainingDuration = totalDuration
}
}
| 0
|
Kotlin
|
1
| 0
|
ddba2a06ae75a6f30b2c08ba46c249281841c1a9
| 397
|
Blade
|
MIT License
|
src/main/kotlin/ar/edu/unq/modelo/Admin.kt
|
CristianGonzalez1980
| 340,727,280
| false
|
{"HTML": 1029458, "Kotlin": 208151, "JavaScript": 63660, "Gherkin": 25692, "CSS": 4371}
|
package ar.edu.unq.modelo
class Admin : ModelObjectWithBsonId {
var userName : String = ""
var password : String = ""
constructor()
constructor(
userName: String,
password: String
) {
this.userName = userName
this.password = <PASSWORD>
}
// override fun castearAMiTipo(other: Any): Admin {
// return other as Admin
// }
}
| 0
|
HTML
|
0
| 0
|
92ff7629378d46529905f73a79bd40dca1ba7fbc
| 400
|
sietelotos-bk
|
The Unlicense
|
app/src/main/java/com/muratozturk/breakingbad/domain/use_case/character_list/GetCharactersUseCase.kt
|
muratozturk5
| 559,985,666
| false
|
{"Kotlin": 36465}
|
package com.muratozturk.breakingbad.domain.use_case.character_list
import com.muratozturk.breakingbad.domain.repository.BreakingBadRepository
import javax.inject.Inject
class GetCharactersUseCase @Inject constructor(
private val repository: BreakingBadRepository
) {
suspend operator fun invoke() = repository.getCharacters()
}
| 0
|
Kotlin
|
3
| 13
|
e36da837b61e5f849e8d17252960382248124785
| 339
|
Breaking-Bad
|
MIT License
|
fragment/fragment/src/androidTest/java/androidx/fragment/app/SafeTransactionInOnResumeTest.kt
|
RikkaW
| 389,105,112
| false
| null |
/*
* Copyright 2018 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 androidx.fragment.app
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class SafeTransactionInOnResumeTest {
@Suppress("DEPRECATION")
var activityRule = androidx.test.rule.ActivityTestRule<OnResumeTestActivity>(
OnResumeTestActivity::class.java
)
// Detect leaks BEFORE and AFTER activity is destroyed
@get:Rule
val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess())
.around(activityRule)
@Test
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.M)
fun onResumeTest() {
assertTrue(activityRule.activity.testResult())
}
}
class DialogActivity : Activity() {
companion object {
private var dialogActivity: Activity? = null
fun finish() {
dialogActivity!!.finish()
dialogActivity = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dialogActivity = this
}
}
class OnResumeTestActivity : FragmentActivity() {
private var firstResume = true
private val testFinishedLatch = CountDownLatch(1)
private var testSuccess = false
override fun onResume() {
super.onResume()
if (firstResume) {
firstResume = false
startActivity(Intent(this, DialogActivity::class.java))
} else {
testSuccess = !supportFragmentManager.isStateSaved
testFinishedLatch.countDown()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
DialogActivity.finish()
}
fun testResult() = testFinishedLatch.await(1, TimeUnit.MINUTES) && testSuccess
}
| 8
| null |
937
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 2,824
|
androidx
|
Apache License 2.0
|
key-manager-grpc/src/main/kotlin/br/com/zup/edu/chavePix/cadastraChavePix/ChavePixExtension.kt
|
Werliney
| 385,941,758
| true
|
{"Kotlin": 57013}
|
package br.com.zup.edu.chavePix.cadastraChavePix
import br.com.zup.edu.CadastraChavePixRequest
import br.com.zup.edu.chavePix.TipoChaveData
import br.com.zup.edu.chavePix.TipoContaData
fun CadastraChavePixRequest.toModel(): ChavePixRequest {
return ChavePixRequest(
idCliente = idCliente,
tipoChave = TipoChaveData.valueOf(tipoChave.name),
valorChave = valorChave,
tipoConta = TipoContaData.valueOf(tipoConta.name)
)
}
| 0
|
Kotlin
|
0
| 0
|
6fe67ad78624a4ff11756160c0e5408fd40388bb
| 459
|
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
app/src/main/java/com/bejussi/tipcalculator/presentation/history/HistoryViewModel.kt
|
Bejussi
| 624,548,452
| false
| null |
package com.bejussi.tipcalculator.presentation.history
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bejussi.tipcalculator.R
import com.bejussi.tipcalculator.core.StringResourcesProvider
import com.bejussi.tipcalculator.domain.tip.TipRepository
import com.bejussi.tipcalculator.presentation.core.UIEvent
import com.bejussi.tipcalculator.presentation.history.model.HistoryTipEvent
import com.bejussi.tipcalculator.presentation.history.model.HistoryTipState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HistoryViewModel @Inject constructor(
private val repository: TipRepository,
private val stringResourcesProvider: StringResourcesProvider
) : ViewModel() {
private val _state = MutableStateFlow(HistoryTipState())
val state = _state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000),HistoryTipState())
private val _event = Channel<UIEvent>()
val event = _event.receiveAsFlow()
init {
onEvent(HistoryTipEvent.CancelSearchTip)
}
fun onEvent(event: HistoryTipEvent) {
when (event) {
is HistoryTipEvent.SearchTip -> {
viewModelScope.launch {
repository.getTipsByDate(event.date).collect {
if (it.isEmpty()) {
_event.send(
UIEvent.ShowToast(
message = stringResourcesProvider.getString(R.string.empty_date_list)
)
)
} else {
_state.emit(
HistoryTipState(
tipList = it,
cancelVisibility = true,
isEmptyList = it.isEmpty()
)
)
}
}
}
}
is HistoryTipEvent.CancelSearchTip -> {
viewModelScope.launch {
repository.getAllTips().collect {
_state.emit(
HistoryTipState(
tipList = it,
cancelVisibility = false,
isEmptyList = it.isEmpty()
)
)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d8a3571ac452ad5886da744d2d5af7788c7aee82
| 2,673
|
TipCalculator
|
MIT License
|
client/src/main/kotlin/io/github/matrixkt/models/events/contents/room/TopicContent.kt
|
bitcard
| 286,144,032
| true
|
{"Kotlin": 792100}
|
package io.github.matrixkt.models.events.contents.room
import io.github.matrixkt.models.events.contents.Content
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A topic is a short message detailing what is currently being discussed in the room.
* It can also be used as a way to display extra information about the room, which may not be suitable for the room name.
* The room topic can also be set when creating a room using `/createRoom` with the `topic` key.
*/
@SerialName("m.room.topic")
@Serializable
data class TopicContent(
/**
* The topic text.
*/
val topic: String
) : Content()
| 0
| null |
0
| 0
|
ce8a51bf838cf4793814e9148991edc1bb93808f
| 652
|
matrix-kt
|
Apache License 2.0
|
Estudos Kotlin/src/main/kotlin/estudos/challenges/ParkingChallenge.kt
|
estherwl
| 468,801,558
| false
|
{"Kotlin": 22413}
|
package estudos.challenges
/* You are making a car parking software that needs to calculate and output the amount due
based on the number of hours the car was parked.
The fee is calculated based on the following price structure:
- the first 5 hours are billed at $1 per hour.
- after that, each hour is billed at $0.5 per hour.
- for each 24 hours, there is a flat fee of $15. */
fun main(args: Array<String>) {
var hours = readLine()!!.toInt()
var total: Double = 0.0
if(hours >= 24){
total = ((hours%24)*0.5) + (15 * (hours/24))
} else if(hours <= 5) {
total += hours
} else if(hours in 6 until 24){
total += (hours - 5) * 0.5 + 5
}
print(total)
// total = when{
// hours in 1..5 -> hours*1.0
// hours in 6..23 -> ((hours-5)*0.5)+5
// hours>=24 -> ((hours%24)*0.5) + (15 * (hours/24))
// else -> 0.0
// }
// println(total)
}
| 0
|
Kotlin
|
0
| 0
|
e1ef5929ead72240a13bf59dd5cbe6f935b2645e
| 920
|
Estudos-Kotlin
|
MIT License
|
plugins/amazonq/codewhisperer/jetbrains-community/tst/software/aws/toolkits/jetbrains/services/codewhisperer/CodeWhispererServiceTest.kt
|
aws
| 91,485,909
| false
| null |
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.codewhisperer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.psi.PsiFile
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.replaceService
import com.intellij.testFramework.runInEdtAndWait
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import software.amazon.awssdk.services.codewhispererruntime.model.FileContext
import software.amazon.awssdk.services.codewhispererruntime.model.GenerateCompletionsRequest
import software.amazon.awssdk.services.codewhispererruntime.model.ProgrammingLanguage
import software.amazon.awssdk.services.codewhispererruntime.model.SupplementalContext
import software.aws.toolkits.jetbrains.core.credentials.AwsConnectionManager
import software.aws.toolkits.jetbrains.core.credentials.ToolkitConnectionManager
import software.aws.toolkits.jetbrains.services.codewhisperer.credentials.CodeWhispererClientAdaptor
import software.aws.toolkits.jetbrains.services.codewhisperer.customization.CodeWhispererCustomization
import software.aws.toolkits.jetbrains.services.codewhisperer.customization.CodeWhispererModelConfigurator
import software.aws.toolkits.jetbrains.services.codewhisperer.language.CodeWhispererProgrammingLanguage
import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererJava
import software.aws.toolkits.jetbrains.services.codewhisperer.model.CaretPosition
import software.aws.toolkits.jetbrains.services.codewhisperer.model.Chunk
import software.aws.toolkits.jetbrains.services.codewhisperer.model.FileContextInfo
import software.aws.toolkits.jetbrains.services.codewhisperer.model.LatencyContext
import software.aws.toolkits.jetbrains.services.codewhisperer.model.SupplementalContextInfo
import software.aws.toolkits.jetbrains.services.codewhisperer.model.TriggerTypeInfo
import software.aws.toolkits.jetbrains.services.codewhisperer.popup.CodeWhispererPopupManager
import software.aws.toolkits.jetbrains.services.codewhisperer.service.CodeWhispererAutomatedTriggerType
import software.aws.toolkits.jetbrains.services.codewhisperer.service.CodeWhispererService
import software.aws.toolkits.jetbrains.services.codewhisperer.service.RequestContext
import software.aws.toolkits.jetbrains.services.codewhisperer.telemetry.CodeWhispererTelemetryService
import software.aws.toolkits.jetbrains.services.codewhisperer.util.FileContextProvider
import software.aws.toolkits.jetbrains.utils.rules.JavaCodeInsightTestFixtureRule
import software.aws.toolkits.telemetry.CodewhispererTriggerType
class CodeWhispererServiceTest {
@Rule
@JvmField
val projectRule = JavaCodeInsightTestFixtureRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
private lateinit var sut: CodeWhispererService
private lateinit var customizationConfig: CodeWhispererModelConfigurator
private lateinit var clientFacade: CodeWhispererClientAdaptor
private lateinit var popupManager: CodeWhispererPopupManager
private lateinit var telemetryService: CodeWhispererTelemetryService
private lateinit var mockPopup: JBPopup
private lateinit var file: PsiFile
@Before
fun setUp() {
sut = CodeWhispererService.getInstance()
customizationConfig = mock()
clientFacade = mock()
mockPopup = mock<JBPopup>()
popupManager = mock {
on { initPopup() } doReturn mockPopup
}
telemetryService = mock()
file = projectRule.fixture.addFileToProject("main.java", "public class Main {}")
runInEdtAndWait {
projectRule.fixture.openFileInEditor(file.virtualFile)
}
ApplicationManager.getApplication().replaceService(CodeWhispererModelConfigurator::class.java, customizationConfig, disposableRule.disposable)
ApplicationManager.getApplication().replaceService(CodeWhispererTelemetryService::class.java, telemetryService, disposableRule.disposable)
ApplicationManager.getApplication().replaceService(CodeWhispererPopupManager::class.java, popupManager, disposableRule.disposable)
projectRule.project.replaceService(CodeWhispererClientAdaptor::class.java, clientFacade, disposableRule.disposable)
projectRule.project.replaceService(AwsConnectionManager::class.java, mock(), disposableRule.disposable)
}
@Test
fun `getRequestContext should have supplementalContext and customizatioArn if they're present`() {
whenever(customizationConfig.activeCustomization(projectRule.project)).thenReturn(
CodeWhispererCustomization(
"fake-arn",
"fake-name",
""
)
)
val mockSupplementalContext = aSupplementalContextInfo(
myContents = listOf(
Chunk(content = "foo", path = "/foo.java"),
Chunk(content = "bar", path = "/bar.java"),
Chunk(content = "baz", path = "/baz.java")
),
myIsUtg = false,
myLatency = 50L
)
val mockFileContextProvider = mock<FileContextProvider> {
on { this.extractFileContext(any(), any()) } doReturn aFileContextInfo()
onBlocking { this.extractSupplementalFileContext(any(), any(), any()) } doReturn mockSupplementalContext
}
projectRule.project.replaceService(FileContextProvider::class.java, mockFileContextProvider, disposableRule.disposable)
val actual = sut.getRequestContext(
TriggerTypeInfo(CodewhispererTriggerType.OnDemand, CodeWhispererAutomatedTriggerType.Unknown()),
projectRule.fixture.editor,
projectRule.project,
file,
LatencyContext()
)
runTest {
actual.awaitSupplementalContext()
}
assertThat(actual.customizationArn).isEqualTo("fake-arn")
assertThat(actual.supplementalContext).isEqualTo(mockSupplementalContext)
}
@Ignore("need update language type since Java is fully supported")
@Test
fun `getRequestContext - cross file context should be empty for non-cross-file user group`() {
val file = projectRule.fixture.addFileToProject("main.java", "public class Main {}")
runInEdtAndWait {
projectRule.fixture.openFileInEditor(file.virtualFile)
}
val actual = sut.getRequestContext(
TriggerTypeInfo(CodewhispererTriggerType.OnDemand, CodeWhispererAutomatedTriggerType.Unknown()),
projectRule.fixture.editor,
projectRule.project,
file,
LatencyContext()
)
assertThat(actual.supplementalContext).isNotNull
assertThat(actual.supplementalContext?.contents).isEmpty()
assertThat(actual.supplementalContext?.contentLength).isEqualTo(0)
}
@Test
fun `given request context, should invoke service API with correct args and await supplemental context deferred`() = runTest {
val mockFileContext = aFileContextInfo(CodeWhispererJava.INSTANCE)
val mockSupContext = spy(
aSupplementalContextInfo(
myContents = listOf(
Chunk(content = "foo", path = "/foo.java"),
Chunk(content = "bar", path = "/bar.java"),
Chunk(content = "baz", path = "/baz.java")
),
myIsUtg = false,
myLatency = 50L
)
)
val mockRequestContext = spy(
RequestContext(
project = projectRule.project,
editor = projectRule.fixture.editor,
triggerTypeInfo = TriggerTypeInfo(CodewhispererTriggerType.AutoTrigger, CodeWhispererAutomatedTriggerType.Enter()),
caretPosition = CaretPosition(0, 0),
fileContextInfo = mockFileContext,
supplementalContextDeferred = async { mockSupContext },
connection = ToolkitConnectionManager.getInstance(projectRule.project).activeConnection(),
latencyContext = LatencyContext(),
customizationArn = "fake-arn"
)
)
sut.invokeCodeWhispererInBackground(mockRequestContext).join()
verify(mockRequestContext, times(1)).awaitSupplementalContext()
verify(clientFacade).generateCompletionsPaginator(any())
argumentCaptor<GenerateCompletionsRequest> {
verify(clientFacade).generateCompletionsPaginator(capture())
assertThat(firstValue.customizationArn()).isEqualTo("fake-arn")
assertThat(firstValue.fileContext()).isEqualTo(mockFileContext.toSdkModel())
assertThat(firstValue.supplementalContexts()).hasSameSizeAs(mockSupContext.contents)
assertThat(firstValue.supplementalContexts()).isEqualTo(mockSupContext.toSdkModel())
}
}
}
private fun CodeWhispererProgrammingLanguage.toSdkModel(): ProgrammingLanguage = ProgrammingLanguage.builder()
.languageName(toCodeWhispererRuntimeLanguage().languageId)
.build()
private fun FileContextInfo.toSdkModel(): FileContext = FileContext.builder()
.filename(fileRelativePath)
.programmingLanguage(programmingLanguage.toCodeWhispererRuntimeLanguage().toSdkModel())
.leftFileContent(caretContext.leftFileContext)
.rightFileContent(caretContext.rightFileContext)
.build()
private fun SupplementalContextInfo.toSdkModel(): List<SupplementalContext> = contents.map {
SupplementalContext.builder()
.content(it.content)
.filePath(it.path)
.build()
}
| 519
| null |
220
| 757
|
a81caf64a293b59056cef3f8a6f1c977be46937e
| 10,192
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
HW1/app/src/main/java/com/example/hw1_template/TaskItem.kt
|
abbyoutsider
| 787,688,802
| false
|
{"Kotlin": 18881}
|
package com.example.hw1_template
import java.io.Serializable
// TaskItem: Represents the data structure for a task in your to-do list.
// IMPORTANT: This class must be well-defined; it's the blueprint for your task data.
// Add more fields as necessary, like dueDate, priority, etc.
data class TaskItem(
val id: Int,
var title: String,
var description: String,
var time: String,
var status: TaskStatus = TaskStatus.PENDING
) : Serializable
enum class TaskStatus {
PENDING,
COMPLETE
}
| 0
|
Kotlin
|
0
| 0
|
cbc411a820e292740e723021b54fa761a063ff3b
| 514
|
kotlin
|
MIT License
|
src/main/kotlin/org/jdc/template/datasource/database/main/individual/Individual.kt
|
lethalskillzz
| 115,807,551
| true
|
{"Kotlin": 114049, "Java": 3829}
|
package org.jdc.template.datasource.database.main.individual
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import org.jdc.template.datasource.database.main.type.IndividualType
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
@Entity(tableName = "individual")
class Individual {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
var householdId: Long = 0
var individualType: IndividualType = IndividualType.HEAD
var firstName: String = ""
var lastName: String = ""
var birthDate: LocalDate? = null
var alarmTime: LocalTime = LocalTime.now()
var lastModified: LocalDateTime = LocalDateTime.now()
var phone: String = ""
var email: String = ""
var available: Boolean = false
/**
* HTTP URL of PNG picture.
*/
var profilePicture: String = ""
fun getFullName() = "$firstName $lastName"
}
| 0
|
Kotlin
|
0
| 1
|
fb19980f455eefb957ae12d40b53baadc3729f38
| 955
|
android-template
|
Apache License 2.0
|
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/CustomDetektReport.kt
|
niraj8
| 272,693,530
| true
|
{"Kotlin": 1852830, "HTML": 4183, "Groovy": 2423}
|
package io.gitlab.arturbosch.detekt.extensions
import io.gitlab.arturbosch.detekt.internal.fileProperty
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputFile
import java.io.File
class CustomDetektReport(private val project: Project) {
@Internal
val reportIdProp: Property<String> = project.objects.property(String::class.java)
var reportId: String
get() = reportIdProp.get()
set(value) = reportIdProp.set(value)
@OutputFile
val destinationProperty: RegularFileProperty = project.fileProperty()
var destination: File
get() = destinationProperty.get().asFile
set(value) = destinationProperty.set(value)
override fun toString(): String {
return "CustomDetektReport(reportId=$reportId, destination=$destination)"
}
}
| 0
|
Kotlin
|
0
| 1
|
8536e848ec2d4470c970442a8ea4579937b4b2d8
| 929
|
detekt
|
Apache License 2.0
|
app/src/main/java/com/diegomalone/bookgoals/ui/progress/ProgressActivity.kt
|
diegomalone
| 117,601,360
| false
| null |
package com.diegomalone.bookgoals.ui.progress
import android.os.Bundle
import com.diegomalone.bookgoals.R
import com.diegomalone.bookgoals.base.BaseActivity
import com.diegomalone.bookgoals.data.model.Book
import com.diegomalone.bookgoals.extension.appComponent
import timber.log.Timber
import javax.inject.Inject
/**
* Created by Diego Malone on 15/01/18.
*/
class ProgressActivity : BaseActivity(), ProgressContract.View {
@Inject
lateinit var presenter: ProgressContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_progress)
appComponent.inject(this)
presenter.attachView(this)
presenter.getCurrentBook()
}
override fun showCurrentBookProgress(book: Book) {
Timber.i("Show book")
}
}
| 0
|
Kotlin
|
0
| 0
|
3e41aee8ce1c301fa527558d21d81d3892c048a1
| 854
|
KBookReadingGoals
|
Apache License 2.0
|
fashion-network/src/main/kotlin/com/aiuta/fashionsdk/network/internal/plugins/ApiKeyAuthenticationPlugin.kt
|
aiuta-com
| 759,918,511
| false
|
{"Kotlin": 644828, "Shell": 1462}
|
package com.aiuta.fashionsdk.network.internal.plugins
import io.ktor.client.plugins.auth.Auth
import io.ktor.client.plugins.auth.AuthProvider
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.header
import io.ktor.http.auth.HttpAuthHeader
internal fun Auth.apiKey(block: ApiKeyAuthConfig.() -> Unit) {
with(ApiKeyAuthConfig().apply(block)) {
this@apiKey.providers.add(ApiKeyAuthProvider(apiKey, sendWithoutRequest))
}
}
internal class ApiKeyAuthConfig {
internal lateinit var apiKey: String
internal var sendWithoutRequest: (HttpRequestBuilder) -> Boolean = { true }
fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean) {
this.sendWithoutRequest = block
}
fun setApiKey(apiKey: String) {
this.apiKey = apiKey
}
}
internal class ApiKeyAuthProvider(
private val apiKey: String,
private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean,
) : AuthProvider {
override val sendWithoutRequest: Boolean
get() = error("Deprecated")
override fun sendWithoutRequest(request: HttpRequestBuilder): Boolean {
return sendWithoutRequestCallback(request)
}
override fun isApplicable(auth: HttpAuthHeader): Boolean {
return auth.authScheme == HEADER_API_KEY
}
override suspend fun addRequestHeaders(
request: HttpRequestBuilder,
authHeader: HttpAuthHeader?,
) {
request.header(HEADER_API_KEY, apiKey)
}
private companion object {
const val HEADER_API_KEY = "x-api-key"
}
}
| 6
|
Kotlin
|
0
| 2
|
083f49b99e8b701ec134e56cf5f8e098cede04c2
| 1,579
|
android-sdk
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/CircleDashed.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.CircleDashed: ImageVector
get() {
if (_circleDashed != null) {
return _circleDashed!!
}
_circleDashed = Builder(name = "CircleDashed", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.41f, 19.74f)
lineToRelative(-1.54f, 2.58f)
curveToRelative(-1.72f, -1.03f, -3.17f, -2.48f, -4.19f, -4.19f)
lineToRelative(2.58f, -1.53f)
curveToRelative(0.77f, 1.29f, 1.86f, 2.38f, 3.15f, 3.15f)
close()
moveTo(19.74f, 7.41f)
lineToRelative(2.58f, -1.53f)
curveToRelative(-1.02f, -1.72f, -2.47f, -3.17f, -4.19f, -4.19f)
lineToRelative(-1.54f, 2.58f)
curveToRelative(1.29f, 0.77f, 2.38f, 1.86f, 3.15f, 3.15f)
close()
moveTo(1.68f, 5.87f)
lineToRelative(2.58f, 1.54f)
curveToRelative(0.77f, -1.29f, 1.86f, -2.38f, 3.15f, -3.15f)
lineToRelative(-1.53f, -2.58f)
curveToRelative(-1.72f, 1.02f, -3.17f, 2.47f, -4.19f, 4.19f)
close()
moveTo(3.0f, 12.0f)
curveToRelative(0.0f, -0.86f, 0.12f, -1.72f, 0.36f, -2.54f)
lineToRelative(-2.88f, -0.84f)
curveToRelative(-0.32f, 1.1f, -0.48f, 2.24f, -0.48f, 3.39f)
reflectiveCurveToRelative(0.16f, 2.29f, 0.48f, 3.39f)
lineToRelative(2.88f, -0.84f)
curveToRelative(-0.24f, -0.82f, -0.36f, -1.68f, -0.36f, -2.54f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-0.86f, 0.0f, -1.72f, -0.12f, -2.54f, -0.36f)
lineToRelative(-0.84f, 2.88f)
curveToRelative(1.1f, 0.32f, 2.24f, 0.48f, 3.39f, 0.48f)
reflectiveCurveToRelative(2.29f, -0.16f, 3.39f, -0.48f)
lineToRelative(-0.84f, -2.88f)
curveToRelative(-0.82f, 0.24f, -1.68f, 0.36f, -2.54f, 0.36f)
close()
moveTo(23.52f, 8.61f)
lineToRelative(-2.88f, 0.84f)
curveToRelative(0.24f, 0.82f, 0.36f, 1.68f, 0.36f, 2.54f)
reflectiveCurveToRelative(-0.12f, 1.72f, -0.36f, 2.54f)
lineToRelative(2.88f, 0.84f)
curveToRelative(0.32f, -1.1f, 0.48f, -2.24f, 0.48f, -3.39f)
reflectiveCurveToRelative(-0.16f, -2.29f, -0.48f, -3.39f)
close()
moveTo(16.6f, 19.74f)
lineToRelative(1.53f, 2.58f)
curveToRelative(1.72f, -1.02f, 3.17f, -2.47f, 4.19f, -4.19f)
lineToRelative(-2.58f, -1.54f)
curveToRelative(-0.77f, 1.29f, -1.86f, 2.38f, -3.15f, 3.15f)
close()
moveTo(8.61f, 0.48f)
lineToRelative(0.84f, 2.88f)
curveToRelative(0.82f, -0.24f, 1.68f, -0.36f, 2.54f, -0.36f)
reflectiveCurveToRelative(1.72f, 0.12f, 2.54f, 0.36f)
lineToRelative(0.84f, -2.88f)
curveToRelative(-1.1f, -0.32f, -2.24f, -0.48f, -3.39f, -0.48f)
reflectiveCurveToRelative(-2.29f, 0.16f, -3.39f, 0.48f)
close()
}
}
.build()
return _circleDashed!!
}
private var _circleDashed: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,273
|
icons
|
MIT License
|
app/src/main/java/dev/jianastrero/composefireworks/ext/DrawScope.kt
|
jianastrero
| 739,001,715
| false
|
{"Kotlin": 26344}
|
package dev.jianastrero.composefireworks.ext
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.dp
fun DrawScope.drawStar(color: Color, size: Float, center: Offset) {
val halfSize = size / 2
val quarterSize = size / 4
drawLine(
color = color,
start = center.copy(y = center.y - size),
end = center.copy(x = center.x + quarterSize, y = center.y - quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x + quarterSize, y = center.y - quarterSize),
end = center.copy(x = center.x + size, y = center.y - quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x + size, y = center.y - quarterSize),
end = center.copy(x = center.x + quarterSize, y = center.y + quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x + quarterSize, y = center.y + quarterSize),
end = center.copy(x = center.x + halfSize, y = center.y + size),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x + halfSize, y = center.y + size),
end = center.copy(y = center.y + quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(y = center.y + quarterSize),
end = center.copy(x = center.x - halfSize, y = center.y + size),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x - halfSize, y = center.y + size),
end = center.copy(x = center.x - quarterSize, y = center.y + quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x - quarterSize, y = center.y + quarterSize),
end = center.copy(x = center.x - size, y = center.y - quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x - size, y = center.y - quarterSize),
end = center.copy(x = center.x - quarterSize, y = center.y - quarterSize),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
drawLine(
color = color,
start = center.copy(x = center.x - quarterSize, y = center.y - quarterSize),
end = center.copy(y = center.y - size),
strokeWidth = 2.dp.toPx(),
cap = Stroke.DefaultCap
)
}
| 0
|
Kotlin
|
0
| 0
|
ab5e0dd13c48ddb64ab42db84f4494f9099f0054
| 2,993
|
compose-fireworks
|
MIT License
|
documentscanner/src/main/java/com/websitebeaver/documentscanner/extensions/Bitmap.kt
|
WebsiteBeaver
| 475,597,305
| false
| null |
package com.detectdocument.extensions
import android.graphics.Bitmap
import android.util.Base64
import java.io.ByteArrayOutputStream
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import kotlin.math.sqrt
/**
* This converts the bitmap to base64
*
* @return image as a base64 string
*/
fun Bitmap.toBase64(quality: Int): String {
val byteArrayOutputStream = ByteArrayOutputStream()
compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream)
return Base64.encodeToString(
byteArrayOutputStream.toByteArray(),
Base64.DEFAULT
)
}
/**
* This converts the bitmap to base64
*
* @param file the bitmap gets saved to this file
*/
fun Bitmap.saveToFile(file: File, quality: Int) {
val fileOutputStream = FileOutputStream(file)
compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream)
fileOutputStream.close()
}
/**
* This resizes the image, so that the byte count is a little less than targetBytes
*
* @param targetBytes the returned bitmap has a size a little less than targetBytes
*/
fun Bitmap.changeByteCountByResizing(targetBytes: Int): Bitmap {
val scale = sqrt(targetBytes.toDouble() / byteCount.toDouble())
return Bitmap.createScaledBitmap(
this,
(width * scale).toInt(),
(height * scale).toInt(),
true
)
}
| 9
| null |
38
| 47
|
58d58d576e5570c5391aee4a15cef6e793672a57
| 1,317
|
android-document-scanner
|
The Unlicense
|
src/main/kotlin/glm_/vec4/Vec4us.kt
|
kotlin-graphics
| 71,653,021
| false
| null |
package glm_.vec4
import glm_.*
import glm_.vec1.Vec1bool
import glm_.vec1.Vec1t
import glm_.vec2.Vec2bool
import glm_.vec2.Vec2t
import glm_.vec2.Vec2us
import glm_.vec3.Vec3bool
import glm_.vec3.Vec3t
import glm_.vec3.Vec3us
import glm_.vec4.operators.vec4us_operators
import kool.*
import unsigned.Ushort
import unsigned.UshortArray
import java.io.PrintStream
import java.nio.*
/**
* Created by elect on 09/10/16.
*/
class Vec4us(@JvmField var ofs: Int, var array: UshortArray) : Vec4t<Ushort>, ToShortBuffer {
inline var x: Ushort
get() = array[ofs]
set(value) = array.set(ofs, value)
inline var y: Ushort
get() = array[ofs + 1]
set(value) = array.set(ofs + 1, value)
inline var z: Ushort
get() = array[ofs + 2]
set(value) = array.set(ofs + 2, value)
inline var w: Ushort
get() = array[ofs + 3]
set(value) = array.set(ofs + 3, value)
inline var vX: Short
get() = array[ofs].toShort()
set(value) = array.set(ofs, value.us)
inline var vY: Short
get() = array[ofs + 1].toShort()
set(value) = array.set(ofs + 1, value.us)
inline var vZ: Short
get() = array[ofs + 2].toShort()
set(value) = array.set(ofs + 2, value.us)
inline var vW: Short
get() = array[ofs + 3].toShort()
set(value) = array.set(ofs + 3, value.us)
// -- Implicit basic constructors --
constructor() : this(0)
constructor(v: Vec4us) : this(v.x, v.y, v.z, v.w)
constructor(v: Vec3us) : this(v.x, v.y, v.z, Ushort(0))
constructor(v: Vec2us) : this(v.x, v.y, Ushort(0), Ushort(0))
// -- Explicit basic constructors --
constructor(x: Ushort) : this(x, x, x, x)
constructor(x: Ushort, y: Ushort, z: Ushort, w: Ushort) : this(0, UshortArray(shortArrayOf(x.v, y.v, z.v, w.v)))
constructor(x: Short) : this(x, x, x, x)
constructor(x: Short, y: Short, z: Short, w: Short) : this(0, UshortArray(shortArrayOf(x, y, z, w)))
// -- Conversion scalar constructors --
constructor(v: Vec1t<out Number>) : this(v._x)
// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification)
constructor(v: Number) : this(v.us)
constructor(x: Number, y: Number, z: Number, w: Number) : this(x.us, y.us, z.us, w.us)
constructor(x: Vec1t<out Number>, y: Number, z: Number, w: Number) : this(x._x, y, z, w)
constructor(x: Number, y: Vec1t<out Number>, z: Number, w: Number) : this(x, y._x, z, w)
constructor(x: Vec1t<out Number>, y: Vec1t<out Number>, z: Number, w: Number) : this(x._x, y._x, z, w)
constructor(x: Number, y: Number, z: Vec1t<out Number>, w: Number) : this(x, y, z._x, w)
constructor(x: Vec1t<out Number>, y: Number, z: Vec1t<out Number>, w: Number) : this(x._x, y, z._x, w)
constructor(x: Number, y: Vec1t<out Number>, z: Vec1t<out Number>, w: Number) : this(x, y._x, z._x, w)
constructor(x: Vec1t<out Number>, y: Vec1t<out Number>, z: Vec1t<out Number>, w: Number) : this(x._x, y._x, z._x, w)
constructor(x: Vec1t<out Number>, y: Number, z: Number, w: Vec1t<out Number>) : this(x._x, y, z, w._x)
constructor(x: Number, y: Vec1t<out Number>, z: Number, w: Vec1t<out Number>) : this(x, y._x, z, w._x)
constructor(x: Vec1t<out Number>, y: Vec1t<out Number>, z: Number, w: Vec1t<out Number>) : this(x._x, y._x, z, w._x)
constructor(x: Number, y: Number, z: Vec1t<out Number>, w: Vec1t<out Number>) : this(x, y, z._x, w._x)
constructor(x: Vec1t<out Number>, y: Number, z: Vec1t<out Number>, w: Vec1t<out Number>) : this(x._x, y, z._x, w._x)
constructor(x: Number, y: Vec1t<out Number>, z: Vec1t<out Number>, w: Vec1t<out Number>) : this(x, y._x, z._x, w._x)
constructor(x: Vec1t<out Number>, y: Vec1t<out Number>, z: Vec1t<out Number>, w: Vec1t<out Number>) : this(x._x, y._x, z._x, w._x)
constructor(xy: Vec2t<out Number>, z: Number, w: Number) : this(xy._x, xy._y, z, w)
constructor(xy: Vec2t<out Number>, z: Vec1t<out Number>, w: Number) : this(xy._x, xy._y, z._x, w)
constructor(xy: Vec2t<out Number>, z: Number, w: Vec1t<out Number>) : this(xy._x, xy._y, z, w._x)
constructor(xy: Vec2t<out Number>, z: Vec1t<out Number>, w: Vec1t<out Number>) : this(xy._x, xy._y, z._x, w._x)
constructor(x: Number, yz: Vec2t<out Number>, w: Number) : this(x, yz._x, yz._y, w)
constructor(x: Vec1t<out Number>, yz: Vec2t<out Number>, w: Number) : this(x._x, yz._x, yz._y, w)
constructor(x: Number, yz: Vec2t<out Number>, w: Vec1t<out Number>) : this(x, yz._x, yz._y, w._x)
constructor(x: Vec1t<out Number>, yz: Vec2t<out Number>, w: Vec1t<out Number>) : this(x._x, yz._x, yz._y, w._x)
constructor(x: Number, y: Number, zw: Vec2t<out Number>) : this(x, y, zw._x, zw._y)
constructor(x: Vec1t<out Number>, y: Number, zw: Vec2t<out Number>) : this(x._x, y, zw._x, zw._y)
constructor(x: Number, y: Vec1t<out Number>, zw: Vec2t<out Number>) : this(x, y, zw._x, zw._y)
constructor(x: Vec1t<out Number>, y: Vec1t<out Number>, zw: Vec2t<out Number>) : this(x._x, y._x, zw._x, zw._y)
constructor(xyz: Vec3t<out Number>, w: Number) : this(xyz._x, xyz._y, xyz._z, w)
constructor(xyz: Vec3t<out Number>, w: Vec1t<out Number>) : this(xyz._x, xyz._y, xyz._z, w._x)
constructor(x: Number, yzw: Vec3t<out Number>) : this(x, yzw._x, yzw._y, yzw._z)
constructor(x: Vec1t<out Number>, yzw: Vec3t<out Number>) : this(x._x, yzw._x, yzw._y, yzw._z)
constructor(xy: Vec2t<out Number>, zw: Vec2t<out Number>) : this(xy._x, xy._y, zw._x, zw._y)
constructor(v: Vec4t<out Number>) : this(v._x, v._y, v._z, v._w)
constructor(v: Vec1bool) : this(v.x.us, 0, 0, 1)
constructor(v: Vec2bool) : this(v.x.us, v.y.us, 0, 1)
constructor(v: Vec3bool) : this(v.x.us, v.y.us, v.z.us, 1)
constructor(v: Vec4bool) : this(v.x.us, v.y.us, v.z.us, v.w.us)
constructor(bytes: ByteArray, index: Int = 0, oneByteOneUshort: Boolean = false, bigEndian: Boolean = true) : this(
if (oneByteOneUshort) bytes[index].us else bytes.getUshort(index, bigEndian),
if (oneByteOneUshort) bytes[index + 1].us else bytes.getUshort(index + Ushort.BYTES, bigEndian),
if (oneByteOneUshort) bytes[index + 2].us else bytes.getUshort(index + Ushort.BYTES * 2, bigEndian),
if (oneByteOneUshort) bytes[index + 3].us else bytes.getUshort(index + Ushort.BYTES * 3, bigEndian))
constructor(chars: CharArray, index: Int = 0) : this(chars[index].us, chars[index + 1].us, chars[index + 2].us, chars[index + 3].us)
constructor(shorts: ShortArray, index: Int = 0) : this(shorts[index], shorts[index + 1], shorts[index + 2], shorts[index + 3])
constructor(ints: IntArray, index: Int = 0) : this(ints[index], ints[index + 1], ints[index + 2], ints[index + 3])
constructor(longs: LongArray, index: Int = 0) : this(longs[index], longs[index + 1], longs[index + 2], longs[index + 3])
constructor(floats: FloatArray, index: Int = 0) : this(floats[index], floats[index + 1], floats[index + 2], floats[index + 3])
constructor(doubles: DoubleArray, index: Int = 0) : this(doubles[index], doubles[index + 1], doubles[index + 2], doubles[index + 3])
constructor(booleans: BooleanArray, index: Int = 0) : this(booleans[index].us, booleans[index + 1].us, booleans[index + 2].us, booleans[index + 3].us)
constructor(numbers: Array<out Number>, index: Int = 0) : this(numbers[index], numbers[index + 1], numbers[index + 2], numbers[index + 3])
constructor(chars: Array<Char>, index: Int = 0) : this(chars[index].us, chars[index + 1].us, chars[index + 2].us, chars[index + 3].us)
constructor(booleans: Array<Boolean>, index: Int = 0) : this(booleans[index].us, booleans[index + 1].us, booleans[index + 2].us, booleans[index + 3].us)
constructor(list: Iterable<*>, index: Int = 0) : this(list.elementAt(index)!!.toShort, list.elementAt(index + 1)!!.toShort,
list.elementAt(index + 2)!!.toShort, list.elementAt(index + 3)!!.toShort)
constructor(bytes: ByteBuffer, index: Int = bytes.pos, oneByteOneUshort: Boolean = false) : this(
if (oneByteOneUshort) bytes[index].us else bytes.getShort(index).us,
if (oneByteOneUshort) bytes[index + 1].us else bytes.getShort(index + Ushort.BYTES).us,
if (oneByteOneUshort) bytes[index + 2].us else bytes.getShort(index + Ushort.BYTES * 2).us,
if (oneByteOneUshort) bytes[index + 3].us else bytes.getShort(index + Ushort.BYTES * 3).us)
constructor(chars: CharBuffer, index: Int = chars.pos) : this(chars[index].us, chars[index + 1].us, chars[index + 2].us, chars[index + 3].us)
constructor(shorts: ShortBuffer, index: Int = shorts.pos) : this(shorts[index], shorts[index + 1], shorts[index + 2], shorts[index + 3])
constructor(ints: IntBuffer, index: Int = ints.pos) : this(ints[index], ints[index + 1], ints[index + 2], ints[index + 3])
constructor(longs: LongBuffer, index: Int = longs.pos) : this(longs[index], longs[index + 1], longs[index + 2], longs[index + 3])
constructor(floats: FloatBuffer, index: Int = floats.pos) : this(floats[index], floats[index + 1], floats[index + 2], floats[index + 3])
constructor(doubles: DoubleBuffer, index: Int = doubles.pos) : this(doubles[index], doubles[index + 1], doubles[index + 2], doubles[index + 3])
constructor(block: (Int) -> Ushort) : this(block(0), block(1), block(2), block(3))
constructor(ptr: Ptr<Ushort>) : this() {
val p = ptr.toPtr<Short>()
x.v = p[0]
y.v = p[1]
z.v = p[2]
w.v = p[3]
}
fun set(bytes: ByteArray, index: Int = 0, oneByteOneShort: Boolean = false, bigEndian: Boolean = true) {
x.v = if (oneByteOneShort) bytes[index].s else bytes.getShort(index, bigEndian)
y.v = if (oneByteOneShort) bytes[index + 1].s else bytes.getShort(index + Ushort.BYTES, bigEndian)
z.v = if (oneByteOneShort) bytes[index + 2].s else bytes.getShort(index + Ushort.BYTES * 2, bigEndian)
w.v = if (oneByteOneShort) bytes[index + 3].s else bytes.getShort(index + Ushort.BYTES * 3, bigEndian)
}
fun set(bytes: ByteBuffer, index: Int = bytes.pos, oneByteOneShort: Boolean = false) {
x.v = if (oneByteOneShort) bytes[index].s else bytes.getShort(index)
y.v = if (oneByteOneShort) bytes[index + 1].s else bytes.getShort(index + Ushort.BYTES)
z.v = if (oneByteOneShort) bytes[index + 2].s else bytes.getShort(index + Ushort.BYTES * 2)
w.v = if (oneByteOneShort) bytes[index + 3].s else bytes.getShort(index + Ushort.BYTES * 3)
}
fun put(x: Ushort, y: Ushort, z: Ushort, w: Ushort) {
this.x = x
this.y = y
this.z = z
this.w = w
}
fun put(x: Short, y: Short, z: Short, w: Short) {
this.x.v = x
this.y.v = y
this.z.v = z
this.w.v = w
}
operator fun invoke(x: Ushort, y: Ushort, z: Ushort, w: Ushort): Vec4us {
this.x = x
this.y = y
this.z = z
this.w = w
return this
}
operator fun invoke(x: Short, y: Short, z: Short, w: Short): Vec4us {
this.x.v = x
this.y.v = y
this.z.v = z
this.w.v = w
return this
}
override fun put(x: Number, y: Number, z: Number, w: Number) {
this.x = x.us
this.y = y.us
this.z = z.us
this.w = w.us
}
override operator fun invoke(x: Number, y: Number, z: Number, w: Number): Vec4us {
this.x = x.us
this.y = y.us
this.z = z.us
this.w = w.us
return this
}
fun to(bytes: ByteArray, index: Int): ByteArray = to(bytes, index, true)
override fun to(bytes: ByteArray, index: Int, bigEndian: Boolean): ByteArray {
bytes.putShort(index, x.v, bigEndian)
bytes.putShort(index + Short.BYTES, y.v, bigEndian)
bytes.putShort(index + Short.BYTES * 2, z.v, bigEndian)
bytes.putShort(index + Short.BYTES * 3, w.v, bigEndian)
return bytes
}
fun toShortArray(): ShortArray = to(ShortArray(length), 0)
infix fun to(shorts: ShortArray): ShortArray = to(shorts, 0)
fun to(shorts: ShortArray, index: Int): ShortArray {
System.arraycopy(array, ofs, shorts, index, length)
return shorts
}
override fun to(buf: ByteBuffer, offset: Int): ByteBuffer {
buf.putShort(offset, x.v)
buf.putShort(offset + Short.BYTES, y.v)
buf.putShort(offset + Short.BYTES * 2, z.v)
buf.putShort(offset + Short.BYTES * 3, w.v)
return buf
}
override fun to(shorts: ShortBuffer, index: Int): ShortBuffer {
shorts[index] = x.v
shorts[index + 1] = y.v
shorts[index + 2] = z.v
shorts[index + 3] = w.v
return shorts
}
// -- Component accesses --
operator fun set(index: Int, value: Short) = when (index) {
0 -> x.v = value
1 -> y.v = value
2 -> z.v = value
3 -> w.v = value
else -> throw ArrayIndexOutOfBoundsException()
}
override operator fun set(index: Int, value: Number) = when (index) {
0 -> x = value.us
1 -> y = value.us
2 -> z = value.us
3 -> w = value.us
else -> throw ArrayIndexOutOfBoundsException()
}
// -- Unary arithmetic operators --
operator fun unaryPlus() = this
// no unaryMinus operator, only signed
// -- Increment main.and decrement operators --
operator fun inc(res: Vec4us = Vec4us()) = plus(res, this, 1, 1, 1, 1)
fun incAssign() = plus(this, this, 1, 1, 1, 1)
operator fun dec(res: Vec4us = Vec4us()) = minus(res, this, 1, 1, 1, 1)
fun decAssign() = minus(this, this, 1, 1, 1, 1)
// -- Specific binary arithmetic operators --
operator fun plus(b: Ushort) = plus(Vec4us(), this, b, b, b, b)
operator fun plus(b: Short) = plus(Vec4us(), this, b, b, b, b)
operator fun plus(b: Int) = plus(Vec4us(), this, b, b, b, b)
operator fun plus(b: Vec4us) = plus(Vec4us(), this, b.x, b.y, b.z, b.w)
fun plus(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us = Vec4us()) = plus(res, this, bX, bY, bZ, bW)
fun plus(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us = Vec4us()) = plus(res, this, bX, bY, bZ, bW)
fun plus(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us = Vec4us()) = plus(res, this, bX, bY, bZ, bW)
fun plus(b: Ushort, res: Vec4us = Vec4us()) = plus(res, this, b, b, b, b)
fun plus(b: Short, res: Vec4us = Vec4us()) = plus(res, this, b, b, b, b)
fun plus(b: Int, res: Vec4us = Vec4us()) = plus(res, this, b, b, b, b)
fun plus(b: Vec4us, res: Vec4us = Vec4us()) = plus(res, this, b.x, b.y, b.z, b.w)
fun plusAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = plus(this, this, bX, bY, bZ, bW)
fun plusAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = plus(this, this, bX, bY, bZ, bW)
fun plusAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = plus(this, this, bX, bY, bZ, bW)
infix operator fun plusAssign(b: Ushort) {
plus(this, this, b, b, b, b)
}
infix operator fun plusAssign(b: Short) {
plus(this, this, b, b, b, b)
}
infix operator fun plusAssign(b: Int) {
plus(this, this, b, b, b, b)
}
infix operator fun plusAssign(b: Vec4us) {
plus(this, this, b.x, b.y, b.z, b.w)
}
operator fun minus(b: Ushort) = minus(Vec4us(), this, b, b, b, b)
operator fun minus(b: Short) = minus(Vec4us(), this, b, b, b, b)
operator fun minus(b: Int) = minus(Vec4us(), this, b, b, b, b)
operator fun minus(b: Vec4us) = minus(Vec4us(), this, b.x, b.y, b.z, b.w)
fun minus(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us = Vec4us()) = minus(res, this, bX, bY, bZ, bW)
fun minus(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us = Vec4us()) = minus(res, this, bX, bY, bZ, bW)
fun minus(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us = Vec4us()) = minus(res, this, bX, bY, bZ, bW)
fun minus(b: Ushort, res: Vec4us = Vec4us()) = minus(res, this, b, b, b, b)
fun minus(b: Short, res: Vec4us = Vec4us()) = minus(res, this, b, b, b, b)
fun minus(b: Int, res: Vec4us = Vec4us()) = minus(res, this, b, b, b, b)
fun minus(b: Vec4us, res: Vec4us = Vec4us()) = minus(res, this, b.x, b.y, b.z, b.w)
fun minusAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = minus(this, this, bX, bY, bZ, bW)
fun minusAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = minus(this, this, bX, bY, bZ, bW)
fun minusAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = minus(this, this, bX, bY, bZ, bW)
infix operator fun minusAssign(b: Ushort) {
minus(this, this, b, b, b, b)
}
infix operator fun minusAssign(b: Short) {
minus(this, this, b, b, b, b)
}
infix operator fun minusAssign(b: Int) {
minus(this, this, b, b, b, b)
}
infix operator fun minusAssign(b: Vec4us) {
minus(this, this, b.x, b.y, b.z, b.w)
}
operator fun times(b: Ushort) = times(Vec4us(), this, b, b, b, b)
operator fun times(b: Short) = times(Vec4us(), this, b, b, b, b)
operator fun times(b: Int) = times(Vec4us(), this, b, b, b, b)
operator fun times(b: Vec4us) = times(Vec4us(), this, b.x, b.y, b.z, b.w)
fun times(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us = Vec4us()) = times(res, this, bX, bY, bZ, bW)
fun times(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us = Vec4us()) = times(res, this, bX, bY, bZ, bW)
fun times(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us = Vec4us()) = times(res, this, bX, bY, bZ, bW)
fun times(b: Ushort, res: Vec4us = Vec4us()) = times(res, this, b, b, b, b)
fun times(b: Short, res: Vec4us = Vec4us()) = times(res, this, b, b, b, b)
fun times(b: Int, res: Vec4us = Vec4us()) = times(res, this, b, b, b, b)
fun times(b: Vec4us, res: Vec4us = Vec4us()) = times(res, this, b.x, b.y, b.z, b.w)
fun timesAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = times(this, this, bX, bY, bZ, bW)
fun timesAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = times(this, this, bX, bY, bZ, bW)
fun timesAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = times(this, this, bX, bY, bZ, bW)
infix operator fun timesAssign(b: Ushort) {
times(this, this, b, b, b, b)
}
infix operator fun timesAssign(b: Short) {
times(this, this, b, b, b, b)
}
infix operator fun timesAssign(b: Int) {
times(this, this, b, b, b, b)
}
infix operator fun timesAssign(b: Vec4us) {
times(this, this, b.x, b.y, b.z, b.w)
}
operator fun div(b: Ushort) = div(Vec4us(), this, b, b, b, b)
operator fun div(b: Short) = div(Vec4us(), this, b, b, b, b)
operator fun div(b: Int) = div(Vec4us(), this, b, b, b, b)
operator fun div(b: Vec4us) = div(Vec4us(), this, b.x, b.y, b.z, b.w)
fun div(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us = Vec4us()) = div(res, this, bX, bY, bZ, bW)
fun div(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us = Vec4us()) = div(res, this, bX, bY, bZ, bW)
fun div(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us = Vec4us()) = div(res, this, bX, bY, bZ, bW)
fun div(b: Ushort, res: Vec4us = Vec4us()) = div(res, this, b, b, b, b)
fun div(b: Short, res: Vec4us = Vec4us()) = div(res, this, b, b, b, b)
fun div(b: Int, res: Vec4us = Vec4us()) = div(res, this, b, b, b, b)
fun div(b: Vec4us, res: Vec4us = Vec4us()) = div(res, this, b.x, b.y, b.z, b.w)
fun divAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = div(this, this, bX, bY, bZ, bW)
fun divAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = div(this, this, bX, bY, bZ, bW)
fun divAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = div(this, this, bX, bY, bZ, bW)
infix operator fun divAssign(b: Ushort) {
div(this, this, b, b, b, b)
}
infix operator fun divAssign(b: Short) {
div(this, this, b, b, b, b)
}
infix operator fun divAssign(b: Int) {
div(this, this, b, b, b, b)
}
infix operator fun divAssign(b: Vec4us) {
div(this, this, b.x, b.y, b.z, b.w)
}
operator fun rem(b: Ushort) = rem(Vec4us(), this, b, b, b, b)
operator fun rem(b: Short) = rem(Vec4us(), this, b, b, b, b)
operator fun rem(b: Int) = rem(Vec4us(), this, b, b, b, b)
operator fun rem(b: Vec4us) = rem(Vec4us(), this, b.x, b.y, b.z, b.w)
fun rem(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us = Vec4us()) = rem(res, this, bX, bY, bZ, bW)
fun rem(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us = Vec4us()) = rem(res, this, bX, bY, bZ, bW)
fun rem(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us = Vec4us()) = rem(res, this, bX, bY, bZ, bW)
fun rem(b: Ushort, res: Vec4us = Vec4us()) = rem(res, this, b, b, b, b)
fun rem(b: Short, res: Vec4us = Vec4us()) = rem(res, this, b, b, b, b)
fun rem(b: Int, res: Vec4us = Vec4us()) = rem(res, this, b, b, b, b)
fun rem(b: Vec4us, res: Vec4us = Vec4us()) = rem(res, this, b.x, b.y, b.z, b.w)
fun remAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = rem(this, this, bX, bY, bZ, bW)
fun remAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = rem(this, this, bX, bY, bZ, bW)
fun remAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = rem(this, this, bX, bY, bZ, bW)
infix operator fun remAssign(b: Ushort) {
rem(this, this, b, b, b, b)
}
infix operator fun remAssign(b: Short) {
rem(this, this, b, b, b, b)
}
infix operator fun remAssign(b: Int) {
rem(this, this, b, b, b, b)
}
infix operator fun remAssign(b: Vec4us) {
rem(this, this, b.x, b.y, b.z, b.w)
}
// -- Generic binary arithmetic operators --
operator fun plus(b: Number) = plus(Vec4us(), this, b.i, b.i, b.i, b.i)
operator fun plus(b: Vec4t<out Number>) = plus(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
fun plus(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us = Vec4us()) = plus(res, this, bX.i, bY.i, bZ.i, bW.i)
fun plus(b: Number, res: Vec4us = Vec4us()) = plus(res, this, b.i, b.i, b.i, b.i)
fun plus(b: Vec4t<out Number>, res: Vec4us = Vec4us()) = plus(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun plusAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = plus(this, this, bX.i, bY.i, bZ.i, bW.i)
infix operator fun plusAssign(b: Number) {
plus(this, this, b.i, b.i, b.i, b.i)
}
infix operator fun plusAssign(b: Vec4t<out Number>) {
plus(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
}
operator fun minus(b: Number) = minus(Vec4us(), this, b.i, b.i, b.i, b.i)
operator fun minus(b: Vec4t<out Number>) = minus(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
fun minus(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us = Vec4us()) = minus(res, this, bX.i, bY.i, bZ.i, bW.i)
fun minus(b: Number, res: Vec4us = Vec4us()) = minus(res, this, b.i, b.i, b.i, b.i)
fun minus(b: Vec4t<out Number>, res: Vec4us = Vec4us()) = minus(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun minusAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = minus(this, this, bX.i, bY.i, bZ.i, bW.i)
infix operator fun minusAssign(b: Number) {
minus(this, this, b.i, b.i, b.i, b.i)
}
infix operator fun minusAssign(b: Vec4t<out Number>) {
minus(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
}
operator fun times(b: Number) = times(Vec4us(), this, b.i, b.i, b.i, b.i)
operator fun times(b: Vec4t<out Number>) = times(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
fun times(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us = Vec4us()) = times(res, this, bX.i, bY.i, bZ.i, bW.i)
fun times(b: Number, res: Vec4us = Vec4us()) = times(res, this, b.i, b.i, b.i, b.i)
fun times(b: Vec4t<out Number>, res: Vec4us = Vec4us()) = times(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun timesAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = times(this, this, bX.i, bY.i, bZ.i, bW.i)
infix operator fun timesAssign(b: Number) {
times(this, this, b.i, b.i, b.i, b.i)
}
infix operator fun timesAssign(b: Vec4t<out Number>) {
times(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
}
operator fun div(b: Number) = div(Vec4us(), this, b.i, b.i, b.i, b.i)
operator fun div(b: Vec4t<out Number>) = div(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
fun div(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us = Vec4us()) = div(res, this, bX.i, bY.i, bZ.i, bW.i)
fun div(b: Number, res: Vec4us = Vec4us()) = div(res, this, b.i, b.i, b.i, b.i)
fun div(b: Vec4t<out Number>, res: Vec4us = Vec4us()) = div(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun divAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = div(this, this, bX.i, bY.i, bZ.i, bW.i)
infix operator fun divAssign(b: Number) {
div(this, this, b.i, b.i, b.i, b.i)
}
infix operator fun divAssign(b: Vec4t<out Number>) {
div(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
}
operator fun rem(b: Number) = rem(Vec4us(), this, b.i, b.i, b.i, b.i)
operator fun rem(b: Vec4t<out Number>) = rem(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
fun rem(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us = Vec4us()) = rem(res, this, bX.i, bY.i, bZ.i, bW.i)
fun rem(b: Number, res: Vec4us = Vec4us()) = rem(res, this, b.i, b.i, b.i, b.i)
fun rem(b: Vec4t<out Number>, res: Vec4us = Vec4us()) = rem(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun remAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = rem(this, this, bX.i, bY.i, bZ.i, bW.i)
infix operator fun remAssign(b: Number) {
rem(this, this, b.i, b.i, b.i, b.i)
}
infix operator fun remAssign(b: Vec4t<out Number>) {
rem(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
}
// -- Specific bitwise operators --
infix fun and(b: Ushort) = and(Vec4us(), this, b, b, b, b)
infix fun and(b: Short) = and(Vec4us(), this, b, b, b, b)
infix fun and(b: Int) = and(Vec4us(), this, b, b, b, b)
fun and(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = and(Vec4us(), this, bX, bY, bZ, bW)
fun and(bX: Short, bY: Short, bZ: Short, bW: Short) = and(Vec4us(), this, bX, bY, bZ, bW)
fun and(bX: Int, bY: Int, bZ: Int, bW: Int) = and(Vec4us(), this, bX, bY, bZ, bW)
fun and(b: Vec4us) = and(Vec4us(), this, b.x, b.y, b.z, b.w)
infix fun andAssign(b: Ushort) = and(this, this, b, b, b, b)
infix fun andAssign(b: Short) = and(this, this, b, b, b, b)
infix fun andAssign(b: Int) = and(this, this, b, b, b, b)
fun andAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = and(this, this, bX, bY, bZ, bW)
fun andAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = and(this, this, bX, bY, bZ, bW)
fun andAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = and(this, this, bX, bY, bZ, bW)
infix fun andAssign(b: Vec4us) = and(this, this, b.x, b.y, b.z, b.w)
fun and(b: Ushort, res: Vec4us) = and(res, this, b, b, b, b)
fun and(b: Short, res: Vec4us) = and(res, this, b, b, b, b)
fun and(b: Int, res: Vec4us) = and(res, this, b, b, b, b)
fun and(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us) = and(res, this, bX, bY, bZ, bW)
fun and(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us) = and(res, this, bX, bY, bZ, bW)
fun and(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us) = and(res, this, bX, bY, bZ, bW)
fun and(b: Vec4us, res: Vec4us) = and(res, this, b.x, b.y, b.z, b.w)
infix fun or(b: Ushort) = or(Vec4us(), this, b, b, b, b)
infix fun or(b: Short) = or(Vec4us(), this, b, b, b, b)
infix fun or(b: Int) = or(Vec4us(), this, b, b, b, b)
fun or(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = or(Vec4us(), this, bX, bY, bZ, bW)
fun or(bX: Short, bY: Short, bZ: Short, bW: Short) = or(Vec4us(), this, bX, bY, bZ, bW)
fun or(bX: Int, bY: Int, bZ: Int, bW: Int) = or(Vec4us(), this, bX, bY, bZ, bW)
fun or(b: Vec4us) = or(Vec4us(), this, b.x, b.y, b.z, b.w)
infix fun orAssign(b: Ushort) = or(this, this, b, b, b, b)
infix fun orAssign(b: Short) = or(this, this, b, b, b, b)
infix fun orAssign(b: Int) = or(this, this, b, b, b, b)
fun orAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = or(this, this, bX, bY, bZ, bW)
fun orAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = or(this, this, bX, bY, bZ, bW)
fun orAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = or(this, this, bX, bY, bZ, bW)
infix fun orAssign(b: Vec4us) = or(this, this, b.x, b.y, b.z, b.w)
fun or(b: Ushort, res: Vec4us) = or(res, this, b, b, b, b)
fun or(b: Short, res: Vec4us) = or(res, this, b, b, b, b)
fun or(b: Int, res: Vec4us) = or(res, this, b, b, b, b)
fun or(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us) = or(res, this, bX, bY, bZ, bW)
fun or(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us) = or(res, this, bX, bY, bZ, bW)
fun or(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us) = or(res, this, bX, bY, bZ, bW)
fun or(b: Vec4us, res: Vec4us) = or(res, this, b.x, b.y, b.z, b.w)
infix fun xor(b: Ushort) = xor(Vec4us(), this, b, b, b, b)
infix fun xor(b: Short) = xor(Vec4us(), this, b, b, b, b)
infix fun xor(b: Int) = xor(Vec4us(), this, b, b, b, b)
fun xor(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = xor(Vec4us(), this, bX, bY, bZ, bW)
fun xor(bX: Short, bY: Short, bZ: Short, bW: Short) = xor(Vec4us(), this, bX, bY, bZ, bW)
fun xor(bX: Int, bY: Int, bZ: Int, bW: Int) = xor(Vec4us(), this, bX, bY, bZ, bW)
fun xor(b: Vec4us) = xor(Vec4us(), this, b.x, b.y, b.z, b.w)
infix fun xorAssign(b: Ushort) = xor(this, this, b, b, b, b)
infix fun xorAssign(b: Short) = xor(this, this, b, b, b, b)
infix fun xorAssign(b: Int) = xor(this, this, b, b, b, b)
fun xorAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = xor(this, this, bX, bY, bZ, bW)
fun xorAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = xor(this, this, bX, bY, bZ, bW)
fun xorAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = xor(this, this, bX, bY, bZ, bW)
infix fun xorAssign(b: Vec4us) = xor(this, this, b.x, b.y, b.z, b.w)
fun xor(b: Ushort, res: Vec4us) = xor(res, this, b, b, b, b)
fun xor(b: Short, res: Vec4us) = xor(res, this, b, b, b, b)
fun xor(b: Int, res: Vec4us) = xor(res, this, b, b, b, b)
fun xor(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us) = xor(res, this, bX, bY, bZ, bW)
fun xor(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us) = xor(res, this, bX, bY, bZ, bW)
fun xor(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us) = xor(res, this, bX, bY, bZ, bW)
fun xor(b: Vec4us, res: Vec4us) = xor(res, this, b.x, b.y, b.z, b.w)
infix fun shl(b: Ushort) = shl(Vec4us(), this, b, b, b, b)
infix fun shl(b: Short) = shl(Vec4us(), this, b, b, b, b)
infix fun shl(b: Int) = shl(Vec4us(), this, b, b, b, b)
fun shl(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = shl(Vec4us(), this, bX, bY, bZ, bW)
fun shl(bX: Short, bY: Short, bZ: Short, bW: Short) = shl(Vec4us(), this, bX, bY, bZ, bW)
fun shl(bX: Int, bY: Int, bZ: Int, bW: Int) = shl(Vec4us(), this, bX, bY, bZ, bW)
fun shl(b: Vec4us) = shl(Vec4us(), this, b.x, b.y, b.z, b.w)
infix fun shlAssign(b: Ushort) = shl(this, this, b, b, b, b)
infix fun shlAssign(b: Short) = shl(this, this, b, b, b, b)
infix fun shlAssign(b: Int) = shl(this, this, b, b, b, b)
fun shlAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = shl(this, this, bX, bY, bZ, bW)
fun shlAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = shl(this, this, bX, bY, bZ, bW)
fun shlAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = shl(this, this, bX, bY, bZ, bW)
infix fun shlAssign(b: Vec4us) = shl(this, this, b.x, b.y, b.z, b.w)
fun shl(b: Ushort, res: Vec4us) = shl(res, this, b, b, b, b)
fun shl(b: Short, res: Vec4us) = shl(res, this, b, b, b, b)
fun shl(b: Int, res: Vec4us) = shl(res, this, b, b, b, b)
fun shl(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us) = shl(res, this, bX, bY, bZ, bW)
fun shl(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us) = shl(res, this, bX, bY, bZ, bW)
fun shl(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us) = shl(res, this, bX, bY, bZ, bW)
fun shl(b: Vec4us, res: Vec4us) = shl(res, this, b.x, b.y, b.z, b.w)
infix fun shr(b: Ushort) = shr(Vec4us(), this, b, b, b, b)
infix fun shr(b: Short) = shr(Vec4us(), this, b, b, b, b)
infix fun shr(b: Int) = shr(Vec4us(), this, b, b, b, b)
fun shr(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = shr(Vec4us(), this, bX, bY, bZ, bW)
fun shr(bX: Short, bY: Short, bZ: Short, bW: Short) = shr(Vec4us(), this, bX, bY, bZ, bW)
fun shr(bX: Int, bY: Int, bZ: Int, bW: Int) = shr(Vec4us(), this, bX, bY, bZ, bW)
fun shr(b: Vec4us) = shr(Vec4us(), this, b.x, b.y, b.z, b.w)
infix fun shrAssign(b: Ushort) = shr(this, this, b, b, b, b)
infix fun shrAssign(b: Short) = shr(this, this, b, b, b, b)
infix fun shrAssign(b: Int) = shr(this, this, b, b, b, b)
fun shrAssign(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort) = shr(this, this, bX, bY, bZ, bW)
fun shrAssign(bX: Short, bY: Short, bZ: Short, bW: Short) = shr(this, this, bX, bY, bZ, bW)
fun shrAssign(bX: Int, bY: Int, bZ: Int, bW: Int) = shr(this, this, bX, bY, bZ, bW)
infix fun shrAssign(b: Vec4us) = shr(this, this, b.x, b.y, b.z, b.w)
fun shr(b: Ushort, res: Vec4us) = shr(res, this, b, b, b, b)
fun shr(b: Short, res: Vec4us) = shr(res, this, b, b, b, b)
fun shr(b: Int, res: Vec4us) = shr(res, this, b, b, b, b)
fun shr(bX: Ushort, bY: Ushort, bZ: Ushort, bW: Ushort, res: Vec4us) = shr(res, this, bX, bY, bZ, bW)
fun shr(bX: Short, bY: Short, bZ: Short, bW: Short, res: Vec4us) = shr(res, this, bX, bY, bZ, bW)
fun shr(bX: Int, bY: Int, bZ: Int, bW: Int, res: Vec4us) = shr(res, this, bX, bY, bZ, bW)
fun shr(b: Vec4us, res: Vec4us) = shr(res, this, b.x, b.y, b.z, b.w)
fun inv(res: Vec4us = Vec4us()) = inv(res, this)
fun invAssign() = inv(this, this)
// -- Generic bitwise operators --
infix fun and(b: Number) = and(Vec4us(), this, b.i, b.i, b.i, b.i)
fun and(bX: Number, bY: Number, bZ: Number, bW: Number) = and(Vec4us(), this, bX.i, bY.i, bZ.i, bW.i)
fun and(b: Vec4t<out Number>) = and(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun andAssign(b: Number) = and(this, this, b.i, b.i, b.i, b.i)
fun andAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = and(this, this, bX.i, bY.i, bZ.i, bW.i)
infix fun andAssign(b: Vec4t<out Number>) = and(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun and(b: Number, res: Vec4us) = and(res, this, b.i, b.i, b.i, b.i)
fun and(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us) = and(res, this, bX.i, bY.i, bZ.i, bW.i)
fun and(b: Vec4t<out Number>, res: Vec4us) = and(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun or(b: Number) = or(Vec4us(), this, b.i, b.i, b.i, b.i)
fun or(bX: Number, bY: Number, bZ: Number, bW: Number) = or(Vec4us(), this, bX.i, bY.i, bZ.i, bW.i)
fun or(b: Vec4t<out Number>) = or(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun orAssign(b: Number) = or(this, this, b.i, b.i, b.i, b.i)
fun orAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = or(this, this, bX.i, bY.i, bZ.i, bW.i)
infix fun orAssign(b: Vec4t<out Number>) = or(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun or(b: Number, res: Vec4us) = or(res, this, b.i, b.i, b.i, b.i)
fun or(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us) = or(res, this, bX.i, bY.i, bZ.i, bW.i)
fun or(b: Vec4t<out Number>, res: Vec4us) = or(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun xor(b: Number) = xor(Vec4us(), this, b.i, b.i, b.i, b.i)
fun xor(bX: Number, bY: Number, bZ: Number, bW: Number) = xor(Vec4us(), this, bX.i, bY.i, bZ.i, bW.i)
fun xor(b: Vec4t<out Number>) = xor(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun xorAssign(b: Number) = xor(this, this, b.i, b.i, b.i, b.i)
fun xorAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = xor(this, this, bX.i, bY.i, bZ.i, bW.i)
infix fun xorAssign(b: Vec4t<out Number>) = xor(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun xor(b: Number, res: Vec4us) = xor(res, this, b.i, b.i, b.i, b.i)
fun xor(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us) = xor(res, this, bX.i, bY.i, bZ.i, bW.i)
fun xor(b: Vec4t<out Number>, res: Vec4us) = xor(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun shl(b: Number) = shl(Vec4us(), this, b.i, b.i, b.i, b.i)
fun shl(bX: Number, bY: Number, bZ: Number, bW: Number) = shl(Vec4us(), this, bX.i, bY.i, bZ.i, bW.i)
fun shl(b: Vec4t<out Number>) = shl(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun shlAssign(b: Number) = shl(this, this, b.i, b.i, b.i, b.i)
fun shlAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = shl(this, this, bX.i, bY.i, bZ.i, bW.i)
infix fun shlAssign(b: Vec4t<out Number>) = shl(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun shl(b: Number, res: Vec4us) = shl(res, this, b.i, b.i, b.i, b.i)
fun shl(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us) = shl(res, this, bX.i, bY.i, bZ.i, bW.i)
fun shl(b: Vec4t<out Number>, res: Vec4us) = shl(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun shr(b: Number) = shr(Vec4us(), this, b.i, b.i, b.i, b.i)
fun shr(bX: Number, bY: Number, bZ: Number, bW: Number) = shr(Vec4us(), this, bX.i, bY.i, bZ.i, bW.i)
fun shr(b: Vec4t<out Number>) = shr(Vec4us(), this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun shrAssign(b: Number) = shr(this, this, b.i, b.i, b.i, b.i)
fun shrAssign(bX: Number, bY: Number, bZ: Number, bW: Number) = shr(this, this, bX.i, bY.i, bZ.i, bW.i)
infix fun shrAssign(b: Vec4t<out Number>) = shr(this, this, b._x.i, b._y.i, b._z.i, b._w.i)
fun shr(b: Number, res: Vec4us) = shr(res, this, b.i, b.i, b.i, b.i)
fun shr(bX: Number, bY: Number, bZ: Number, bW: Number, res: Vec4us) = shr(res, this, bX.i, bY.i, bZ.i, bW.i)
fun shr(b: Vec4t<out Number>, res: Vec4us) = shr(res, this, b._x.i, b._y.i, b._z.i, b._w.i)
infix fun allLessThan(us: Ushort): Boolean = x < us && y < us && z < us && w < us
infix fun anyLessThan(us: Ushort): Boolean = x < us || y < us || z < us || w < us
infix fun lessThan(us: Ushort): Vec4bool = Vec4bool { get(it) < us }
infix fun allLessThanEqual(us: Ushort): Boolean = x <= us && y <= us && z <= us && w <= us
infix fun anyLessThanEqual(us: Ushort): Boolean = x <= us || y <= us || z <= us || w <= us
infix fun lessThanEqual(us: Ushort): Vec4bool = Vec4bool { get(it) <= us }
infix fun allEqual(us: Ushort): Boolean = x == us && y == us && z == us && w == us
infix fun anyEqual(us: Ushort): Boolean = x == us || y == us || z == us || w == us
infix fun equal(us: Ushort): Vec4bool = Vec4bool { get(it) == us }
infix fun allNotEqual(us: Ushort): Boolean = x != us && y != us && z != us && w != us
infix fun anyNotEqual(us: Ushort): Boolean = x != us || y != us || z != us || w != us
infix fun notEqual(us: Ushort): Vec4bool = Vec4bool { get(it) != us }
infix fun allGreaterThan(us: Ushort): Boolean = x > us && y > us && z > us && w > us
infix fun anyGreaterThan(us: Ushort): Boolean = x > us || y > us || z > us || w > us
infix fun greaterThan(us: Ushort): Vec4bool = Vec4bool { get(it) > us }
infix fun allGreaterThanEqual(us: Ushort): Boolean = x >= us && y >= us && z >= us && w >= us
infix fun anyGreaterThanEqual(us: Ushort): Boolean = x >= us || y >= us || z >= us || w >= us
infix fun greaterThanEqual(us: Ushort): Vec4bool = Vec4bool { get(it) >= us }
infix fun allLessThan(v: Vec4us): Boolean = x < v.x && y < v.y && z < v.z && w < v.w
infix fun anyLessThan(v: Vec4us): Boolean = x < v.x || y < v.y || z < v.z || w < v.w
infix fun lessThan(v: Vec4us): Vec4bool = Vec4bool { get(it) < v[it] }
infix fun allLessThanEqual(v: Vec4us): Boolean = x <= v.x && y <= v.y && z <= v.z && w <= v.w
infix fun anyLessThanEqual(v: Vec4us): Boolean = x <= v.x || y <= v.y || z <= v.z || w <= v.w
infix fun lessThanEqual(v: Vec4us): Vec4bool = Vec4bool { get(it) <= v[it] }
infix fun allEqual(v: Vec4us): Boolean = x == v.x && y == v.y && z == v.z && w == v.w
infix fun anyEqual(v: Vec4us): Boolean = x == v.x || y == v.y || z == v.z || w == v.w
infix fun equal(v: Vec4us): Vec4bool = Vec4bool { get(it) == v[it] }
infix fun allNotEqual(v: Vec4us): Boolean = x != v.x && y != v.y && z != v.z && w != v.w
infix fun anyNotEqual(v: Vec4us): Boolean = x != v.x || y != v.y || z != v.z || w != v.w
infix fun notEqual(v: Vec4us): Vec4bool = Vec4bool { get(it) != v[it] }
infix fun allGreaterThan(v: Vec4us): Boolean = x > v.x && y > v.y && z > v.z && w > v.w
infix fun anyGreaterThan(v: Vec4us): Boolean = x > v.x || y > v.y || z > v.z || w > v.w
infix fun greaterThan(v: Vec4us): Vec4bool = Vec4bool { get(it) > v[it] }
infix fun allGreaterThanEqual(v: Vec4us): Boolean = x >= v.x && y >= v.y && z >= v.z && w >= v.w
infix fun anyGreaterThanEqual(v: Vec4us): Boolean = x >= v.x || y >= v.y || z >= v.z || w >= v.w
infix fun greaterThanEqual(v: Vec4us): Vec4bool = Vec4bool { get(it) >= v[it] }
companion object : vec4us_operators {
const val length = Vec4t.LENGTH
@JvmField
val size = length * Ushort.BYTES
@JvmStatic
fun fromPointer(ptr: Ptr<Ushort>) = Vec4us(ptr)
}
override fun size() = size
override fun equals(other: Any?) = other is Vec4us && this[0] == other[0] && this[1] == other[1] && this[2] == other[2] && this[3] == other[3]
override fun hashCode() = 31 * (31 * (31 * x.v.hashCode() + y.v.hashCode()) + z.v.hashCode()) + w.v.hashCode()
@JvmOverloads
fun print(name: String = "", stream: PrintStream = System.out) = stream.print("$name$this")
@JvmOverloads
fun println(name: String = "", stream: PrintStream = System.out) = stream.println("$name$this")
//@formatter:off
override inline var _x get() = x; set(value) { x = value }
override inline var r get() = x; set(value) { x = value }
override inline var s get() = x; set(value) { x = value }
override inline var _y get() = y; set(value) { y = value }
override inline var g get() = y; set(value) { y = value }
override inline var t get() = y; set(value) { y = value }
override inline var _z get() = z; set(value) { z = value }
override inline var b get() = z; set(value) { z = value }
override inline var p get() = z; set(value) { z = value }
override inline var _w get() = w; set(value) { w = value }
override inline var a get() = w; set(value) { w = value }
override inline var q get() = w; set(value) { w = value }
//@formatter:on
override inline operator fun get(index: Int) = array[ofs + index]
inline operator fun set(index: Int, value: Ushort) {
array[ofs + index] = value
}
override inline operator fun component1() = x
override inline operator fun component2() = y
override inline operator fun component3() = z
override inline operator fun component4() = w
override fun toString(): String = "($x, $y, $z, $w)"
}
| 7
| null |
19
| 99
|
dcbdd6237fbc5af02722b8ea1b404a93ce38a043
| 43,585
|
glm
|
MIT License
|
app/src/main/java/com/jm/androidmvvmproject/viewmodel/ListViewModel.kt
|
JonathanMoreno14
| 191,068,968
| false
| null |
package com.jm.androidmvvmproject.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jm.androidmvvmproject.di.DaggerApiComponent
import com.jm.androidmvvmproject.model.Quotes
import com.jm.androidmvvmproject.model.QuotesService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableSingleObserver
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class ListViewModel: ViewModel(){
@Inject
lateinit var quotesService: QuotesService
init {
DaggerApiComponent.create().inject(this)
}
private val disposable = CompositeDisposable()
val quotes = MutableLiveData<List<Quotes>>()
val quotesLoadError = MutableLiveData<Boolean>()
val loading = MutableLiveData<Boolean>()
fun refresh() {
fetchQuotes()
}
private fun fetchQuotes(){
loading.value = true
disposable.add(
quotesService.getQuotes()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object: DisposableSingleObserver<List<Quotes>>(){
override fun onSuccess(value: List<Quotes>) {
quotes.value = value
quotesLoadError.value = false
loading.value = false
}
override fun onError(e: Throwable) {
quotesLoadError.value = true
loading.value = false
}
})
)
}
override fun onCleared() {
super.onCleared()
disposable.clear()
}
}
| 0
|
Kotlin
|
1
| 0
|
f18eea2bcfb782d55a1e4d00537f769cf2b5a2a3
| 1,784
|
Android-MVVM-App
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/makerecalldecisionapi/domain/makerecalldecisions/recommendation/BookRecallToPpud.kt
|
ministryofjustice
| 478,614,213
| false
|
{"Kotlin": 1418654, "Shell": 18492, "Mustache": 1801, "Dockerfile": 1124, "Ruby": 229}
|
package uk.gov.justice.digital.hmpps.makerecalldecisionapi.domain.makerecalldecisions.recommendation
import uk.gov.justice.digital.hmpps.makerecalldecisionapi.domain.makerecalldecisions.PpudUser
import java.time.LocalDate
import java.time.LocalDateTime
data class BookRecallToPpud(
val decisionDateTime: LocalDateTime? = null,
val isInCustody: Boolean? = null,
val custodyType: String? = null,
val releasingPrison: String? = null,
val indexOffence: String? = null,
val ppudSentenceId: String? = null,
val mappaLevel: String? = null,
val policeForce: String? = null,
val probationArea: String? = null,
@Deprecated("Replaced by recommendedTo")
val recommendedToOwner: String? = null,
val recommendedTo: PpudUser? = null,
val receivedDateTime: LocalDateTime? = null,
val releaseDate: LocalDate? = null,
val riskOfContrabandDetails: String? = null,
val riskOfSeriousHarmLevel: String? = null,
val sentenceDate: LocalDate? = null,
val gender: String? = null,
val ethnicity: String? = null,
val firstNames: String? = null,
// deprecated - keep for now to prevent dev from breaking.
val firstName: String? = null,
// deprecated - keep for now to prevent dev from breaking.
val secondName: String? = null,
val lastName: String? = null,
val dateOfBirth: LocalDate? = null,
val cro: String? = null,
val prisonNumber: String? = null,
val legislationReleasedUnder: String? = null,
)
| 4
|
Kotlin
|
1
| 1
|
a9c8c47f6b385bc1f1e2f7b207eb114c6c5dd94d
| 1,431
|
make-recall-decision-api
|
MIT License
|
app/src/main/java/sample/jetpack/compose/ui/theme/Theme.kt
|
ritwikjamuar
| 643,342,278
| false
| null |
package sample.jetpack.compose.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ComposeSampleTheme(
darkTheme : Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor : Boolean = true,
content : @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| 0
|
Kotlin
|
0
| 0
|
7762ecc71f91ffb5789dd353610036c02aba3bef
| 2,148
|
ComposeSample
|
MIT License
|
sentry-samples/kmp-app-mvvm-di/shared/src/commonMain/kotlin/sentry.kmp.demo/models/AuthenticationViewModel.kt
|
getsentry
| 285,502,515
| false
|
{"Kotlin": 222417, "Objective-C": 33107, "Swift": 8383, "Shell": 6517, "Ruby": 6435, "Makefile": 1717, "C": 1239}
|
package sentry.kmp.demo.models
import io.sentry.kotlin.multiplatform.Sentry
import io.sentry.kotlin.multiplatform.SentryLevel
import io.sentry.kotlin.multiplatform.protocol.Breadcrumb
class LoginException(message: String) : Exception(message)
class AuthenticationViewModel : ViewModel() {
fun login(withError: Boolean): Boolean {
return if (withError) {
try {
throw LoginException("Error logging in")
} catch (exception: Exception) {
Sentry.captureException(exception) {
val breadcrumb = Breadcrumb.error("Error during login").apply {
setData("touch event", "on login")
}
it.addBreadcrumb(breadcrumb)
it.setContext("Login", "Failed due to ...")
it.setTag("login", "failed")
it.level = SentryLevel.ERROR
}
false
}
} else {
true
}
}
fun signUp() {
Sentry.crash()
}
}
| 24
|
Kotlin
|
19
| 97
|
a42d02cb266274fa4417a29363d8eaa59701f290
| 1,074
|
sentry-kotlin-multiplatform
|
MIT License
|
scientific/src/commonMain/kotlin/unit/AngularAcceleration.kt
|
splendo
| 191,371,940
| false
| null |
/*
Copyright 2021 Splendo Consulting B.V. The Netherlands
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.splendo.kaluga.scientific.unit
import com.splendo.kaluga.base.utils.Decimal
import com.splendo.kaluga.scientific.PhysicalQuantity
import kotlinx.serialization.Serializable
val AngularAccelerationUnits: Set<AngularAcceleration> get() = AngularVelocityUnits.flatMap { angularVelocity ->
TimeUnits.map { angularVelocity per it }
}.toSet()
@Serializable
data class AngularAcceleration(val angularVelocity: AngularVelocity, val per: Time) : AbstractScientificUnit<PhysicalQuantity.AngularAcceleration>(), MetricAndImperialScientificUnit<PhysicalQuantity.AngularAcceleration> {
override val quantity = PhysicalQuantity.AngularAcceleration
override val system = MeasurementSystem.MetricAndImperial
override val symbol: String by lazy {
if (angularVelocity.per == per) {
"${angularVelocity.angle.symbol} / ${per.symbol}2"
} else {
"${angularVelocity.angle.symbol} / (${angularVelocity.per.symbol} * ${per.symbol})"
}
}
override fun fromSIUnit(value: Decimal): Decimal = per.toSIUnit(angularVelocity.fromSIUnit(value))
override fun toSIUnit(value: Decimal): Decimal = angularVelocity.toSIUnit(per.fromSIUnit(value))
}
infix fun AngularVelocity.per(time: Time) = AngularAcceleration(this, time)
| 91
|
Kotlin
|
3
| 93
|
cd0f3a583efb69464aa020d206f598c6d15a0899
| 1,906
|
kaluga
|
Apache License 2.0
|
core/src/main/kotlin/voodoo/forge/ForgeUtil.kt
|
codewizard0
| 170,712,177
| true
|
{"Kotlin": 438883, "Shell": 5361, "Ruby": 73}
|
package voodoo.forge
import com.github.kittinunf.fuel.core.extensions.cUrlString
import com.github.kittinunf.fuel.coroutines.awaitObjectResponseResult
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.serialization.kotlinxDeserializerOf
import com.github.kittinunf.result.Result
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import mu.KLogging
import voodoo.data.ForgeVersion
import voodoo.util.Downloader
/**
* Created by nikky on 30/12/17.
* @author Nikky
*/
object ForgeUtil : KLogging() {
val deferredData by lazy {
GlobalScope.async { getForgeData() }
}
suspend fun getForgeBuild(version: String, mcVersion: String): Int {
val data = deferredData.await()
return if (version.equals("recommended", true) || version.equals("latest", true)) {
val promoVersion = "$mcVersion-${version.toLowerCase()}"
data.promos[promoVersion]!!
} else {
version.toInt()
}
}
suspend fun mcVersionsMap(filter: List<String>? = null): Map<String, Map<String, Int>> {
val forgeData = deferredData.await()
return forgeData.mcversion.let {
if(filter != null && filter.isNotEmpty()) {
it.filterKeys { version -> filter.contains(version) }
} else {
it
}
}.entries.associate { (version, numbers) ->
val versionIdentifier = "mc" + version.replace('.', '_')
val versions = numbers.associateBy { number ->
val buildIdentifier = "build$number"
buildIdentifier
}
versionIdentifier to versions
}
}
suspend fun promoMap(): Map<String, Int> {
val forgeData = deferredData.await()
return forgeData.promos.mapKeys { (key, version) ->
val keyIdentifier = key.replace('-', '_').replace('.', '_').run {
if (this.first().isDigit())
"mc$this"
else
this
}
keyIdentifier
}
}
suspend fun forgeVersionOf(build: Int?): ForgeVersion? {
if (build == null || build <= 0) return null
return forgeVersionOf(build)
}
suspend fun forgeVersionOf(build: Int): ForgeVersion {
val data = deferredData.await()
val webpath = data.webpath
val artifact = data.number[build.toString()]!!
val mcversion = artifact.mcversion
val forgeVersion = artifact.version
val branch = artifact.branch
var longVersion = "$mcversion-$forgeVersion"
if (branch != null) {
longVersion += "-$branch"
}
val fileName = "forge-$longVersion-installer.jar" // "forge-mcversion-$forgeVersion(-$branch)/installer.jar"
val url = "$webpath$longVersion/$fileName"
return ForgeVersion(
url,
fileName,
longVersion,
forgeVersion
)
}
private suspend fun getForgeData(): ForgeData {
val url = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json"
val loader: KSerializer<ForgeData> = ForgeData.serializer()
loop@ while (true) {
val (request, response, result) = url.httpGet()
.header("User-Agent" to Downloader.useragent)
.awaitObjectResponseResult(kotlinxDeserializerOf(loader = loader))
when (result) {
is Result.Success -> return result.value
is Result.Failure -> {
logger.error("getForgeData")
logger.error("url: $url")
logger.error("cUrl: ${request.cUrlString()}")
logger.error("response: $response")
logger.error { result.error }
continue@loop
}
}
}
}
}
@Serializable
data class ForgeData(
val adfocus: String,
val artifact: String,
val homepage: String,
val webpath: String,
val name: String,
val branches: Map<String, List<Int>>,
val mcversion: Map<String, List<Int>>,
val number: Map<String, Artifact>,
val promos: Map<String, Int>
)
@Serializable
data class Artifact(
val branch: String?,
val build: Int,
val files: List<List<String>>, // extension, file, checksum
val mcversion: String,
val modified: Double,
val version: String
)
| 0
|
Kotlin
|
0
| 0
|
b12be54b1802250830070ba8db9538175f8ae7e2
| 4,560
|
Voodoo
|
MIT License
|
data/src/main/java/com/yveschiong/data/mappers/PersonDataEntityMapper.kt
|
yveschiong
| 155,301,951
| false
|
{"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 51, "Kotlin": 106, "INI": 1, "JSON": 2}
|
package com.yveschiong.data.mappers
import com.yveschiong.data.entities.PersonData
import com.yveschiong.domain.common.Mapper
import com.yveschiong.domain.entities.PersonEntity
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PersonDataEntityMapper @Inject
constructor() : Mapper<PersonData, PersonEntity>() {
override fun mapFrom(from: PersonData): PersonEntity {
return PersonEntity(
from.firstName, from.middleName, from.lastName, from.license, from.id
)
}
}
| 0
|
Kotlin
|
0
| 0
|
0fcef969c37db162b4eebbaa974a2d950a12cfec
| 525
|
personal-record-book
|
Apache License 2.0
|
data/src/main/java/com/yveschiong/data/mappers/PersonDataEntityMapper.kt
|
yveschiong
| 155,301,951
| false
|
{"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 51, "Kotlin": 106, "INI": 1, "JSON": 2}
|
package com.yveschiong.data.mappers
import com.yveschiong.data.entities.PersonData
import com.yveschiong.domain.common.Mapper
import com.yveschiong.domain.entities.PersonEntity
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PersonDataEntityMapper @Inject
constructor() : Mapper<PersonData, PersonEntity>() {
override fun mapFrom(from: PersonData): PersonEntity {
return PersonEntity(
from.firstName, from.middleName, from.lastName, from.license, from.id
)
}
}
| 0
|
Kotlin
|
0
| 0
|
0fcef969c37db162b4eebbaa974a2d950a12cfec
| 525
|
personal-record-book
|
Apache License 2.0
|
daggercore/src/main/java/com/worldsnas/daggercore/DaggerExtensions.kt
|
worldsnas
| 178,716,293
| false
| null |
package com.worldsnas.daggercore
import android.app.Activity
import android.content.Context
import android.view.View
import com.worldsnas.daggercore.lifecycle.LifecycleComponent
import com.worldsnas.daggercore.lifecycle.LifecycleComponentProvider
fun View.coreComponent(): CoreComponent =
context.coreComponent()
fun Context.coreComponent(): CoreComponent =
if (applicationContext is CoreComponentProvider) {
(applicationContext as CoreComponentProvider).core()
} else {
throw IllegalArgumentException("app class must implement CoreComponentProvider")
}
val Activity.lifecycleComponent: LifecycleComponent
get() =
if (this is LifecycleComponentProvider) {
this.lifecycleComponent()
} else {
throw IllegalStateException("activity class must implement LifecycleComponentProvider $this")
}
| 15
| null |
8
| 57
|
c7d084d2cf2c4f9486337fe347d5d6b8b5806e0a
| 874
|
AIO
|
Apache License 2.0
|
gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/importing/KotlinDslScriptModelResolverCommon.kt
|
JetBrains
| 278,369,660
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradle.scripting.importing
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.Pair
import org.gradle.tooling.model.kotlin.dsl.KotlinDslModelsParameters.*
import org.gradle.tooling.model.kotlin.dsl.KotlinDslScriptsModel
import org.jetbrains.kotlin.idea.gradleTooling.KotlinDslScriptAdditionalTask
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
@IntellijInternalApi
val LOG = Logger.getInstance(KotlinDslScriptModelResolverCommon::class.java)
@Order(Integer.MIN_VALUE) // to be the first
abstract class KotlinDslScriptModelResolverCommon : AbstractProjectResolverExtension() {
override fun getExtraProjectModelClasses(): Set<Class<out Any>> {
return setOf(KotlinDslScriptsModel::class.java)
}
override fun getToolingExtensionsClasses(): Set<Class<out Any>> {
return setOf(KotlinDslScriptAdditionalTask::class.java)
}
override fun getExtraCommandLineArgs(): List<String> {
return listOf("-P$CORRELATION_ID_GRADLE_PROPERTY_NAME=${System.nanoTime()}")
}
}
| 191
| null |
4372
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 1,371
|
intellij-kotlin
|
Apache License 2.0
|
Logger/app/src/main/java/com/mazaiting/logger/MainApplication.kt
|
mazaiting
| 141,557,021
| false
|
{"Java": 7986, "Kotlin": 944}
|
package com.mazaiting.logger
import android.app.Application
import com.mazaiting.log.L
/**
* 应用入口
* Created by mazaiting on 2018/7/19.
*/
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
// L.setProp(BuildConfig.DEBUG, "MainActivity")
L.setDebug(BuildConfig.DEBUG)
}
}
| 1
| null |
1
| 1
|
835bc5d6546a3bddf5b8f75af59d1c66e05fc9ec
| 322
|
Log
|
Apache License 2.0
|
calendar/day21/Day21.kt
|
rocketraman
| 726,025,416
| false
|
{"Kotlin": 45660}
|
package day21
import Day
import Lines
class Day21 : Day() {
override fun part1(input: Lines): Any {
TODO("Not yet solved")
}
override fun part2(input: Lines): Any {
TODO("Not yet solved")
}
}
| 3
|
Kotlin
|
0
| 0
|
ca9db0df821f410b8edd7200918b40cc61daba06
| 211
|
template-advent-of-kotlin
|
Apache License 2.0
|
FluentUI.Demo/src/androidTest/java/com/microsoft/fluentuidemo/demos/V2TabBarActivityUITest.kt
|
microsoft
| 257,221,908
| false
| null |
package com.microsoft.fluentuidemo.demos
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.printToLog
import com.microsoft.fluentuidemo.BaseTest
import org.junit.Before
import org.junit.Test
class V2TabBarActivityUITest : BaseTest() {
@Before
fun initialize() {
launchActivity(V2TabBarActivity::class.java)
}
@Test
fun testAll() {
val verticalRadio = composeTestRule.onNodeWithTag(TAB_BAR_VERTICAL_RADIO)
val horizontalRadio = composeTestRule.onNodeWithTag(TAB_BAR_HORIZONTAL_RADIO)
val noTextRadio = composeTestRule.onNodeWithTag(TAB_BAR_NO_TEXT_RADIO)
val addButton = composeTestRule.onNodeWithTag(TAB_BAR_ADD_BUTTON)
val removeButton = composeTestRule.onNodeWithTag(TAB_BAR_REMOVE_BUTTON)
val tabBar = composeTestRule.onNodeWithTag(TAB_BAR)
toggleControlToValue(verticalRadio, true)
tabBar.assertExists("Vertical TabBar did not render")
toggleControlToValue(horizontalRadio, true)
tabBar.assertExists("Horizontal TabBar did not render")
toggleControlToValue(noTextRadio, true)
tabBar.assertExists("No Text TabBar did not render")
while (isEnabled(removeButton))
removeButton.performClick()
tabBar.assertExists("Removing all tabs did not work")
while (isEnabled(addButton))
addButton.performClick()
tabBar.assertExists("Adding all tabs did not work")
}
}
| 43
| null |
92
| 574
|
851a4989a4fce5db50a1818aa4121538c1fb4ad9
| 1,521
|
fluentui-android
|
MIT License
|
src/test/kotlin/com/glancebar/apiboilerplate/controller/RoleControllerTest.kt
|
yisen-cai
| 321,651,755
| false
| null |
package com.glancebar.apiboilerplate.controller
import com.glancebar.apiboilerplate.service.RoleService
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
/**
*
* @author YISEN
* @date 2020/12/18
*/
@SpringBootTest
@AutoConfigureMockMvc
internal class RoleControllerTest {
@Autowired
lateinit var roleController: RoleController
@MockBean
lateinit var roleService: RoleService
@Autowired
lateinit var mockMvc: MockMvc
// @Test
fun addRole() {
val body =
"""
{
name: "USER",
description: "Normal user role.",
authorities: []
}
""".trimIndent()
mockMvc.perform(
MockMvcRequestBuilders.post("/roles")
.content(body)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isCreated)
.andExpect(
MockMvcResultMatchers
.content()
.contentType(MediaType.APPLICATION_JSON)
)
}
// @Test
fun getRole() {
HttpStatus.CREATED
}
@Test
fun getRoles() {
}
@Test
fun deleteRole() {
}
@Test
fun updateRole() {
}
}
| 1
|
Kotlin
|
0
| 1
|
beb48202163b6bd39001661969a2a640bc359734
| 1,685
|
api-boilerplate
|
Apache License 2.0
|
app/src/main/java/com/example/friendzone/common/top_bar/TopBar.kt
|
mohitdamke
| 839,901,877
| false
|
{"Kotlin": 310975}
|
package com.example.friendzone.common.top_bar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color.Companion.Blue
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import com.example.friendzone.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar() {
TopAppBar(
title = { Text(text = stringResource(R.string.app_name), fontSize = 18.sp) },
colors = TopAppBarColors(
containerColor = White,
scrolledContainerColor = Red,
navigationIconContentColor = White,
actionIconContentColor = Blue,
titleContentColor = Gray
),
)
}
| 0
|
Kotlin
|
0
| 2
|
6d016f16d12b5a037c30ced93ade4d1c72c36295
| 1,050
|
FriendZone-App
|
MIT License
|
ktls-dsl/lang/src/main/kotlin/io/kotless/dsl/app/events/EventsStorage.kt
|
rdhuri
| 230,230,718
| true
|
{"Kotlin": 223802}
|
package io.kotless.dsl.app.events
import io.kotless.ScheduledEventType
import io.kotless.dsl.lang.event.Scheduled
import io.kotless.dsl.reflection.ReflectionScanner
import org.slf4j.LoggerFactory
import java.lang.reflect.Method
import kotlin.math.absoluteValue
import kotlin.reflect.KFunction
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.jvm.kotlinFunction
internal object EventsStorage {
private val logger = LoggerFactory.getLogger(EventsStorage::class.java)
private val cache = HashMap<String, KFunction<*>>()
private var scanned = false
fun scan() {
if (scanned) return
ReflectionScanner.methodsWithAnnotation<Scheduled>().forEach { method ->
logger.debug("Found function ${method.name} for annotation ${Scheduled::class.simpleName}")
val kFunc = method.kotlinFunction
val annotation = kFunc?.findAnnotation<Scheduled>()
if (annotation != null) {
if (annotation.id.isNotBlank()) {
cache[annotation.id] = kFunc
} else {
val ids = method.possibleNames()
val keys = ids.map { "${ScheduledEventType.General.prefix}-${it.hashCode().absoluteValue}" }
for (key in keys) {
cache[key] = kFunc
logger.debug("Saved with key $key function ${kFunc.name} for annotation ${Scheduled::class.simpleName}")
}
}
}
}
scanned = true
}
operator fun get(key: String): KFunction<*>? {
scan()
return cache[key] ?: return null
}
private fun Method.possibleNames(): Set<String> {
val klass = declaringClass.kotlin.qualifiedName!!
return setOf("$klass.$name", "${klass.substringBeforeLast(".")}.$name")
}
}
| 0
| null |
0
| 0
|
f294759c73a3bed5a411c0e3e027e7a02d86e201
| 1,869
|
kotless
|
Apache License 2.0
|
src/main/kotlin/bewis09/bewisclient/screen/MainOptionsScreen.kt
|
Bewis09
| 755,277,240
| false
|
{"Kotlin": 207736, "Java": 77040}
|
package bewis09.bewisclient.screen
import bewis09.bewisclient.Bewisclient
import bewis09.bewisclient.drawable.MainOptionsElement
import bewis09.bewisclient.drawable.UsableTexturedButtonWidget
import bewis09.bewisclient.mixin.ScreenMixin
import bewis09.bewisclient.screen.elements.ElementList
import bewis09.bewisclient.settingsLoader.Settings
import bewis09.bewisclient.settingsLoader.SettingsLoader
import net.minecraft.client.MinecraftClient
import net.minecraft.client.gui.DrawContext
import net.minecraft.client.gui.screen.ButtonTextures
import net.minecraft.client.gui.screen.Screen
import net.minecraft.client.gui.widget.ButtonWidget
import net.minecraft.client.gui.widget.ClickableWidget
import net.minecraft.client.gui.widget.TextFieldWidget
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.VertexConsumer
import net.minecraft.client.sound.PositionedSoundInstance
import net.minecraft.client.sound.SoundManager
import net.minecraft.sound.SoundEvents
import net.minecraft.text.Text
import net.minecraft.util.Identifier
import net.minecraft.util.math.ColorHelper
import net.minecraft.util.math.MathHelper
import org.joml.Matrix4f
import java.util.*
import kotlin.math.*
@Suppress("CAST_NEVER_SUCCEEDS")
class MainOptionsScreen : Screen(Text.empty()) {
var animationStart = 0L
var animatedScreen: Screen? = null
var animationState = AnimationState.STABLE
private var searchBar: TextFieldWidget? = null
private var bottomAnimation: ArrayList<ClickableWidget> = arrayListOf()
var slice = 0
private var totalHeight = 0
var scrolls = arrayListOf(0F)
var shouldNotNotifyChange = false
private val closeTextures: ButtonTextures = ButtonTextures(Identifier("bewisclient","textures/sprites/close_button.png"), Identifier("bewisclient","textures/sprites/close_button_highlighted.png"))
private val backTextures: ButtonTextures = ButtonTextures(Identifier("bewisclient","textures/sprites/back_button.png"),Identifier("bewisclient","textures/sprites/back_button_highlighted.png"))
var allElements = arrayListOf(ElementList.main())
init {
animationState = AnimationState.TO_MAIN_SCREEN_UNSTARTED
}
override fun render(context: DrawContext?, mouseX: Int, mouseY: Int, delta: Float) {
context!!
context.fill(0,0,width,height, 0xAA000000.toInt())
correctScroll()
var animationFrame = 1F
val animationSpeed = MathHelper.clamp(SettingsLoader.getInt("design","options_menu.animation_time").toInt(),1,500)
if(System.currentTimeMillis() - animationStart >= animationSpeed) {
if(animationState==AnimationState.TO_OTHER_SCREEN) {
client?.setScreen(animatedScreen)
return
}
if(animationState==AnimationState.LEFT) {
slice--
scrolls.removeLast()
allElements.removeLast()
}
if(animationState==AnimationState.RIGHT) {
slice++
}
animationState = AnimationState.STABLE
}
if(animationState!=AnimationState.STABLE) {
animationFrame = ((System.currentTimeMillis() - animationStart).toFloat())/animationSpeed
animationFrame = (1-cos(Math.PI * animationFrame).toFloat())/2F
if(animationState==AnimationState.TO_OTHER_SCREEN) {
animationFrame = 1F-animationFrame
}
animationFrame = MathHelper.clamp(0F,animationFrame,1F)
}
val middleAnimationFrame = animationFrame
if(animationState.animation==AnimationState.MIDDLE_ANIMATION)
animationFrame = 1f
context.fill((this.width/4) +4,0, (this.width-this.width/4-2)-2,this.height,
((0x88*animationFrame).toLong()*0x1000000).toInt()
)
bottomAnimation.forEach {
it.y = (height - (24 * animationFrame)).toInt()
}
val width = (this.width* scale.toDouble()).toInt()
val height = (this.height* scale.toDouble()).toInt()
context.matrices.scale(1f/ scale,1f/ scale,1f/ scale)
var h = 4 + scrolls[slice].toInt()
val normalOffset: Int = (if (animationState == AnimationState.LEFT) width/2*middleAnimationFrame else if (animationState == AnimationState.RIGHT) -width/2*middleAnimationFrame else 0F).roundToInt()
if(animationState!=AnimationState.STABLE)
context.enableScissor((this.width/4+4*animationFrame).toInt(),0, (this.width-(this.width/4+4*animationFrame)).toInt(),(this.height))
allElements[slice].forEach {element ->
h+=4+element.render(context,
width/4+10 + normalOffset,
h,
width/2-20,
(mouseX* scale).toInt(),
(mouseY* scale).toInt(),
max(10,floor(animationFrame*255).toLong() )*0x1000000L)
}
if(animationState==AnimationState.STABLE)
context.enableScissor((this.width/4+4*animationFrame).toInt(),0, (this.width-(this.width/4+4*animationFrame)).toInt(),(this.height))
totalHeight = h - scrolls[slice].toInt() + 8
if(animationState==AnimationState.RIGHT) {
h = 4 + scrolls[slice+1].toInt()
allElements[slice+1].forEach {element ->
h+=4+element.render(context,
width/4+10 + normalOffset + width/2,
h,
width/2-20,
(mouseX* scale).toInt(),
(mouseY* scale).toInt(),
max(10,floor(animationFrame*255).toLong() )*0x1000000L)
}
} else if(animationState==AnimationState.LEFT) {
h = 4 + scrolls[slice-1].toInt()
allElements[slice-1].forEach {element ->
h+=4+element.render(context,
width/4+10 + normalOffset - width/2,
h,
width/2-20,
(mouseX* scale).toInt(),
(mouseY* scale).toInt(),
max(10,floor(animationFrame*255).toLong() )*0x1000000L)
}
}
context.disableScissor()
context.matrices.scale(scale, scale, scale)
context.matrices.translate(0f,0f,3f)
context.enableScissor((this.width/4) +4,(this.height-28*animationFrame).toInt(), (this.width-this.width/4-2)-2,this.height)
context.fill(0,0,width,height, 0xAA000000.toInt())
context.disableScissor()
context.fill((this.width/4) +4,(this.height-28*animationFrame).toInt(), (this.width-this.width/4-2)-2,this.height,
0xAA000000.toInt()
)
for (drawable in (this as ScreenMixin).getDrawables()) {
if(drawable is ClickableWidget)
drawable.setAlpha(max(0.05f,animationFrame))
drawable.render(context, mouseX, mouseY, delta)
}
context.matrices.translate(0f,0f,-3f)
fillGradient(context, (this.width/4) -2,0, ((this.width/4)+6*animationFrame).toInt()-2,this.height,0,
((0xFF*animationFrame).toLong()*0x1000000).toInt()
)
fillGradient(context, (this.width-(this.width/4)-6*animationFrame).toInt()+2,0,this.width- (this.width/4) +2,this.height,
((0xFF*animationFrame).toLong()*0x1000000).toInt(), 0)
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
clicked = true
if(animationState==AnimationState.STABLE && mouseX>width/4 && mouseX<width/4*3 && mouseY<height-28) {
allElements[slice].forEach {it.mouseClicked(mouseX* scale, mouseY* scale, button, this)}
}
return super.mouseClicked(mouseX, mouseY, button)
}
override fun mouseReleased(mouseX: Double, mouseY: Double, button: Int): Boolean {
clicked = false
if(animationState==AnimationState.STABLE && mouseX>width/4 && mouseX<width/4*3 && mouseY<height-28) {
allElements[slice].forEach {it.mouseReleased(mouseX* scale, mouseY* scale, button)}
}
return super.mouseReleased(mouseX, mouseY, button)
}
override fun charTyped(chr: Char, modifiers: Int): Boolean {
ArrayList(allElements[slice]).forEach {it.charTyped(chr, modifiers)}
return super.charTyped(chr, modifiers)
}
override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
ArrayList(allElements[slice]).forEach {it.keyPressed(keyCode, scanCode, modifiers)}
return super.keyPressed(keyCode, scanCode, modifiers)
}
override fun mouseDragged(mouseX: Double, mouseY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean {
if(animationState==AnimationState.STABLE && mouseX>width/4 && mouseX<width/4*3 && mouseY<height-28) {
allElements[slice].forEach {it.onDrag(mouseX* scale, mouseY* scale, deltaX* scale, deltaY* scale, button)}
}
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)
}
override fun init() {
bottomAnimation = arrayListOf()
if(animationState==AnimationState.TO_MAIN_SCREEN_UNSTARTED) {
animationState=AnimationState.TO_MAIN_SCREEN
animationStart=System.currentTimeMillis()
}
bottomAnimation.add(addDrawableChild(UsableTexturedButtonWidget(width/4+8,height-24,20,20, backTextures) {
goBack()
}))
bottomAnimation.add(addDrawableChild(UsableTexturedButtonWidget(width/4*3-28,height-24,20,20,closeTextures) {
startAllAnimation(null)
}))
bottomAnimation.add(addDrawableChild(ButtonWidget.builder(Bewisclient.getTranslationText("gui.edit_hud")) {
startAllAnimation(WidgetConfigScreen(this))
}.dimensions(width/4+30,height-24,width/6-29,20).build()))
bottomAnimation.add(addDrawableChild(ButtonWidget.builder(Bewisclient.getTranslationText("gui.load_from_file")) {
SettingsLoader.loadSettings()
}.dimensions(width/4*3-1-width/6,height-24,width/6-29,20).build()))
searchBar = addDrawableChild(TextFieldWidget(MinecraftClient.getInstance().textRenderer,width/2+4-width/12,height-24,width/6-8,20,Text.empty()))
searchBar?.setChangedListener {
if(!shouldNotNotifyChange) {
if (it == "") {
allElements = arrayListOf(ElementList.main())
scrolls = arrayListOf(0f)
slice = 0
} else {
allElements.add(getList(ElementList.main()))
scrolls.add(0F)
slice++
}
}
}
bottomAnimation.add(searchBar!!)
}
fun getList(elements: ArrayList<MainOptionsElement>): ArrayList<MainOptionsElement> {
val list: ArrayList<MainOptionsElement> = arrayListOf()
for (e in elements) {
if(Bewisclient.getTranslatedString(e.title).lowercase(Locale.getDefault()).contains(searchBar!!.text.lowercase(Locale.getDefault())) && e.javaClass!=MainOptionsElement::class.java) {
list.add(e)
}
if(e.elements!=null) {
list.addAll(getList(e.elements!!))
}
}
return list
}
fun startAllAnimation(screen: Screen?) {
animationState = AnimationState.TO_OTHER_SCREEN
animationStart = System.currentTimeMillis()
animatedScreen = screen
}
fun goBack() {
if(animationState==AnimationState.STABLE)
if(slice>0 && searchBar?.text=="") {
shouldNotNotifyChange = true
searchBar?.text = ""
animationState = AnimationState.LEFT
animationStart = System.currentTimeMillis()
shouldNotNotifyChange = false
} else {
startAllAnimation(null)
}
}
fun openNewSlice(elements: ArrayList<MainOptionsElement>) {
allElements.add(elements)
scrolls.add(0F)
animationState = AnimationState.RIGHT
animationStart = System.currentTimeMillis()
}
override fun close() {
goBack()
}
enum class AnimationState(val animation: AnimationState?) {
ALL_ANIMATION(null),
MIDDLE_ANIMATION(null),
STABLE(null),
TO_OTHER_SCREEN(ALL_ANIMATION),
TO_MAIN_SCREEN(ALL_ANIMATION),
TO_MAIN_SCREEN_UNSTARTED(ALL_ANIMATION),
LEFT(MIDDLE_ANIMATION),
RIGHT(MIDDLE_ANIMATION)
}
private fun fillGradient(context: DrawContext, startX: Int, startY: Int, endX: Int, endY: Int, colorStart: Int, colorEnd: Int) {
val vertexConsumer: VertexConsumer = context.vertexConsumers.getBuffer(RenderLayer.getGui())
val f = ColorHelper.Argb.getAlpha(colorStart).toFloat() / 255.0f
val g = ColorHelper.Argb.getRed(colorStart).toFloat() / 255.0f
val h = ColorHelper.Argb.getGreen(colorStart).toFloat() / 255.0f
val i = ColorHelper.Argb.getBlue(colorStart).toFloat() / 255.0f
val j = ColorHelper.Argb.getAlpha(colorEnd).toFloat() / 255.0f
val k = ColorHelper.Argb.getRed(colorEnd).toFloat() / 255.0f
val l = ColorHelper.Argb.getGreen(colorEnd).toFloat() / 255.0f
val m = ColorHelper.Argb.getBlue(colorEnd).toFloat() / 255.0f
val matrix4f: Matrix4f = context.matrices.peek().positionMatrix
vertexConsumer.vertex(matrix4f, endX.toFloat(), startY.toFloat(), 5f).color(k, l, m, j).next()
vertexConsumer.vertex(matrix4f, startX.toFloat(), startY.toFloat(), 5f).color(g, h, i, f).next()
vertexConsumer.vertex(matrix4f, startX.toFloat(), endY.toFloat(), 5f).color(g, h, i, f).next()
vertexConsumer.vertex(matrix4f, endX.toFloat(), endY.toFloat(), 5f).color(k, l, m, j).next()
}
fun correctScroll() {
scrolls[slice]=max((height* scale -32-totalHeight),scrolls[slice])
scrolls[slice]=min(0f,scrolls[slice])
}
override fun mouseScrolled(mouseX: Double, mouseY: Double, horizontalAmount: Double, verticalAmount: Double): Boolean {
if(animationState==AnimationState.STABLE)
scrolls[slice]+=verticalAmount.toFloat()*20
correctScroll()
return super.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)
}
fun playDownSound(soundManager: SoundManager) {
soundManager.play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0f))
}
companion object {
var laS = 1f/ SettingsLoader.getFloat("design","options_menu.scale")
var clicked = false
val scale: Float
get() {
if(!clicked) {
laS = 1f/SettingsLoader.getFloat("design","options_menu.scale")
}
return laS
}
}
}
| 7
|
Kotlin
|
1
| 0
|
7a6cb7774e709d1593358658c553a2e4926a7a0c
| 14,931
|
Bewisclient-2
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/oguzdogdu/wallieshd/presentation/downloadphoto/DownloadPhotoFragment.kt
|
oguzsout
| 616,912,430
| false
|
{"Kotlin": 369442}
|
package com.oguzdogdu.wallieshd.presentation.downloadphoto
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import com.oguzdogdu.wallieshd.R
import com.oguzdogdu.wallieshd.core.BaseBottomSheetDialogFragment
import com.oguzdogdu.wallieshd.databinding.FragmentDownloadPhotoBinding
import com.oguzdogdu.wallieshd.util.downloadImage
import com.oguzdogdu.wallieshd.util.observeInLifecycle
import com.oguzdogdu.wallieshd.util.showToast
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class DownloadPhotoFragment :
BaseBottomSheetDialogFragment<FragmentDownloadPhotoBinding>(
FragmentDownloadPhotoBinding::inflate
) {
private val viewModel: DownloadPhotoViewModel by viewModels()
private val args: DownloadPhotoFragmentArgs by navArgs()
override fun initListeners() {
super.initListeners()
binding.apply {
buttonRawQuality.setOnClickListener {
viewModel.handleUIEvent(DownloadPhotoEvent.ClickedRaw)
}
buttonFullQuality.setOnClickListener {
viewModel.handleUIEvent(DownloadPhotoEvent.ClickedFull)
}
buttonMediumQuality.setOnClickListener {
viewModel.handleUIEvent(DownloadPhotoEvent.ClickedMedium)
}
buttonLowQuality.setOnClickListener {
viewModel.handleUIEvent(DownloadPhotoEvent.ClickedLow)
}
}
}
override fun observeData() {
super.observeData()
getQualityState()
}
private fun getQualityState() {
viewModel.downloadPhotoState.observeInLifecycle(viewLifecycleOwner, observer = { state ->
when (state?.quality) {
RAW -> downloadImageFromWeb(args.raw)
FULL -> downloadImageFromWeb(args.high)
MEDIUM -> downloadImageFromWeb(args.medium)
LOW -> downloadImageFromWeb(args.low)
}
})
}
private fun downloadImageFromWeb(url: String?) {
val directory: String = requireContext().getString(R.string.app_name)
val fileName = args.imageTitle + FILE_NAME_SUFFIX
requireView().showToast(requireContext(), R.string.downloading_text, Toast.LENGTH_LONG)
val downloadableImage = url?.let { requireContext().downloadImage(it, directory, fileName) }
if (downloadableImage == true) {
requireView().showToast(
requireContext(),
getString(R.string.download_photo_success),
Toast.LENGTH_LONG
)
this.dismiss()
}
}
companion object {
const val FILE_NAME_SUFFIX = ".jpg"
const val RAW = "raw"
const val FULL = "high"
const val MEDIUM = "medium"
const val LOW = "low"
}
}
| 0
|
Kotlin
|
0
| 8
|
e6f899f32c4e914fc9e585c28f7d54bfd05398fd
| 2,864
|
Wallies
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.