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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/jvmMain/kotlin/acidicoala/koalageddon/core/model/ILangString.kt
|
acidicoala
| 584,899,259
| false
| null |
package acidicoala.koalageddon.core.model
import acidicoala.koalageddon.core.ui.composition.LocalStrings
import acidicoala.koalageddon.core.values.Strings
import androidx.compose.runtime.Composable
/**
* Encapsulates a string reference in a language-agnostic manner.
* Use [LangString] to instantiate a new instance of [ILangString].
*/
interface ILangString {
fun text(strings: Strings): String
val text: String
@Composable
get() = text(LocalStrings.current)
}
class LangString(
private vararg val placeholders: Pair<String, String>,
private val factory: Strings.() -> String
) : ILangString {
override fun text(strings: Strings) = placeholders.fold(initial = factory(strings)) { acc, (key, value) ->
acc.replace(key, value)
}
}
| 1
|
Kotlin
|
4
| 50
|
9ec09a7ba5cabc7b1be173a9c8e8794c93984a24
| 784
|
Koalageddon2
|
The Unlicense
|
video-sdk/src/main/java/com/kaleyra/video_sdk/call/participants/model/ParticipantsUiState.kt
|
KaleyraVideo
| 686,975,102
| false
|
{"Kotlin": 5025429, "Shell": 7470, "Python": 6756, "Java": 1213}
|
package com.kaleyra.video_sdk.call.participants.model
import androidx.compose.runtime.Immutable
import com.kaleyra.video_sdk.common.immutablecollections.ImmutableList
import com.kaleyra.video_sdk.common.uistate.UiState
@Immutable
internal data class ParticipantsUiState(
val invitedParticipants: ImmutableList<String> = ImmutableList(),
val adminsStreamsIds: ImmutableList<String> = ImmutableList(),
val isLocalParticipantAdmin: Boolean = false,
): UiState
| 0
|
Kotlin
|
0
| 1
|
d73e4727cec4875a98b21110823947edcfe9e28c
| 470
|
VideoAndroidSDK
|
Apache License 2.0
|
app/src/main/java/com/droidafricana/moveery/ui/details/similardetails/similarshow/SimilarShowDetailsFragment.kt
|
Fbada006
| 240,091,360
| false
| null |
package com.droidafricana.moveery.ui.details.similardetails.similarshow
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.RequestManager
import com.droidafricana.moveery.R
import com.droidafricana.moveery.databinding.FragmentSimilarShowDetailsBinding
import com.droidafricana.moveery.di.Injectable
import com.droidafricana.moveery.models.shows.TvShow
import com.droidafricana.moveery.ui.details.VideoAdapter
import com.droidafricana.moveery.utils.Constants
import com.droidafricana.moveery.utils.DetailsHelper
import com.droidafricana.moveery.utils.OnVideoClickListener
import com.droidafricana.moveery.utils.Resource
import com.droidafricana.moveery.utils.buildShareIntent
import com.droidafricana.moveery.utils.loadImage
import com.droidafricana.moveery.utils.playVideo
import com.droidafricana.moveery.utils.showAndHandleBackButton
import com.droidafricana.moveery.utils.toPercentage
import com.like.LikeButton
import com.like.OnLikeListener
import javax.inject.Inject
/**
*Display similar movie details excluding the "Similar" section
*/
class SimilarShowDetailsFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
lateinit var requestManager: RequestManager
private lateinit var binding: FragmentSimilarShowDetailsBinding
private val viewModel: SimilarShowsViewModel by viewModels { viewModelFactory }
private val args: SimilarShowDetailsFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_similar_show_details, container, false
)
// Inflate the layout for this fragment
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.toolbar.showAndHandleBackButton(activity)
binding.lifecycleOwner = viewLifecycleOwner
val tvShow = args.tvShow
if (tvShow != null) {
displayShowDetails(tvShow)
viewModel.getVideosResource(tvShow.id)
}
val videoAdapter = VideoAdapter(
requireContext(),
OnVideoClickListener { playVideo(it) }
)
binding.similarVideoShowsList.adapter = videoAdapter
val videoLayoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.similarVideoShowsList.layoutManager = videoLayoutManager
tvShow?.id.let {
viewModel.videoRes.observe(viewLifecycleOwner, Observer { resource ->
when (resource.status) {
Resource.Status.SUCCESS -> {
if (!resource.data.isNullOrEmpty()) {
videoAdapter.submitList(resource.data)
} else {
showError()
}
}
Resource.Status.ERROR -> showError()
Resource.Status.LOADING -> showLoading()
}
})
}
observeLikedState()
onLikeButtonClicked()
onShareFabClicked()
}
private fun onShareFabClicked() {
binding.shareShow.setOnClickListener {
buildShareIntent(
args.tvShow!!.id,
Constants.SHOW_TYPE
)
}
}
private fun observeLikedState() {
viewModel.isShowInFav(args.tvShow?.id!!).observe(viewLifecycleOwner, Observer {
binding.likeButton.isLiked = it != null
})
}
private fun onLikeButtonClicked() {
binding.likeButton.setOnLikeListener(object : OnLikeListener {
override fun liked(likeButton: LikeButton?) {
args.tvShow?.let { viewModel.insertShowIntoFav(it) }
}
override fun unLiked(likeButton: LikeButton?) {
args.tvShow?.let { viewModel.deleteShowFromFav(it.id) }
}
})
}
/**Display the passed in movie from the [args]*/
private fun displayShowDetails(tvShow: TvShow?) {
val posterUrl = Constants.IMAGE_BASE_URL + tvShow?.poster_path
binding.ivSimilarShowPoster.loadImage(posterUrl, requestManager)
binding.tvSimilarShowTitle.text = tvShow?.name
binding.tvSimilarShowGenre.text =
DetailsHelper.getGenres(tvShow?.genre_ids, requireContext())
binding.tvSimilarShowYear.text = tvShow?.first_air_date?.substring(0, 4)
binding.tvSimilarShowOverview.text = tvShow?.overview
binding.tvSimilarShowRating.text = tvShow?.vote_average?.toPercentage()
binding.ratingCustomView.apply {
setValue(tvShow?.vote_average?.toInt()!!.times(10))
setFillColor(
DetailsHelper.getRatingColor(
tvShow.vote_average.toInt().times(10),
requireContext()
)
)
setStrokeColor(ContextCompat.getColor(requireContext(), R.color.colorAccent))
}
}
private fun showLoading() {
binding.videoLoadingSpinner.visibility = View.VISIBLE
binding.videoShowsError.visibility = View.GONE
}
private fun showError() {
binding.videoLoadingSpinner.visibility = View.GONE
binding.videoShowsError.visibility = View.VISIBLE
}
}
| 0
|
Kotlin
|
0
| 2
|
92b175690eac0333ecbe0d87c9f07084f6099459
| 5,927
|
Moveery
|
Apache License 2.0
|
src/test/kotlin/com/jetbrains/kotlin/structuralsearch/search/KotlinSSTypeReferenceTest.kt
|
JetBrains
| 250,351,744
| false
| null |
package com.jetbrains.kotlin.structuralsearch.search
import com.jetbrains.kotlin.structuralsearch.KotlinSSResourceInspectionTest
class KotlinSSTypeReferenceTest : KotlinSSResourceInspectionTest() {
override fun getBasePath(): String = "typeReference"
fun testAny() { doTest("fun '_('_ : '_) { '_* }") }
fun testFqType() { doTest("fun '_('_ : kotlin.Int) { '_* }") }
fun testFunctionType() { doTest("fun '_('_ : ('_) -> '_) { '_* }") }
fun testNullableType() { doTest("fun '_('_ : '_ ?) { '_* }") }
fun testFqTextFilter() { doTest("""fun '_('_ : '_:[regex( kotlin\.Int )])""") }
fun testStandaloneNullable() { doTest("Int?") }
fun testStandaloneParameter() { doTest("Array<Int>") }
}
| 9
|
Kotlin
|
2
| 17
|
40f5895867975ee38b60333033672b7957bfb491
| 727
|
intellij-structural-search-for-kotlin
|
Apache License 2.0
|
app/src/test/java/com/example/mvvmkotlin/data/repository/tvshow/FakeTvShowRepositoryImpl.kt
|
LennoxNunu
| 722,461,003
| false
|
{"Kotlin": 75877}
|
package com.example.mvvmkotlin.data.repository.tvshow
import com.example.mvvmkotlin.data.model.tvshow.TvShow
import com.example.mvvmkotlin.domain.repository.TvShowRepository
class FakeTvShowRepositoryImpl: TvShowRepository {
private val tvShows = mutableListOf<TvShow>()
init {
tvShows.add(TvShow("",1,"name1","overview1","posterPath1"))
tvShows.add(TvShow("",1,"name1","overview1","posterPath1"))
}
override suspend fun getTvShows(): List<TvShow>? {
return tvShows
}
override suspend fun updateTvShows(): List<TvShow>? {
tvShows.clear()
tvShows.add(TvShow("",1,"name1","overview1","posterPath1"))
tvShows.add(TvShow("",1,"name1","overview1","posterPath1"))
return tvShows
}
}
| 0
|
Kotlin
|
0
| 0
|
b71d72a83ed99bbcd09ddfe884a9ca0631ea772e
| 766
|
MVVMKotlin
|
MIT License
|
data/src/main/java/com/bikcodeh/mubi/data/local/preferences/LoginDataStoreOperationImpl.kt
|
Bikcodeh
| 553,763,395
| false
|
{"Kotlin": 253338}
|
package com.bikcodeh.mubi.data.local.preferences
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import com.bikcodeh.mubi.data.util.Constants.LOGIN_PREFERENCES_KEY
import com.bikcodeh.mubi.data.util.Constants.PREFERENCES_NAME
import com.bikcodeh.mubi.domain.repository.LoginDataStoreOperations
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
import javax.inject.Inject
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCES_NAME)
class LoginDataStoreOperationImpl @Inject constructor(
context: Context
) : LoginDataStoreOperations {
private val dataStore = context.dataStore
private object PreferencesKeys {
val isLoggedIn = booleanPreferencesKey(LOGIN_PREFERENCES_KEY)
}
override suspend fun saveLogin(isLoggedIn: Boolean) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.isLoggedIn] = isLoggedIn
}
}
override fun getIsLogged(): Flow<Boolean> {
return dataStore.data.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
val isLoggedIn = preferences[PreferencesKeys.isLoggedIn] ?: false
isLoggedIn
}
}
}
| 0
|
Kotlin
|
0
| 1
|
25929e402744a1070357ff1af9b05eb7d8bd345c
| 1,715
|
Mubi
|
MIT License
|
projector-server-core/src/main/kotlin/org/jetbrains/projector/server/core/ij/KeymapSetter.kt
|
JetBrains
| 267,844,825
| false
| null |
/*
* MIT License
*
* Copyright (c) 2019-2022 JetBrains s.r.o.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.jetbrains.projector.server.core.ij
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import org.jetbrains.projector.common.protocol.data.UserKeymap
import org.jetbrains.projector.util.loading.UseProjectorLoader
import org.jetbrains.projector.util.loading.state.IdeState
import org.jetbrains.projector.util.loading.state.whenOccurred
import org.jetbrains.projector.util.logging.Logger
import javax.swing.SwingUtilities
@UseProjectorLoader
public object KeymapSetter {
private val logger = Logger<KeymapSetter>()
private fun UserKeymap.toKeyMapManagerFieldName() = when (this) {
UserKeymap.WINDOWS -> KeymapManager.X_WINDOW_KEYMAP
UserKeymap.MAC -> KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP
UserKeymap.LINUX -> KeymapManager.GNOME_KEYMAP
}
public fun setKeymap(keymap: UserKeymap) {
IdeState.CONFIGURATION_STORE_INITIALIZED.whenOccurred("set keymap to match user's OS ($keymap)") {
SwingUtilities.invokeLater {
// it should be done on EDT
val keymapManagerExInstance = KeymapManagerEx.getInstanceEx()
val userKeymapName = keymap.toKeyMapManagerFieldName()
val keymapInstance = keymapManagerExInstance.getKeymap(userKeymapName) ?: run {
logger.error { "getKeymap($userKeymapName) == null - skipping setting keymap" }
return@invokeLater
}
keymapManagerExInstance.activeKeymap = keymapInstance
}
}
}
}
| 20
| null |
94
| 815
|
0f1e08a68f01c417a7ce8a58afe77d63603e22db
| 2,619
|
projector-client
|
MIT License
|
tezos-core/src/main/kotlin/it/airgap/tezos/core/internal/delegate/DelegateContext.kt
|
airgap-it
| 460,351,851
| false
| null |
package it.airgap.tezos.core.internal.delegate
import it.airgap.tezos.core.internal.annotation.InternalTezosSdkApi
@InternalTezosSdkApi
public interface DelegateContext : DefaultDelegateContext, LazyWeakDelegateContext
| 0
|
Kotlin
|
2
| 1
|
c5af5ffdd4940670bd66842580d82c2b9d682d84
| 220
|
tezos-kotlin-sdk
|
MIT License
|
uikit/src/main/java/com/sendbird/uikit/internal/ui/messages/FormMessageView.kt
|
sendbird
| 350,188,329
| false
| null |
package com.sendbird.uikit.internal.ui.messages
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sendbird.android.message.BaseMessage
import com.sendbird.uikit.R
import com.sendbird.uikit.SendbirdUIKit
import com.sendbird.uikit.activities.adapter.FormFieldAdapter
import com.sendbird.uikit.databinding.SbViewFormMessageComponentBinding
import com.sendbird.uikit.internal.extensions.forms
import com.sendbird.uikit.internal.extensions.setAppearance
import com.sendbird.uikit.model.MessageListUIParams
import com.sendbird.uikit.utils.DrawableUtils
import com.sendbird.uikit.utils.ViewUtils
internal class FormMessageView @JvmOverloads internal constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.sb_widget_other_user_message
) : BaseMessageView(context, attrs, defStyle) {
override val binding: SbViewFormMessageComponentBinding
private val editedAppearance: Int
private val sentAtAppearance: Int
private val nicknameAppearance: Int
private val messageAppearance: Int
private val formFieldAdapter: FormFieldAdapter = FormFieldAdapter()
override val layout: View
get() = binding.root
init {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.MessageView_User, defStyle, 0)
try {
binding = SbViewFormMessageComponentBinding.inflate(LayoutInflater.from(getContext()), this, true)
val isDarkMode = SendbirdUIKit.isDarkMode()
sentAtAppearance = a.getResourceId(
R.styleable.MessageView_User_sb_message_time_text_appearance,
R.style.SendbirdCaption4OnLight03
)
nicknameAppearance = a.getResourceId(
R.styleable.MessageView_User_sb_message_sender_name_text_appearance,
R.style.SendbirdCaption1OnLight02
)
editedAppearance = a.getResourceId(
R.styleable.MessageView_User_sb_message_other_edited_mark_text_appearance,
R.style.SendbirdBody3OnLight02
)
messageAppearance = a.getResourceId(
R.styleable.MessageView_User_sb_message_other_text_appearance,
R.style.SendbirdBody3OnLight01
)
val messageBackground = a.getResourceId(
R.styleable.MessageView_User_sb_message_other_background,
R.drawable.sb_shape_chat_bubble
)
val messageBackgroundTint =
a.getColorStateList(R.styleable.MessageView_User_sb_message_other_background_tint)
binding.contentPanel.background =
DrawableUtils.setTintList(context, messageBackground, messageBackgroundTint)
binding.rvFormFields.adapter = formFieldAdapter
binding.rvFormFields.layoutManager = LinearLayoutManager(context)
binding.rvFormFields.addItemDecoration(
ItemSpacingDecoration(resources.getDimensionPixelSize(R.dimen.sb_size_8))
)
binding.buttonSubmit.background = if (isDarkMode) {
ResourcesCompat.getDrawable(resources, R.drawable.sb_shape_submit_button_dark, null)
} else {
ResourcesCompat.getDrawable(resources, R.drawable.sb_shape_submit_button_light, null)
}
binding.buttonSubmit.setAppearance(
context,
if (isDarkMode) R.style.SendbirdButtonOnLight01 else R.style.SendbirdButtonOnDark01
)
val linkTextColor = a.getColorStateList(R.styleable.MessageView_User_sb_message_other_link_text_color)
val clickedLinkBackgroundColor = a.getResourceId(
R.styleable.MessageView_User_sb_message_other_clicked_link_background_color,
R.color.primary_100
)
binding.tvMessageFormDisabled.setLinkTextColor(linkTextColor)
binding.tvMessageFormDisabled.clickedLinkBackgroundColor = ContextCompat.getColor(context, clickedLinkBackgroundColor)
} finally {
a.recycle()
}
}
fun drawFormMessage(message: BaseMessage, messageListUIParams: MessageListUIParams) {
val form = message.forms.firstOrNull() ?: return
formFieldAdapter.setFormFields(form)
messageUIConfig?.let {
it.otherSentAtTextUIConfig.mergeFromTextAppearance(context, sentAtAppearance)
it.otherNicknameTextUIConfig.mergeFromTextAppearance(context, nicknameAppearance)
it.otherMessageBackground?.let { background -> binding.contentPanel.background = background }
it.otherEditedTextMarkUIConfig.mergeFromTextAppearance(context, editedAppearance)
it.otherMessageTextUIConfig.mergeFromTextAppearance(context, messageAppearance)
it.linkedTextColor?.let { linkedTextColor -> binding.tvMessageFormDisabled.setLinkTextColor(linkedTextColor) }
}
if (messageListUIParams.channelConfig.enableFormTypeMessage) {
binding.formEnabledLayout.visibility = VISIBLE
binding.tvMessageFormDisabled.visibility = GONE
} else {
binding.formEnabledLayout.visibility = GONE
binding.tvMessageFormDisabled.visibility = VISIBLE
}
ViewUtils.drawTextMessage(
binding.tvMessageFormDisabled,
message,
messageUIConfig,
false,
null,
null
)
if (form.answeredList == null) {
setSubmitButtonVisibility(View.VISIBLE)
} else {
setSubmitButtonVisibility(View.GONE)
}
ViewUtils.drawNickname(binding.tvNickname, message, messageUIConfig, false)
ViewUtils.drawProfile(binding.ivProfileView, message)
ViewUtils.drawSentAt(binding.tvSentAt, message, messageUIConfig)
}
private fun setSubmitButtonVisibility(visibility: Int) {
if (visibility !in setOf(View.VISIBLE, View.GONE)) return
binding.buttonSubmit.visibility = visibility
}
fun setSubmitButtonClickListener(listener: OnClickListener?) {
binding.buttonSubmit.setOnClickListener { view ->
val isReadyToSubmit = formFieldAdapter.isReadyToSubmit()
formFieldAdapter.updateValidation()
if (!isReadyToSubmit) {
return@setOnClickListener
}
listener?.onClick(view)
}
}
private class ItemSpacingDecoration(
private val spacing: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
val itemCount = state.itemCount
val isLastPosition = position == (itemCount - 1)
with(outRect) {
left = 0
top = 0
right = 0
bottom = if (isLastPosition) 0 else spacing
}
}
}
}
| 1
| null |
43
| 39
|
c2f6aa7f37fb1428a96f3d93cf05e736e3659351
| 7,314
|
sendbird-uikit-android
|
MIT License
|
app/src/main/java/io/github/wulkanowy/ui/modules/login/recover/LoginRecoverFragment.kt
|
wezuwiusz
| 827,505,734
| false
| null |
package io.github.wulkanowy.ui.modules.login.recover
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.webkit.*
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.yariksoffice.lingver.Lingver
import dagger.hilt.android.AndroidEntryPoint
import io.github.wulkanowy.R
import io.github.wulkanowy.data.repositories.PreferencesRepository
import io.github.wulkanowy.databinding.FragmentLoginRecoverBinding
import io.github.wulkanowy.ui.base.BaseFragment
import io.github.wulkanowy.ui.modules.login.LoginActivity
import io.github.wulkanowy.ui.modules.login.form.LoginSymbolAdapter
import io.github.wulkanowy.utils.hideSoftInput
import io.github.wulkanowy.utils.showSoftInput
import javax.inject.Inject
@AndroidEntryPoint
class LoginRecoverFragment :
BaseFragment<FragmentLoginRecoverBinding>(R.layout.fragment_login_recover), LoginRecoverView {
private var _binding: FragmentLoginRecoverBinding? = null
private val bindingLocal: FragmentLoginRecoverBinding get() = _binding!!
@Inject
lateinit var presenter: LoginRecoverPresenter
@Inject
lateinit var lingver: Lingver
@Inject
lateinit var preferencesRepository: PreferencesRepository
companion object {
fun newInstance() = LoginRecoverFragment()
}
private lateinit var hostKeys: Array<String>
private lateinit var hostValues: Array<String>
private lateinit var hostSymbols: Array<String>
override val recoverHostValue: String
get() = hostValues.getOrNull(hostKeys.indexOf(bindingLocal.loginRecoverHost.text.toString()))
.orEmpty()
override val formHostSymbol: String
get() = hostSymbols.getOrNull(hostKeys.indexOf(bindingLocal.loginRecoverHost.text.toString()))
.orEmpty()
override val recoverNameValue: String
get() = bindingLocal.loginRecoverName.text.toString().trim()
override val emailHintString: String
get() = getString(R.string.login_email_hint)
override val loginPeselEmailHintString: String
get() = getString(R.string.login_login_pesel_email_hint)
override val invalidEmailString: String
get() = getString(R.string.login_invalid_email)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
restoreCorrectLocale()
_binding = FragmentLoginRecoverBinding.bind(view)
presenter.onAttachView(this)
}
// https://issuetracker.google.com/issues/37113860
private fun restoreCorrectLocale() {
if (preferencesRepository.appLanguage == "system") {
lingver.setFollowSystemLocale(requireContext())
} else {
lingver.setLocale(requireContext(), lingver.getLocale())
}
}
override fun initView() {
(requireActivity() as LoginActivity).showActionBar(true)
hostKeys = resources.getStringArray(R.array.hosts_keys)
hostValues = resources.getStringArray(R.array.hosts_values)
hostSymbols = resources.getStringArray(R.array.hosts_symbols)
with(bindingLocal) {
loginRecoverWebView.setBackgroundColor(Color.TRANSPARENT)
loginRecoverName.doOnTextChanged { _, _, _, _ -> presenter.onNameTextChanged() }
loginRecoverHost.setOnItemClickListener { _, _, _, _ -> presenter.onHostSelected() }
loginRecoverButton.setOnClickListener { presenter.onRecoverClick() }
loginRecoverErrorRetry.setOnClickListener { presenter.onRecoverClick() }
loginRecoverErrorDetails.setOnClickListener { presenter.onDetailsClick() }
loginRecoverLogin.setOnClickListener { (activity as LoginActivity).onBackPressed() }
}
with(bindingLocal.loginRecoverHost) {
setText(hostKeys.getOrNull(0).orEmpty())
setAdapter(
LoginSymbolAdapter(context, R.layout.support_simple_spinner_dropdown_item, hostKeys)
)
setOnClickListener { if (bindingLocal.loginRecoverFormContainer.visibility == GONE) dismissDropDown() }
}
}
override fun setDefaultCredentials(username: String) {
bindingLocal.loginRecoverName.setText(username)
}
override fun setErrorNameRequired() {
with(bindingLocal.loginRecoverNameLayout) {
requestFocus()
error = getString(R.string.error_field_required)
}
}
override fun setUsernameHint(hint: String) {
bindingLocal.loginRecoverNameLayout.hint = hint
}
override fun setUsernameError(message: String) {
with(bindingLocal.loginRecoverNameLayout) {
requestFocus()
error = message
}
}
override fun clearUsernameError() {
bindingLocal.loginRecoverNameLayout.error = null
}
override fun showProgress(show: Boolean) {
bindingLocal.loginRecoverProgress.visibility = if (show) VISIBLE else GONE
}
override fun showRecoverForm(show: Boolean) {
bindingLocal.loginRecoverFormContainer.visibility = if (show) VISIBLE else GONE
}
override fun showCaptcha(show: Boolean) {
bindingLocal.loginRecoverCaptchaContainer.visibility = if (show) VISIBLE else GONE
}
override fun showErrorView(show: Boolean) {
bindingLocal.loginRecoverError.visibility = if (show) VISIBLE else GONE
bindingLocal.loginRecoverErrorDetails.isVisible = true
}
override fun setErrorDetails(message: String) {
bindingLocal.loginRecoverErrorMessage.text = message
}
override fun showSuccessView(show: Boolean) {
bindingLocal.loginRecoverSuccess.visibility = if (show) VISIBLE else GONE
}
override fun setSuccessTitle(title: String) {
bindingLocal.loginRecoverSuccessTitle.text = title
}
override fun setSuccessMessage(message: String) {
bindingLocal.loginRecoverSuccessMessage.text = message
}
override fun showSoftKeyboard() {
activity?.showSoftInput()
}
override fun hideSoftKeyboard() {
activity?.hideSoftInput()
}
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
override fun loadReCaptcha(siteKey: String, url: String) {
val html = """
<div style="position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);" id="recaptcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=cl&render=explicit&hl=pl" async defer></script>
<script>var cl=()=>grecaptcha.render("recaptcha",{
sitekey:'$siteKey',
callback:e =>Android.captchaCallback(e)})</script>
""".trimIndent()
with(bindingLocal.loginRecoverWebView) {
settings.javaScriptEnabled = true
webViewClient = object : WebViewClient() {
private var recoverWebViewSuccess = true
override fun onPageFinished(view: WebView?, url: String?) {
if (recoverWebViewSuccess) {
showCaptcha(true)
showProgress(false)
} else {
showProgress(false)
showErrorView(true)
bindingLocal.loginRecoverErrorDetails.isVisible = false
}
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
recoverWebViewSuccess = false
}
}
loadDataWithBaseURL(url, html, "text/html", "UTF-8", null)
addJavascriptInterface(object {
@Suppress("UNUSED")
@JavascriptInterface
fun captchaCallback(reCaptchaResponse: String) {
activity?.runOnUiThread {
presenter.onReCaptchaVerified(reCaptchaResponse)
}
}
}, "Android")
}
}
override fun onResume() {
super.onResume()
presenter.updateFields()
}
override fun onDestroyView() {
bindingLocal.loginRecoverWebView.destroy()
_binding = null
presenter.onDetachView()
super.onDestroyView()
}
}
| 96
| null |
6
| 28
|
82b4ea930e64d0d6e653fb9024201b372cdb5df2
| 8,500
|
neowulkanowy
|
Apache License 2.0
|
platforms/core-configuration/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/SourceDistributionProvider.kt
|
gradle
| 302,322
| false
| null |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.resolver
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.artifacts.transform.TransformSpec
import org.gradle.api.attributes.Attribute
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.kotlin.dsl.*
import org.gradle.util.GradleVersion
import java.io.File
interface SourceDistributionProvider {
fun sourceDirs(): Collection<File>
}
class SourceDistributionResolver(val project: Project) : SourceDistributionProvider {
companion object {
val artifactType = Attribute.of("artifactType", String::class.java)
val zipType = "zip"
val unzippedDistributionType = "unzipped-distribution"
val sourceDirectory = "src-directory"
}
override fun sourceDirs(): Collection<File> =
try {
sourceDirs
} catch (ex: Exception) {
project.logger.warn("Unexpected exception while resolving Gradle distribution sources: ${ex.message}", ex)
emptyList()
}
private
val sourceDirs by lazy {
createSourceRepository()
registerTransforms()
transientConfigurationForSourcesDownload().files
}
private
fun registerTransforms() {
registerTransform<UnzipDistribution> {
from.attribute(artifactType, zipType)
to.attribute(artifactType, unzippedDistributionType)
}
registerTransform<FindGradleSources> {
from.attribute(artifactType, unzippedDistributionType)
to.attribute(artifactType, sourceDirectory)
}
}
private
fun transientConfigurationForSourcesDownload() =
detachedConfigurationFor(gradleSourceDependency()).apply {
attributes.attribute(artifactType, sourceDirectory)
}
private
fun detachedConfigurationFor(dependency: Dependency) =
configurations.detachedConfiguration(dependency)
private
fun gradleSourceDependency() = dependencies.create(
group = "gradle",
name = "gradle",
version = dependencyVersion(gradleVersion),
configuration = null,
classifier = "src",
ext = "zip"
)
private
fun createSourceRepository() = ivy {
val repoName = repositoryNameFor(gradleVersion)
name = "Gradle $repoName"
setUrl("https://services.gradle.org/$repoName")
metadataSources {
artifact()
}
patternLayout {
if (isSnapshot(gradleVersion)) {
ivy("/dummy") // avoids a lookup that interferes with version listing
}
artifact("[module]-[revision](-[classifier])(.[ext])")
}
}
private
fun repositoryNameFor(gradleVersion: String) =
if (isSnapshot(gradleVersion)) "distributions-snapshots" else "distributions"
private
fun dependencyVersion(gradleVersion: String) =
if (isSnapshot(gradleVersion)) toVersionRange(gradleVersion) else gradleVersion
private
fun isSnapshot(gradleVersion: String) = gradleVersion.contains('+')
private
fun toVersionRange(gradleVersion: String) =
"(${minimumGradleVersion()}, $gradleVersion]"
private
inline fun <reified T : TransformAction<TransformParameters.None>> registerTransform(configure: Action<TransformSpec<TransformParameters.None>>) =
dependencies.registerTransform(T::class.java, configure)
private
fun ivy(configure: Action<IvyArtifactRepository>) =
repositories.ivy(configure)
private
fun minimumGradleVersion(): String? {
val baseVersionString = GradleVersion.version(gradleVersion).baseVersion.version
val (major, minor) = baseVersionString.split('.')
return when (minor) {
// TODO:kotlin-dsl consider commenting out this clause once the 1st 6.0 snapshot is out
"0" -> {
// When testing against a `major.0` snapshot we need to take into account
// that source distributions matching the major version might not have
// been published yet. In that case we adjust the constraint to include
// source distributions beginning from the previous major version.
"${previous(major)}.0"
}
else -> {
// Otherwise include source distributions beginning from the previous minor version only.
"$major.${previous(minor)}"
}
}
}
private
fun previous(versionDigit: String) =
Integer.valueOf(versionDigit) - 1
private
val resolver by lazy { projectInternal.newDetachedResolver() }
private
val projectInternal
get() = project as ProjectInternal
private
val repositories
get() = resolver.repositories
private
val configurations
get() = resolver.configurations
private
val dependencies
get() = resolver.dependencies
private
val gradleVersion
get() = project.gradle.gradleVersion
}
| 2,663
| null |
4552
| 15,640
|
3fde2e4dd65124d0f3b2ef42f7e93446ccd7cced
| 5,898
|
gradle
|
Apache License 2.0
|
cordapp-cpk/src/main/kotlin/net/corda/plugins/cpk/PublishAfterEvaluationHandler.kt
|
rankinc
| 380,033,966
| true
|
{"Kotlin": 868814, "Java": 177787, "Groovy": 73722, "Shell": 4346, "Batchfile": 106}
|
package net.corda.plugins.cpk
import org.gradle.api.Action
import org.gradle.api.InvalidUserCodeException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.XmlProvider
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.ModuleVersionIdentifier
import org.gradle.api.artifacts.ResolvedArtifact
import org.gradle.api.invocation.Gradle
import org.gradle.api.logging.Logger
import org.gradle.api.plugins.JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME
import org.gradle.api.provider.Provider
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.tasks.GenerateMavenPom
import org.gradle.api.tasks.TaskContainer
import org.w3c.dom.Element
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.function.Function
class PublishAfterEvaluationHandler(rootProject: Project) : Action<Gradle> {
private val logger: Logger = rootProject.logger
private var artifactoryPublisher: ArtifactoryPublisher? = null
private fun enableArtifactoryPublisher(plugin: Plugin<*>) {
artifactoryPublisher = try {
ArtifactoryPublisher(plugin, logger)
} catch (_: Exception) {
logger.warn("Cannot publish CPK companion POM to Artifactory")
null
}
}
init {
rootProject.plugins.withId("com.jfrog.artifactory") { plugin ->
enableArtifactoryPublisher(plugin)
}
}
override fun execute(gradle: Gradle) {
for (project in gradle.rootProject.allprojects) {
// The plugin ID is the only reliable way to check
// whether a particular plugin has been applied.
// Each sub-project can load its plugins into its
// own classloader, which makes all of the [Plugin]
// implementation classes different.
if (project.plugins.hasPlugin(CORDAPP_CPK_PLUGIN_ID)) {
publishCompanionFor(project)
}
}
}
private fun publishCompanionFor(project: Project) {
val publications = (project.extensions.findByType(PublishingExtension::class.java) ?: return).publications
val pomXmlWriter = PomXmlWriter(project.configurations)
publications.withType(MavenPublication::class.java)
.matching { it.pom.packaging == "jar" && !it.groupId.isNullOrEmpty() }
.all { pub ->
// Create a "companion" POM to support transitive CPK relationships.
val publicationProvider = publications.register("cpk-${pub.name}-companion", MavenPublication::class.java) { cpk ->
cpk.groupId = toCompanionGroupId(pub.groupId, pub.artifactId)
cpk.artifactId = toCompanionArtifactId(pub.artifactId)
cpk.version = pub.version
cpk.pom { pom ->
pom.packaging = "pom"
pom.url.set(pub.pom.url)
pom.description.set(pub.pom.description)
pom.inceptionYear.set(pub.pom.inceptionYear)
pom.withXml(pomXmlWriter)
}
}
artifactoryPublisher?.run {
publish(project.tasks, pub, publicationProvider)
}
}
}
}
private class PomXmlWriter(private val configurations: ConfigurationContainer) : Action<XmlProvider> {
override fun execute(xml: XmlProvider) {
val compileClasspath = configurations.getByName(COMPILE_CLASSPATH_CONFIGURATION_NAME).resolvedConfiguration
val dependencies = xml.asElement().appendElement("dependencies")
val cordappWriter = DependencyXmlWriter(dependencies, Function(::CordappCoordinate))
val cordappDependencies = configurations.getByName(CORDAPP_CONFIGURATION_NAME).allDependencies
compileClasspath.resolveFirstLevel(cordappDependencies).forEach(cordappWriter::write)
val providedWriter = DependencyXmlWriter(dependencies, Function(::ProvidedCoordinate))
val providedDependencies = configurations.getByName(CORDA_PROVIDED_CONFIGURATION_NAME).allDependencies
compileClasspath.resolveFirstLevel(providedDependencies).forEach(providedWriter::write)
}
}
private class DependencyXmlWriter(
private val dependencies: Element,
private val coordinateFactory: Function<ResolvedArtifact, out MavenCoordinate>
) {
fun write(artifact: ResolvedArtifact) {
val maven = coordinateFactory.apply(artifact)
val dependency = dependencies.appendElement("dependency")
dependency.appendElement("groupId", maven.groupId)
dependency.appendElement("artifactId", maven.artifactId)
dependency.appendElement("version", maven.version)
maven.classifier?.also { classifier ->
dependency.appendElement("classifier", classifier)
}
if (maven.type != "jar") {
dependency.appendElement("type", maven.type)
}
dependency.appendElement("scope", "compile")
}
}
private abstract class MavenCoordinate(artifact: ResolvedArtifact) {
@JvmField
protected val id: ModuleVersionIdentifier = artifact.moduleVersion.id
@JvmField
protected val artifactName: String = artifact.name
abstract val groupId: String?
abstract val artifactId: String
val version: String? get() = id.version
val classifier: String? = artifact.classifier
val type: String? = artifact.type
}
private class CordappCoordinate(artifact: ResolvedArtifact): MavenCoordinate(artifact) {
override val groupId: String get() = toCompanionGroupId(id.group, artifactName)
override val artifactId: String get() = toCompanionArtifactId(artifactName)
}
private class ProvidedCoordinate(artifact: ResolvedArtifact): MavenCoordinate(artifact) {
override val groupId: String get() = id.group
override val artifactId: String get() = artifactName
}
/**
* Integrate with the `com.jfrog.artifactory` Gradle plugin, which uses a
* [ProjectEvaluationListener][org.gradle.api.ProjectEvaluationListener] to
* configure itself. We can therefore assume here that any `ArtifactoryTask`
* objects have already been configured.
*
* All we need is the set of [MavenPublication] objects that are to be
* published to Artifactory. If our CPK's own [MavenPublication] is
* among them then we include its companion's publication too.
*/
private class ArtifactoryPublisher(plugin: Plugin<*>, logger: Logger) {
private companion object {
private const val ARTIFACTORY_TASK_NAME = "org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask"
private const val GET_PUBLICATIONS_METHOD_NAME = "getMavenPublications"
}
private val artifactoryTaskClass = try {
@Suppress("unchecked_cast")
Class.forName(ARTIFACTORY_TASK_NAME, true, plugin::class.java.classLoader) as Class<out Task>
} catch (e: ClassNotFoundException) {
logger.warn("Task {} from Gradle com.jfrog.artifactory plugin is not available.", ARTIFACTORY_TASK_NAME)
throw e
}
private val mavenPublications: Method = try {
artifactoryTaskClass.getMethod(GET_PUBLICATIONS_METHOD_NAME)
} catch (e: Exception) {
logger.warn("Cannot locate $GET_PUBLICATIONS_METHOD_NAME method for ArtifactoryTask", e)
throw e
}
init {
if (!MutableCollection::class.java.isAssignableFrom(mavenPublications.returnType)) {
logger.warn("Method {} does not return a collection type.", mavenPublications)
throw InvalidUserCodeException()
}
}
private fun getMavenPublications(task: Task): MutableCollection<MavenPublication> {
return try {
@Suppress("unchecked_cast")
mavenPublications.invoke(task) as MutableCollection<MavenPublication>
} catch (e: InvocationTargetException) {
throw InvalidUserCodeException("Failed to extract Maven publications from $task", e.targetException)
}
}
fun publish(tasks: TaskContainer, owner: MavenPublication, provider: Provider<out MavenPublication>) {
tasks.withType(artifactoryTaskClass).configureEach { task ->
val publications = getMavenPublications(task)
if (publications.contains(owner)) {
val publication = provider.get()
if (publications.add(publication)) {
// Only modify the task graph if our publication wasn't already present.
task.dependsOn(tasks.named(getGeneratePomTaskName(publication), GenerateMavenPom::class.java))
}
}
}
}
private fun getGeneratePomTaskName(publication: MavenPublication): String {
// This name is documented behaviour for Gradle's maven-publish plugin.
return "generatePomFileFor${publication.name.capitalize()}Publication"
}
}
| 0
| null |
0
| 0
|
620b7af7c0e58fb82cdf6d685db6a00d3fa57c47
| 9,032
|
corda-gradle-plugins
|
Apache License 2.0
|
app/src/main/java/com/bmco/cratesiounofficial/models/Crate.kt
|
Catman155
| 110,840,290
| false
| null |
package com.bmco.cratesiounofficial.models
import com.bmco.cratesiounofficial.CrateNotifier
import com.bmco.cratesiounofficial.Networking
import com.bmco.cratesiounofficial.interfaces.OnDependencyDownloadListener
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import java.io.Serializable
import java.util.HashMap
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder("badges", "categories", "created_at", "description", "documentation", "downloads", "exact_match", "homepage", "id", "keywords", "license", "links", "max_version", "name", "repository", "updated_at", "versions")
class Crate : Serializable {
@JsonProperty("badges")
@get:JsonProperty("badges")
@set:JsonProperty("badges")
var badges: Any? = null
@JsonProperty("categories")
@get:JsonProperty("categories")
@set:JsonProperty("categories")
var categories: Any? = null
@JsonProperty("created_at")
@get:JsonProperty("created_at")
@set:JsonProperty("created_at")
var createdAt: String? = null
@JsonProperty("description")
@get:JsonProperty("description")
@set:JsonProperty("description")
var description: String? = null
@JsonProperty("documentation")
@get:JsonProperty("documentation")
@set:JsonProperty("documentation")
var documentation: String? = null
@JsonProperty("downloads")
@get:JsonProperty("downloads")
@set:JsonProperty("downloads")
var downloads: Int = 0
@JsonProperty("exact_match")
@get:JsonProperty("exact_match")
@set:JsonProperty("exact_match")
var isExactMatch: Boolean = false
@JsonProperty("homepage")
@get:JsonProperty("homepage")
@set:JsonProperty("homepage")
var homepage: String? = null
@JsonProperty("id")
@get:JsonProperty("id")
@set:JsonProperty("id")
var id: String? = null
@JsonProperty("keywords")
@get:JsonProperty("keywords")
@set:JsonProperty("keywords")
var keywords: Any? = null
@JsonProperty("license")
@get:JsonProperty("license")
@set:JsonProperty("license")
var license: String? = null
@JsonProperty("links")
@get:JsonProperty("links")
@set:JsonProperty("links")
var links: Links? = null
@JsonProperty("max_version")
@get:JsonProperty("max_version")
@set:JsonProperty("max_version")
var maxVersion: String? = null
@JsonProperty("name")
@get:JsonProperty("name")
@set:JsonProperty("name")
var name: String? = null
@JsonProperty("repository")
@get:JsonProperty("repository")
@set:JsonProperty("repository")
var repository: String? = null
@JsonProperty("updated_at")
@get:JsonProperty("updated_at")
@set:JsonProperty("updated_at")
var updatedAt: String? = null
@JsonProperty("versions")
@get:JsonProperty("versions")
@set:JsonProperty("versions")
var versions: List<Any>? = null
@JsonProperty("recent_downloads")
@get:JsonProperty("recent_downloads")
@set:JsonProperty("recent_downloads")
var recentDownloads: Int? = null
@JsonIgnore
private val additionalProperties = HashMap<String, Any>()
var versionList: List<Version>? = null
private var dependencies: List<Dependency>? = null
@JsonAnyGetter
fun getAdditionalProperties(): Map<String, Any> {
return this.additionalProperties
}
@JsonAnySetter
fun setAdditionalProperty(name: String, value: Any) {
this.additionalProperties[name] = value
}
fun getDependencies(listener: OnDependencyDownloadListener?) {
if (this.dependencies == null) {
Networking.getDependenciesForCrate(this.id!!, this.maxVersion!!, { dependencies ->
this@Crate.dependencies = dependencies
listener?.onDependenciesReady(dependencies)
}, {
/// todo: error message
})
} else {
listener!!.onDependenciesReady(this.dependencies!!)
}
}
}
| 1
|
Kotlin
|
3
| 13
|
70d970002e2500a25da811e003490ad40aa45a44
| 4,215
|
crates-io-android
|
Apache License 2.0
|
toolkit/livedata/src/test/kotlin/br/com/arch/toolkit/livedata/extention/LiveDataTransformationTest.kt
|
matheus-corregiari
| 131,161,672
| false
| null |
package br.com.arch.toolkit.livedata.extention
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.MutableLiveData
import br.com.arch.toolkit.livedata.response.MutableResponseLiveData
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.given
import com.nhaarman.mockitokotlin2.mock
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.times
class LiveDataTransformationTest {
@Rule
@get:Rule
@JvmField
var instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var mockedTransformation: (String) -> Int
private var owner = object : LifecycleOwner {
private val registry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
registry.markState(Lifecycle.State.RESUMED)
return registry
}
}
@Before
fun setup() {
mockedTransformation = mock()
given(mockedTransformation.invoke("ONE")).willReturn(0)
given(mockedTransformation.invoke("TWO")).willReturn(0)
}
@Test
fun mapShouldTransformThePostedData() {
val mockedObserver: (Int) -> Unit = mock()
val liveData = MutableLiveData<String>()
val transformedLiveData = liveData.map(mockedTransformation)
transformedLiveData.observe(owner, mockedObserver)
liveData.postValue(null)
Mockito.verifyNoInteractions(mockedObserver)
liveData.postValue("ONE")
Mockito.verify(mockedObserver).invoke(0)
}
@Test
fun mapShouldTransformEachItemInPostedData() {
val mockedObserver: (List<Int>) -> Unit = mock()
val liveData = MutableLiveData<List<String>>()
val transformedLiveData = liveData.mapList(mockedTransformation)
transformedLiveData.observe(owner, mockedObserver)
liveData.postValue(null)
Mockito.verifyNoInteractions(mockedObserver)
liveData.postValue(listOf("ONE", "TWO"))
Mockito.verify(mockedTransformation, times(2)).invoke(any())
Mockito.verify(mockedObserver).invoke(any())
}
@Test
fun map_withTransformAsync_shouldTransformEachItemInPostedResponseDataStartingThreads() {
val threadCount = Thread.activeCount()
val mockedObserver: (List<Int>) -> Unit = mock()
val liveData = MutableResponseLiveData<List<String>>()
val transformedLiveData = liveData.mapList(true, mockedTransformation)
transformedLiveData.observeData(owner, mockedObserver)
liveData.postData(listOf("ONE", "TWO"))
Assert.assertNotEquals(threadCount, Thread.activeCount())
Thread.sleep(50)
Mockito.verify(mockedTransformation, times(2)).invoke(any())
Mockito.verify(mockedObserver).invoke(any())
}
@Test
fun map_withoutTransformAsync_shouldTransformEachItemInPostedResponseDataWithoutStartingThreads() {
val threadCount = Thread.activeCount()
val mockedObserver: (List<Int>) -> Unit = mock()
val liveData = MutableResponseLiveData<List<String>>()
val transformedLiveData = liveData.mapList(mockedTransformation)
transformedLiveData.observeData(owner, mockedObserver)
liveData.postData(listOf("ONE", "TWO"))
Assert.assertEquals(threadCount, Thread.activeCount())
Thread.sleep(50)
Mockito.verify(mockedTransformation, times(2)).invoke(any())
Mockito.verify(mockedObserver).invoke(any())
}
}
| 2
|
Kotlin
|
3
| 19
|
d0beed2e77f8b5d0aecf3dd15f83ce9a5ec315cc
| 3,684
|
arch-toolkit
|
Apache License 2.0
|
wear/src/main/java/com/vlad1m1r/watchface/settings/base/viewholders/SettingsButtonViewHolder.kt
|
VladimirWrites
| 153,897,525
| false
| null |
package com.vlad1m1r.watchface.settings.base.viewholders
import android.view.View
import android.widget.Button
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import com.vlad1m1r.watchface.R
class SettingsButtonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(@StringRes titleRes: Int, onClickFun: () -> Unit) {
itemView.findViewById<Button>(R.id.settings_button).apply {
if (titleRes > 0) {
setText(titleRes)
}
setOnClickListener {
onClickFun()
}
}
}
}
| 5
|
Kotlin
|
21
| 99
|
0d54c556bffd7bb3e91fde670ff3baf05b6633bf
| 623
|
AnalogWatchFace
|
Apache License 2.0
|
app/src/main/java/com/udacity/project4/locationreminders/savereminder/selectreminderlocation/SelectLocationFragment.kt
|
MostafaMohamed2002
| 536,962,296
| false
|
{"Kotlin": 105705}
|
package com.udacity.project4.locationreminders.savereminder.selectreminderlocation
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.content.res.Resources
import android.location.Geocoder
import android.location.Location
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import com.firebase.ui.auth.data.model.Resource
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.material.snackbar.Snackbar
import com.udacity.project4.BuildConfig
import com.udacity.project4.R
import com.udacity.project4.base.BaseFragment
import com.udacity.project4.databinding.FragmentSelectLocationBinding
import com.udacity.project4.locationreminders.savereminder.SaveReminderViewModel
import com.udacity.project4.utils.setDisplayHomeAsUpEnabled
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import java.lang.Exception
import java.util.*
class SelectLocationFragment : BaseFragment(), OnMapReadyCallback {
override val _viewModel: SaveReminderViewModel by sharedViewModel()
private lateinit var googleMap: GoogleMap
private lateinit var binding: FragmentSelectLocationBinding
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private var currentPOI: PointOfInterest? = null
private var currentPOIMarker: Marker? = null
private val REQUEST_LOCATION_PERMISSION = 1
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_select_location, container, false)
binding.viewModel = _viewModel
binding.lifecycleOwner = this
setHasOptionsMenu(true)
setDisplayHomeAsUpEnabled(true)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.let {
mapFragment.getMapAsync(this)
}
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(requireContext())
binding.saveLocation.setOnClickListener {
locationSelected()
}
return binding.root
}
private fun locationSelected() {
if(currentPOI==null)
Toast.makeText(context, getString(R.string.selectpoi), Toast.LENGTH_SHORT).show()
else {
_viewModel.savePOILocation(currentPOI)
findNavController().navigate(SelectLocationFragmentDirections.actionSelectLocationFragmentToSaveReminderFragment())
}
}
override fun onMapReady(gmap: GoogleMap) {
googleMap=gmap
setPoiClick(googleMap)
setLocationClick(googleMap)
setMapStyle(googleMap)
enableMyLocation()
}
@SuppressLint("MissingPermission")
private fun enableMyLocation() {
if (isPermissionGranted()) {
googleMap.isMyLocationEnabled = true
zoomToCurrentLocation(true)
} else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
Snackbar.make(
requireActivity().findViewById(android.R.id.content),
R.string.location_required_error,
Snackbar.LENGTH_INDEFINITE
)
.setAction(android.R.string.ok) {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}.show()
} else {
requestPermissions(
arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}
}
@SuppressLint("MissingPermission")
private fun zoomToCurrentLocation(b: Boolean) {
val locationRequest = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_LOW_POWER
}
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val settingsClient = LocationServices.getSettingsClient(requireActivity())
val locationSettingsResponseTask =
settingsClient.checkLocationSettings(builder.build())
locationSettingsResponseTask.addOnFailureListener { exception ->
if (exception is ResolvableApiException && b) {
startIntentSenderForResult(
exception.resolution.intentSender,
REQUEST_TURN_DEVICE_LOCATION_ON,
null,
0,
0,
0,
null
)
} else {
Snackbar.make(
binding.root,
R.string.location_required_error, Snackbar.LENGTH_INDEFINITE
).setAction(android.R.string.ok) {
zoomToCurrentLocation(true)
}.show()
}
}
locationSettingsResponseTask.addOnCompleteListener {
if (it.isSuccessful) {
fusedLocationProviderClient.lastLocation
.addOnSuccessListener { location: Location? ->
// Got last known location. In some rare situations this can be null.
if (location != null) {
val zoomLevel = 15f
val currentLatLng = LatLng(location.latitude, location.longitude)
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
currentLatLng,
zoomLevel
)
)
}
}
}
}
}
private fun isPermissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun setMapStyle(gmap: GoogleMap) {
try {
val success = gmap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
context,
R.raw.map_style
)
)
if (!success) {
Log.e("MapStyle","Style parsing failed.")
}
}catch (e: Resources.NotFoundException){
Log.e("mapStyleNotFound","${e.message}")
}
}
private fun setLocationClick(gmap: GoogleMap) {
gmap.setOnMapClickListener {
val theAddress=Geocoder(context, Locale.getDefault()).getFromLocation(it.latitude, it.longitude, 1)
if (theAddress.isNotEmpty()){
val theAddress: String = theAddress[0].getAddressLine(0)
val theAddressPoi = PointOfInterest(it, null, theAddress)
currentPOIMarker?.remove()
val poiMarker = gmap.addMarker(
MarkerOptions()
.position(theAddressPoi.latLng)
.title(theAddressPoi.name)
)
poiMarker?.showInfoWindow()
currentPOIMarker = poiMarker
currentPOI = theAddressPoi
}
}
}
private fun setPoiClick(gmap: GoogleMap) {
gmap.setOnPoiClickListener { pointOfInterest ->
currentPOIMarker?.remove()
val pointOfInterestMarker=gmap.addMarker(
MarkerOptions()
.position(pointOfInterest.latLng)
.title(pointOfInterest.name)
)
pointOfInterestMarker.showInfoWindow()
currentPOIMarker=pointOfInterestMarker
currentPOI=pointOfInterest
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_TURN_DEVICE_LOCATION_ON -> {
zoomToCurrentLocation(false)
}
}
}
@SuppressLint("MissingPermission")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// Check if location permissions are granted and if so enable the
// location data layer.
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.isNotEmpty() && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
googleMap.isMyLocationEnabled = true
zoomToCurrentLocation(false)
} else {
Snackbar.make(
requireActivity().findViewById(android.R.id.content),
R.string.location_required_error,
Snackbar.LENGTH_INDEFINITE
)
.setAction(R.string.settings) {
startActivity(Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
})
}.show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.map_options, menu)
}
override fun onOptionsItemSelected(item: MenuItem)= when (item.itemId) {
R.id.normal_map -> {
googleMap.mapType = GoogleMap.MAP_TYPE_NORMAL
true
}
R.id.hybrid_map -> {
googleMap.mapType = GoogleMap.MAP_TYPE_HYBRID
true
}
R.id.satellite_map -> {
googleMap.mapType = GoogleMap.MAP_TYPE_SATELLITE
true
}
R.id.terrain_map -> {
googleMap.mapType = GoogleMap.MAP_TYPE_TERRAIN
true
}
else -> super.onOptionsItemSelected(item) }
companion object {
private const val REQUEST_TURN_DEVICE_LOCATION_ON = 1002
}
}
// override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// inflater.inflate(R.menu.map_options, menu)
// }
//
// override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
// R.id.normal_map -> {
// googleMap.mapType = GoogleMap.MAP_TYPE_NORMAL
// true
// }
// R.id.hybrid_map -> {
// googleMap.mapType = GoogleMap.MAP_TYPE_HYBRID
// true
// }
// R.id.satellite_map -> {
// googleMap.mapType = GoogleMap.MAP_TYPE_SATELLITE
// true
// }
// R.id.terrain_map -> {
// googleMap.mapType = GoogleMap.MAP_TYPE_TERRAIN
// true
// }
// else -> super.onOptionsItemSelected(item)
// }
//
// override fun onRequestPermissionsResult(
// requestCode: Int,
// permissions: Array<out String>,
// grantResults: IntArray
// ) {
// if (grantResults.isEmpty() || grantResults[LOCATION_PERMISSION_INDEX] == PackageManager.PERMISSION_DENIED
// || (requestCode == REQUEST_FOREGROUND_AND_BACKGROUND_PERMISSION_RESULT_CODE &&
// grantResults[BACKGROUND_LOCATION_PERMISSION_INDEX] ==
// PackageManager.PERMISSION_DENIED)
// ) {
// Snackbar.make(
// binding.constraintLayout,
// R.string.permission_denied_explanation,
// Snackbar.LENGTH_INDEFINITE
// ).setAction(R.string.settings) {
// startActivity(Intent().apply {
// action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
// data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
// flags = Intent.FLAG_ACTIVITY_NEW_TASK
// })
// }.show()
// } else {
// Log.e("onRequestPermissionsRes","onRequestPermissionsResult else called")
// checkDeviceLocationSettingsAndStartGeofence()
// }
// }
//
//
//
// override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// super.onActivityResult(requestCode, resultCode, data)
// Log.e("onActivityResult","ResultCode is $resultCode and requestCode is $requestCode")
// if (requestCode == REQUEST_TURN_DEVICE_LOCATION_ON) {
// Log.e("onActivityResult","onActivityResult REQUEST_TURN_DEVICE_LOCATION_ON ")
// checkDeviceLocationSettingsAndStartGeofence(false)
// }
// }
//
// @TargetApi(29)
// private fun foregroundAndBackgroundLocationPermissionApproved(): Boolean {
// val foregroundLocationApproved =
// (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
// requireContext(), Manifest.permission.ACCESS_FINE_LOCATION
// ))
// val backgroundLocationApproved =
// if (runningQOrLater) {
//
// PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
// requireContext(),
// Manifest.permission.ACCESS_BACKGROUND_LOCATION
// )
// } else {
// true
// }
// return foregroundLocationApproved && backgroundLocationApproved
// }
//
// @SuppressLint("MissingPermission")
// fun zoomToDeviceLocation() {
// fusedLocationProviderClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
// if (location != null) {
// val userLatLng = LatLng(location.latitude, location.longitude)
// val zoomLevel = 15f
// googleMap.moveCamera(
// CameraUpdateFactory.newLatLngZoom(
// userLatLng,
// zoomLevel
// )
// )
// }
// }
// }
//
// @TargetApi(29)
// private fun foregroundAndBackgroundLocationPermission() {
// Log.e("foregroundBackground","foregroundAndBackgroundLocationPermissionApproved is ${foregroundAndBackgroundLocationPermissionApproved()}")
// if (foregroundAndBackgroundLocationPermissionApproved()) {
// checkDeviceLocationSettingsAndStartGeofence()
// }
// var permissionsArray = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
// Log.e("runningQOrLater","runningQOrLater is $runningQOrLater")
// val resultCode = when {
// runningQOrLater -> {
// permissionsArray += Manifest.permission.ACCESS_BACKGROUND_LOCATION
// REQUEST_FOREGROUND_AND_BACKGROUND_PERMISSION_RESULT_CODE
// }
// else ->
// REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
// }
// Log.e("resultCode","resultCode is $resultCode")
// ActivityCompat.requestPermissions(
// requireActivity(),
// permissionsArray,
// resultCode
// )
// }
//
// private fun onLocationSelected(poi: PointOfInterest) {
// val latLng = poi.latLng
// _viewModel.reminderSelectedLocationStr.value = poi.name
// _viewModel.latitude.value = latLng.latitude
// _viewModel.longitude.value = latLng.longitude
// findNavController().popBackStack()
// }
//
// @SuppressLint("MissingPermission")
// private fun checkDeviceLocationSettingsAndStartGeofence(resolve: Boolean = true) {
// val locationRequest = LocationRequest.create().apply {
// priority = LocationRequest.PRIORITY_LOW_POWER
// }
// val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
// val settingsClient = LocationServices.getSettingsClient(requireActivity())
// val locationSettingsResponseTask =
// settingsClient.checkLocationSettings(builder.build())
// locationSettingsResponseTask.addOnFailureListener { exception ->
// if (exception is ResolvableApiException && resolve) {
// try {
// Log.e("StartGeofence"," exception.startResolutionForResult")
// startIntentSenderForResult(
// exception.resolution.intentSender,
// REQUEST_TURN_DEVICE_LOCATION_ON,
// null,
// 0,
// 0,
// 0,
// null
// )
// } catch (sendEx: IntentSender.SendIntentException) {
// Log.e("StartGeofence","Error getting location settings resolution: ${sendEx.message}")
// }
// } else {
// Log.e("StartGeofence","Error getting location settings resolution: showing snackbar")
// Snackbar.make(
// binding.constraintLayout,
// R.string.location_required_error, Snackbar.LENGTH_INDEFINITE
// ).setAction(android.R.string.ok) {
// Log.e("StartGeofence","setAction oK")
// checkDeviceLocationSettingsAndStartGeofence()
// }.show()
// }
// }
// locationSettingsResponseTask.addOnCompleteListener {
// if (it.isSuccessful) {
// googleMap.isMyLocationEnabled = true
// }
// }
// }
//
// private fun addPOI(map: GoogleMap) {
// map.setOnPoiClickListener { poi ->
// binding.saveLocation.visibility = View.VISIBLE
// binding.saveLocation.setOnClickListener {
// onLocationSelected(poi)
// }
// val poiMarker = map.addMarker(
// MarkerOptions().position(poi.latLng).title(poi.name)
// )
// poiMarker.showInfoWindow()
// }
//
// }
//
// private fun addMapClik(map: GoogleMap) {
// map.setOnMapClickListener {
// binding.saveLocation.visibility = View.VISIBLE
// binding.saveLocation.setOnClickListener { view ->
// _viewModel.latitude.value = it.latitude
// _viewModel.longitude.value = it.longitude
// _viewModel.reminderSelectedLocationStr.value = "Custom location used"
// findNavController().popBackStack()
// }
//
// val cameraUpdate = CameraUpdateFactory.newLatLngZoom(it, 15f)
// map.moveCamera(cameraUpdate)
// val poiMarker = map.addMarker(MarkerOptions().position(it))
// poiMarker.showInfoWindow()
// }
//
// }
//
// private fun setMapStyle(map: GoogleMap) {
// try {
// val success = map.setMapStyle(
// MapStyleOptions.loadRawResourceStyle(
// context,
// R.raw.map_style
// )
// )
// } catch (exc: Exception) {
// Log.e("setMapStyle","Exception getting the file")
// }
// }
| 0
|
Kotlin
|
0
| 0
|
9695ef5fa0b608c015d7f0820398196adac8f58e
| 20,138
|
Location-Reminder-App
|
MIT License
|
plano/src/main/kotlin/com/hanggrian/plano/MediaSize.kt
|
hanggrian
| 166,536,203
| false
|
{"Kotlin": 126046, "SCSS": 22632, "HTML": 21448, "CSS": 5501, "JavaScript": 1666, "Ruby": 243}
|
package com.hanggrian.plano
import org.slf4j.LoggerFactory
import java.io.Serializable
public class MediaSize(
override var width: Float,
override var height: Float,
private val trimSizes: MutableList<TrimSize> = mutableListOf(),
) : Size,
List<TrimSize> by trimSizes,
Serializable {
private var _trimWidth: Float? = null
private var _trimHeight: Float? = null
private var _gapHorizontal: Float? = null
private var _gapVertical: Float? = null
private var _isAllowFlipRight: Boolean? = null
private var _isAllowFlipBottom: Boolean? = null
public val trimWidth: Float
get() = checkNotNull(_trimWidth) { "Must call populate at least once" }
public val trimHeight: Float
get() = checkNotNull(_trimHeight) { "Must call populate at least once" }
public val gapHorizontal: Float
get() = checkNotNull(_gapHorizontal) { "Must call populate at least once" }
public val gapVertical: Float
get() = checkNotNull(_gapVertical) { "Must call populate at least once" }
public var isAllowFlipRight: Boolean
get() = checkNotNull(_isAllowFlipRight) { "Must call populate at least once" }
set(value) {
_isAllowFlipRight = value
populate(trimWidth, trimHeight, gapHorizontal, gapVertical, value, isAllowFlipBottom)
}
public var isAllowFlipBottom: Boolean
get() = checkNotNull(_isAllowFlipBottom) { "Must call populate at least once" }
set(value) {
_isAllowFlipBottom = value
populate(trimWidth, trimHeight, gapHorizontal, gapVertical, isAllowFlipRight, value)
}
public val coverage: Float
get() =
(trimSizes.sumOf { (it.width.toDouble() * it.height) }.toFloat()) *
100 /
(width * height)
public val mainWidth: Float get() = maxOf { it.x + it.width }
public val mainHeight: Float get() = maxOf { it.y + it.height }
public val remainingWidth: Float get() = width - mainWidth
public val remainingHeight: Float get() = height - mainHeight
public fun rotate() {
width = height.also { height = width }
populate(
trimWidth,
trimHeight,
gapHorizontal,
gapVertical,
isAllowFlipRight,
isAllowFlipBottom,
)
}
/** Using the total of 6 possible calculations, determine the most efficient of them. */
public fun populate(
trimWidth: Float,
trimHeight: Float,
gapHorizontal: Float,
gapVertical: Float,
allowFlipRight: Boolean,
allowFlipBottom: Boolean,
) {
_trimWidth = trimWidth
_trimHeight = trimHeight
_gapHorizontal = gapHorizontal
_gapVertical = gapVertical
_isAllowFlipRight = allowFlipRight
_isAllowFlipBottom = allowFlipBottom
trimSizes.clear()
trimSizes.addAll(
buildList {
add(
traditional(
width,
height,
trimWidth,
trimHeight,
gapHorizontal,
gapVertical,
allowFlipRight,
allowFlipBottom,
),
)
add(
traditional(
width,
height,
trimHeight,
trimWidth,
gapHorizontal,
gapVertical,
allowFlipRight,
allowFlipBottom,
),
)
if (allowFlipRight) {
add(
alwaysFlipRight(
width,
height,
trimWidth,
trimHeight,
gapHorizontal,
gapVertical,
allowFlipBottom,
),
)
add(
alwaysFlipRight(
width,
height,
trimHeight,
trimWidth,
gapHorizontal,
gapVertical,
allowFlipBottom,
),
)
}
if (!allowFlipBottom) {
return@buildList
}
add(
alwaysFlipBottom(
width,
height,
trimWidth,
trimHeight,
gapHorizontal,
gapVertical,
allowFlipRight,
),
)
add(
alwaysFlipBottom(
width,
height,
trimHeight,
trimWidth,
gapHorizontal,
gapVertical,
allowFlipRight,
),
)
}.maxByOrNull { it.size }!!,
)
}
/** Lay columns and rows, then search for optional leftovers. */
private fun traditional(
mediaWidth: Float,
mediaHeight: Float,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
flipRight: Boolean,
flipBottom: Boolean,
): List<TrimSize> {
if (BuildConfig2.DEBUG) {
logger.info(
"Calculating traditionally ${mediaWidth}x$mediaHeight - " +
"${trimWidth}x$trimHeight:",
)
}
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
val sizes = mutableListOf<TrimSize>()
val columns = (mediaWidth / finalTrimWidth).toInt()
val rows = (mediaHeight / finalTrimHeight).toInt()
sizes.populate(columns, rows, trimWidth, trimHeight, horizontalGap, verticalGap)
if (flipRight) {
val flippedRights =
measureFlippedRights(
columns,
mediaWidth,
mediaHeight,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flippedRights.first > 0) {
sizes.populateFlippedRights(
columns,
flippedRights,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
}
}
if (flipBottom) {
val flippedBottoms =
measureFlippedBottoms(
rows,
mediaWidth,
mediaHeight,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flippedBottoms.second > 0) {
sizes.populateFlippedBottoms(
rows,
flippedBottoms,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
}
}
return sizes
}
/** Columns are always flipped. */
private fun alwaysFlipRight(
mediaWidth: Float,
mediaHeight: Float,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
flipBottom: Boolean,
): List<TrimSize> {
if (BuildConfig2.DEBUG) {
logger.info(
"Calculating radical column ${mediaWidth}x$mediaHeight - " +
"${trimWidth}x$trimHeight:",
)
}
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
val sizes = mutableListOf<TrimSize>()
val columns = ((mediaWidth - finalTrimHeight) / finalTrimWidth).toInt()
val rows = (mediaHeight / finalTrimHeight).toInt()
sizes.populate(columns, rows, trimWidth, trimHeight, horizontalGap, verticalGap)
val flippedColumns =
measureFlippedRights(
columns,
mediaWidth,
mediaHeight,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
sizes.populateFlippedRights(
columns,
flippedColumns,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flipBottom) {
val flippedBottoms =
measureFlippedBottoms(
rows,
mediaWidth - trimHeight,
mediaHeight,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flippedBottoms.second > 0) {
sizes.populateFlippedBottoms(
rows,
flippedBottoms,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
}
}
return sizes
}
/** Rows are always flipped. */
private fun alwaysFlipBottom(
mediaWidth: Float,
mediaHeight: Float,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
flipRight: Boolean,
): List<TrimSize> {
if (BuildConfig2.DEBUG) {
logger.info(
"Calculating radical row ${mediaWidth}x$mediaHeight - " +
"${trimWidth}x$trimHeight:",
)
}
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
val sizes = mutableListOf<TrimSize>()
val columns = (mediaWidth / finalTrimWidth).toInt()
val rows = ((mediaHeight - finalTrimWidth) / finalTrimHeight).toInt()
sizes.populate(columns, rows, trimWidth, trimHeight, horizontalGap, verticalGap)
val flippedBottoms =
measureFlippedBottoms(
rows,
mediaWidth,
mediaHeight,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
sizes.populateFlippedBottoms(
rows,
flippedBottoms,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flipRight) {
val flippedRights =
measureFlippedRights(
columns,
mediaWidth,
mediaHeight - trimWidth,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
if (flippedRights.first > 0) {
sizes.populateFlippedRights(
columns,
flippedRights,
trimWidth,
trimHeight,
horizontalGap,
verticalGap,
)
}
}
return sizes
}
private fun MutableList<TrimSize>.populate(
columns: Int,
rows: Int,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
) {
if (BuildConfig2.DEBUG) {
logger.info("* columns: $columns")
logger.info("* rows: $rows")
}
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
for (column in 0 until columns) {
val x = column * finalTrimWidth
for (row in 0 until rows) {
val y = row * finalTrimHeight
this += TrimSize(x, y, trimWidth, trimHeight)
}
}
}
private fun measureFlippedRights(
columns: Int,
mediaWidth: Float,
mediaHeight: Float,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
): Pair<Int, Int> {
var flippedRightColumns = 0
var flippedRightRows = 0
if (columns > 0) {
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
flippedRightColumns =
((mediaWidth - columns * finalTrimWidth) / finalTrimHeight).toInt()
if (flippedRightColumns > 0) {
flippedRightRows = (mediaHeight / finalTrimWidth).toInt()
}
}
if (BuildConfig2.DEBUG) {
logger.info("* flippedRightRows: $flippedRightRows")
logger.info("* flippedRightColumns: $flippedRightColumns")
}
return flippedRightColumns to flippedRightRows
}
private fun measureFlippedBottoms(
rows: Int,
mediaWidth: Float,
mediaHeight: Float,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
): Pair<Int, Int> {
var flippedBottomColumns = 0
var flippedBottomRows = 0
if (rows > 0) {
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
flippedBottomRows = ((mediaHeight - rows * finalTrimHeight) / finalTrimWidth).toInt()
if (flippedBottomRows > 0) {
flippedBottomColumns = (mediaWidth / finalTrimHeight).toInt()
}
}
if (BuildConfig2.DEBUG) {
logger.info("* flippedBottomRows: $flippedBottomRows")
logger.info("* flippedBottomColumns: $flippedBottomColumns")
}
return flippedBottomColumns to flippedBottomRows
}
private fun MutableList<TrimSize>.populateFlippedRights(
columns: Int,
flippedRights: Pair<Int, Int>,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
) {
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
val startX = columns * finalTrimWidth - horizontalGap + verticalGap
for (flippedRightColumn in 0 until flippedRights.first) {
val x = startX + flippedRightColumn * finalTrimHeight
for (flippedRightRow in 0 until flippedRights.second) {
val y = flippedRightRow * finalTrimWidth
this += TrimSize(x, y, trimHeight, trimWidth)
}
}
}
private fun MutableList<TrimSize>.populateFlippedBottoms(
rows: Int,
flippedBottoms: Pair<Int, Int>,
trimWidth: Float,
trimHeight: Float,
horizontalGap: Float,
verticalGap: Float,
) {
val finalTrimWidth = trimWidth + horizontalGap
val finalTrimHeight = trimHeight + verticalGap
val startY = rows * finalTrimHeight - verticalGap + horizontalGap
for (flippedBottomRow in 0 until flippedBottoms.second) {
val y = startY + flippedBottomRow * finalTrimWidth
for (flippedBottomColumn in 0 until flippedBottoms.first) {
val x = flippedBottomColumn * finalTrimHeight
this += TrimSize(x, y, trimHeight, trimWidth)
}
}
}
private companion object {
private val logger = LoggerFactory.getLogger(MediaSize::class.java)
}
}
| 1
|
Kotlin
|
0
| 2
|
30a56b6dd1187239429f2e2354091bb29f4df512
| 16,115
|
plano
|
Apache License 2.0
|
project/jimmer-sql-kotlin/src/test/kotlin/org/babyfish/jimmer/sql/kt/dto/DepartmentViewTest.kt
|
babyfish-ct
| 488,154,823
| false
| null |
package org.babyfish.jimmer.sql.kt.dto
import org.babyfish.jimmer.kt.new
import org.babyfish.jimmer.sql.kt.common.assertContentEquals
import org.babyfish.jimmer.sql.kt.model.hr.Department
import org.babyfish.jimmer.sql.kt.model.hr.addBy
import org.babyfish.jimmer.sql.kt.model.hr.by
import org.babyfish.jimmer.sql.kt.model.hr.dto.DepartmentCompositeView
import org.babyfish.jimmer.sql.kt.model.hr.dto.DepartmentIdFunView
import org.babyfish.jimmer.sql.kt.model.hr.dto.DepartmentView
import kotlin.test.Test
class DepartmentViewTest {
@Test
fun testToEntity() {
val view = DepartmentView(
id = "3",
employeeIds = listOf("4", "5")
)
assertContentEquals(
"""{"id":"3","employees":[{"id":"4"},{"id":"5"}]}""",
view.toEntity()
)
}
@Test
fun testFromEntity() {
val entity = new(Department::class).by {
id = 3L
employeeIds = listOf(4L, 5L)
}
assertContentEquals(
"DepartmentView(id=3, employeeIds=[4, 5])",
DepartmentView(entity)
)
}
@Test
fun testToEntityByIdFun() {
val view = DepartmentIdFunView(
id = "3",
employeeIds = listOf("4", "5")
)
assertContentEquals(
"""{"id":"3","employees":[{"id":"4"},{"id":"5"}]}""",
view.toEntity()
)
}
@Test
fun testFromEntityByIdFun() {
val entity = new(Department::class).by {
id = 3L
employeeIds = listOf(4L, 5L)
}
assertContentEquals(
"DepartmentIdFunView(id=3, employeeIds=[4, 5])",
DepartmentIdFunView(entity)
)
}
@Test
fun testToEntityByComposite() {
val view = DepartmentCompositeView(
id = "3",
employees = listOf(
DepartmentCompositeView.TargetOf_employees(
id = "4",
name = "Jim"
),
DepartmentCompositeView.TargetOf_employees(
id = "5",
name = "Kate"
)
)
)
assertContentEquals(
"""{
|--->"id":"3",
|--->"employees":[
|--->--->{"id":"4","name":"Jim"},
|--->--->{"id":"5","name":"Kate"}
|--->]
|}""".trimMargin(),
view.toEntity()
)
}
@Test
fun testFromEntityByComposite() {
val entity = new(Department::class).by {
id = 3L
employees().addBy {
id = 4L
name = "Jim"
}
employees().addBy {
id = 4L
name = "Kate"
}
}
assertContentEquals(
"""DepartmentCompositeView(
|--->id=3,
|--->employees=[
|--->--->TargetOf_employees(id=4, name=Jim),
|--->--->TargetOf_employees(id=4, name=Kate)
|--->]
|)""".trimMargin(),
DepartmentCompositeView(entity)
)
}
}
| 18
| null |
72
| 725
|
873f8405a268d95d0b2e0ff796e2d0925ced21e7
| 3,191
|
jimmer
|
Apache License 2.0
|
kotlin/src/generated/kotlin/org/schema/kotlin/MutableRating.kt
|
aweiland
| 206,867,770
| false
| null |
package org.schema.kotlin
import org.schema.*
class MutableEmployerAggregateRating {
private val map = HashMap<String,Any>()
var itemReviewed: Thing
get() = map["itemReviewed"] as Thing
set(value) { map["itemReviewed"] = value }
fun itemReviewed(builder: MutableThing.() -> Unit) { map["itemReviewed"] = MutableThing().apply(builder).build() }
var ratingCount: Int
get() = map["ratingCount"] as Int
set(value) { map["ratingCount"] = value }
var reviewCount: Int
get() = map["reviewCount"] as Int
set(value) { map["reviewCount"] = value }
var author: Any
get() = map["author"]!!
set(value) { map["author"] = value }
fun authorOrganization(builder: MutableOrganization.() -> Unit) { map["author"] = MutableOrganization().apply(builder).build() }
fun authorPerson(builder: MutablePerson.() -> Unit) { map["author"] = MutablePerson().apply(builder).build() }
var bestRating: Any
get() = map["bestRating"]!!
set(value) { map["bestRating"] = value }
var ratingValue: Any
get() = map["ratingValue"]!!
set(value) { map["ratingValue"] = value }
var worstRating: Any
get() = map["worstRating"]!!
set(value) { map["worstRating"] = value }
var reviewAspect: String
get() = map["reviewAspect"] as String
set(value) { map["reviewAspect"] = value }
var additionalType: String
get() = map["additionalType"] as String
set(value) { map["additionalType"] = value }
var alternateName: String
get() = map["alternateName"] as String
set(value) { map["alternateName"] = value }
var description: Description
get() = map["description"] as Description
set(value) { map["description"] = value }
var disambiguatingDescription: String
get() = map["disambiguatingDescription"] as String
set(value) { map["disambiguatingDescription"] = value }
var image: Image
get() = map["image"] as Image
set(value) { map["image"] = value }
var mainEntityOfPage: Any
get() = map["mainEntityOfPage"]!!
set(value) { map["mainEntityOfPage"] = value }
fun mainEntityOfPageCreativeWork(builder: MutableCreativeWork.() -> Unit) { map["mainEntityOfPage"] = MutableCreativeWork().apply(builder).build() }
var name: String
get() = map["name"] as String
set(value) { map["name"] = value }
var sameAs: String
get() = map["sameAs"] as String
set(value) { map["sameAs"] = value }
var url: String
get() = map["url"] as String
set(value) { map["url"] = value }
var potentialAction: Action
get() = map["potentialAction"] as Action
set(value) { map["potentialAction"] = value }
fun potentialAction(builder: MutableAction.() -> Unit) { map["potentialAction"] = MutableAction().apply(builder).build() }
var identifier: Identifier
get() = map["identifier"] as Identifier
set(value) { map["identifier"] = value }
var subjectOf: Any
get() = map["subjectOf"]!!
set(value) { map["subjectOf"] = value }
fun subjectOfCreativeWork(builder: MutableCreativeWork.() -> Unit) { map["subjectOf"] = MutableCreativeWork().apply(builder).build() }
fun subjectOfEvent(builder: MutableEvent.() -> Unit) { map["subjectOf"] = MutableEvent().apply(builder).build() }
var id: String
get() = map["id"] as String
set(value) { map["id"] = value }
fun build() = org.schema.EmployerAggregateRating.Builder(map).build()
}
| 1
| null |
1
| 1
|
fe0b9e4acdd4a459558ba601181812e2e7f11146
| 3,358
|
jsonld-metadata
|
Apache License 2.0
|
app/src/main/java/com/breezeshankar/features/attendance/model/OutputResponse.kt
|
DebashisINT
| 851,529,165
| false
|
{"Kotlin": 15698684, "Java": 1025747}
|
package com.breezeshankar.features.attendance.model
import com.breezeshankar.base.BaseResponse
class OutputResponse: BaseResponse() {
var last_visit_order_list:ArrayList<last_visit_order_list>?=null
}
data class last_visit_order_list(var shop_name:String="",var shop_id:String="",var shop_Type:String="",
var shop_TypeName:String="",var last_visited_date:String="",var last_order_date:String="")
| 0
|
Kotlin
|
0
| 0
|
d382b7af0064e3965a2a89789c42731687d911f5
| 431
|
SHANKARMG
|
Apache License 2.0
|
app/src/main/java/com/roshastudio/roshastu/enum/CommentStatus.kt
|
sepandd97
| 345,416,807
| false
| null |
package com.roshastudio.roshastu.enum
enum class CommentStatus {
APPROVE, NOT_APPROVE, WATING_FOR_APPROVAL}
| 0
|
Kotlin
|
0
| 0
|
1f840c763e4be909afcb6af98d52b5542de43e09
| 112
|
Roshastu
|
MIT License
|
core/src/test/kotlin/sift/core/dsl/SiftTypeTest.kt
|
junkdog
| 561,870,959
| false
|
{"Kotlin": 573369, "Shell": 5738, "Java": 627}
|
package sift.core.dsl
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class SiftTypeTest {
val types = listOf(
"java.lang.String".type,
"java.lang.Integer".type,
"java.lang.Long".type,
"java.lang.Boolean".type,
"java.lang.Object".type,
"java.lang.Number".type,
"java.lang.reflect.Array".type,
"java.lang.reflect.Field".type,
"java.util.Map".type,
"java.util.List".type,
"java.util.HashMap".type,
"java.util.LinkedHashMap".type,
"java.util.HashMap<java.lang.Integer, java.lang.String>".type,
"java.util.HashMap<java.lang.Integer, java.lang.Integer>".type,
)
@Test
fun `match non-generic java lang types`() {
val javaLang = Regex("""java\.lang\.[\w.]+$""").type // \w does not match <
assertThat(types.filter(javaLang::matches))
.containsExactlyInAnyOrder(
"java.lang.String".type,
"java.lang.Integer".type,
"java.lang.Long".type,
"java.lang.Boolean".type,
"java.lang.Object".type,
"java.lang.Number".type,
"java.lang.reflect.Array".type,
"java.lang.reflect.Field".type,
)
}
@Test
fun `match concrete map types`() {
val maps = Regex("[^.]Map").type
assertThat(types.filter(maps::matches))
.containsExactlyInAnyOrder(
"java.util.HashMap".type,
"java.util.LinkedHashMap".type,
"java.util.HashMap<java.lang.Integer, java.lang.String>".type,
"java.util.HashMap<java.lang.Integer, java.lang.Integer>".type,
)
}
@Test
fun `match maps with integer keys`() {
val mapOfInts = Regex("Map<[\\w.]+Integer").type
assertThat(types.filter(mapOfInts::matches))
.containsExactlyInAnyOrder(
"java.util.HashMap<java.lang.Integer, java.lang.String>".type,
"java.util.HashMap<java.lang.Integer, java.lang.Integer>".type,
)
}
@Test
fun `match types operator contains`() {
assertThat(Regex("Field").type in types).isTrue
assertThat(Regex("Field2").type in types).isFalse
}
}
| 5
|
Kotlin
|
0
| 56
|
b486fe82fc07d85355311c13160a9fadc2f65831
| 2,322
|
sift
|
MIT License
|
src/examples/kotlin/net/dinkla/raytracer/examples/objects/World16.kt
|
jdinkla
| 38,753,756
| false
|
{"Kotlin": 490829, "Shell": 239}
|
package net.dinkla.raytracer.examples.objects
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.world.Builder
import net.dinkla.raytracer.world.World
import net.dinkla.raytracer.world.WorldDefinition
object World16 : WorldDefinition {
override val id: String = "World16.kt"
override fun world(): World = Builder.build {
// camera(d = 1000.0, eye = p(0, 0, 4), lookAt = p(0, 0, 0))
camera(d = 500.0, eye = p(0, 100, 200), lookAt = p(0, 0, 0))
ambientLight(ls = 0.5)
lights {
pointLight(location = p(2, 2, 1), ls = 1.0)
}
materials {
matte(id = "m1", cd = c(1, 1, 0), ka = 0.75, kd = 0.75)
matte(id = "m2", cd = c(1, 1, 1), ka = 0.75, kd = 0.75)
}
objects {
openCylinder(material = "m1", y0 = 0.2, y1 = 1.5, radius = 0.9)
plane(material = "m2", point = Point3D.ORIGIN, normal = Normal.UP)
}
}
}
| 0
|
Kotlin
|
2
| 5
|
01286be063088774b63560e2ad737d4b8dc8d7a8
| 1,002
|
from-the-ground-up-ray-tracer
|
Apache License 2.0
|
voiceping-sdk/src/main/java/com/smartwalkie/voicepingsdk/CustomAudioRecorder.kt
|
SmartWalkieOrg
| 96,063,593
| false
|
{"Java": 768731, "Kotlin": 70634}
|
package com.smartwalkie.voicepingsdk
/**
* Created by kukuhsain on 12/03/18.
*/
interface CustomAudioRecorder {
fun record(placeholderData: ByteArray): ByteArray
}
| 5
|
Java
|
9
| 26
|
215d16e1d7351592c5ce6109305e355f5df1f11a
| 171
|
VoicePing-Walkie-Talkie-AndroidSDK
|
MIT License
|
hubdle-gradle-plugin/main/kotlin/com/javiersc/hubdle/project/extensions/kotlin/multiplatform/targets/HubdleKotlinMultiplatformAndroidNativeExtension.kt
|
JavierSegoviaCordoba
| 348,863,451
| false
|
{"Kotlin": 501858, "Shell": 21101, "Perl": 4726, "CSS": 195}
|
package com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets
import com.javiersc.hubdle.project.extensions.HubdleDslMarker
import com.javiersc.hubdle.project.extensions._internal.getHubdleExtension
import com.javiersc.hubdle.project.extensions.apis.HubdleEnableableExtension
import com.javiersc.hubdle.project.extensions.apis.enableAndExecute
import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.hubdleKotlinMultiplatform
import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets.android.HubdleKotlinMultiplatformAndroidNativeArm32Extension
import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets.android.HubdleKotlinMultiplatformAndroidNativeArm64Extension
import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets.android.HubdleKotlinMultiplatformAndroidNativeX64Extension
import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets.android.HubdleKotlinMultiplatformAndroidNativeX86Extension
import com.javiersc.hubdle.project.extensions.kotlin.shared.HubdleKotlinMinimalSourceSetConfigurableExtension
import javax.inject.Inject
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.provider.Property
@HubdleDslMarker
public open class HubdleKotlinMultiplatformAndroidNativeExtension
@Inject
constructor(project: Project) : HubdleKotlinMinimalSourceSetConfigurableExtension(project) {
override val project: Project
get() = super.project
override val isEnabled: Property<Boolean> = property { false }
override val requiredExtensions: Set<HubdleEnableableExtension>
get() = setOf(hubdleKotlinMultiplatform)
override val targetName: String = "androidNative"
public val allEnabled: Property<Boolean> = property { false }
@HubdleDslMarker
public fun allEnabled(value: Boolean = true) {
allEnabled.set(value)
}
public val androidNativeArm32: HubdleKotlinMultiplatformAndroidNativeArm32Extension
get() = getHubdleExtension()
@HubdleDslMarker
public fun androidNativeArm32(
action: Action<HubdleKotlinMultiplatformAndroidNativeArm32Extension> = Action {}
) {
androidNativeArm32.enableAndExecute(action)
}
public val androidNativeArm64: HubdleKotlinMultiplatformAndroidNativeArm64Extension
get() = getHubdleExtension()
@HubdleDslMarker
public fun androidNativeArm64(
action: Action<HubdleKotlinMultiplatformAndroidNativeArm64Extension> = Action {}
) {
androidNativeArm64.enableAndExecute(action)
}
public val androidNativeX64: HubdleKotlinMultiplatformAndroidNativeX64Extension
get() = getHubdleExtension()
@HubdleDslMarker
public fun androidNativeX64(
action: Action<HubdleKotlinMultiplatformAndroidNativeX64Extension> = Action {}
) {
androidNativeX64.enableAndExecute(action)
}
public val androidNativeX86: HubdleKotlinMultiplatformAndroidNativeX86Extension
get() = getHubdleExtension()
@HubdleDslMarker
public fun androidNativeX86(
action: Action<HubdleKotlinMultiplatformAndroidNativeX86Extension> = Action {}
) {
androidNativeX86.enableAndExecute(action)
}
override fun Project.defaultConfiguration() {
lazyConfigurable {
if (allEnabled.get()) {
androidNativeArm32()
androidNativeArm64()
androidNativeX64()
androidNativeX86()
}
}
}
}
| 12
|
Kotlin
|
10
| 26
|
e880ed2481243bfab76a5df41476bbaeb7094fa5
| 3,517
|
hubdle
|
Apache License 2.0
|
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/api/FirDesignation.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2023 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.low.level.api.fir.api
import org.jetbrains.kotlin.analysis.low.level.api.fir.providers.nullableJavaSymbolProvider
import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirLibraryOrLibrarySourceResolvableModuleSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.FirElementFinder
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.containingClassId
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.getContainingFile
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.isScriptDependentDeclaration
import org.jetbrains.kotlin.analysis.utils.errors.requireIsInstance
import org.jetbrains.kotlin.analysis.utils.errors.unexpectedElementError
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.utils.isLocal
import org.jetbrains.kotlin.fir.diagnostics.ConeDestructuringDeclarationsOnTopLevel
import org.jetbrains.kotlin.fir.expressions.FirStatement
import org.jetbrains.kotlin.fir.resolve.providers.firProvider
import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.utils.exceptions.withFirEntry
import org.jetbrains.kotlin.fir.visitors.FirVisitorVoid
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.utils.exceptions.checkWithAttachment
import org.jetbrains.kotlin.utils.exceptions.errorWithAttachment
class FirDesignationWithFile(
path: List<FirRegularClass>,
target: FirElementWithResolveState,
val firFile: FirFile
) : FirDesignation(
path,
target,
) {
fun toSequenceWithFile(includeTarget: Boolean): Sequence<FirElementWithResolveState> = sequence {
yield(firFile)
yieldAll(path)
if (includeTarget) yield(target)
}
}
class FirDesignationWithScript(
path: List<FirRegularClass>,
target: FirElementWithResolveState,
val firScript: FirScript,
): FirDesignation(path, target)
open class FirDesignation(
val path: List<FirRegularClass>,
val target: FirElementWithResolveState,
) {
fun toSequence(includeTarget: Boolean): Sequence<FirElementWithResolveState> = sequence {
yieldAll(path)
if (includeTarget) yield(target)
}
}
private fun collectDesignationPath(target: FirElementWithResolveState): List<FirRegularClass>? {
when (target) {
is FirSimpleFunction,
is FirProperty,
is FirField,
is FirConstructor,
is FirEnumEntry,
is FirPropertyAccessor,
-> {
requireIsInstance<FirCallableDeclaration>(target)
if (target.symbol.callableId.isLocal || target.status.visibility == Visibilities.Local) {
return null
}
val containingClassId = target.containingClassLookupTag()?.classId ?: return emptyList()
if (target.origin is FirDeclarationOrigin.SubstitutionOverride) {
val originalContainingClassId = target.originalForSubstitutionOverride?.containingClassLookupTag()?.classId
if (containingClassId == originalContainingClassId) {
// Ugly temporary hack for call-site substitution overrides (KTIJ-24004).
// Containing class ID from the origin cannot be used, as the origin might be in a different module.
return emptyList()
}
}
return collectDesignationPathWithContainingClass(target, containingClassId)
}
is FirClassLikeDeclaration -> {
if (target.isLocal) {
return null
}
val containingClassId = target.symbol.classId.outerClassId ?: return emptyList()
return collectDesignationPathWithContainingClass(target, containingClassId)
}
is FirDanglingModifierList -> {
val containingClassId = target.containingClass()?.classId ?: return emptyList()
return collectDesignationPathWithContainingClass(target, containingClassId)
}
is FirAnonymousInitializer -> {
val containingClassId = target.containingClassId()
if (containingClassId.isLocal) return null
return collectDesignationPathWithContainingClass(target, containingClassId)
}
is FirErrorProperty -> {
return if (target.diagnostic == ConeDestructuringDeclarationsOnTopLevel) emptyList() else null
}
is FirScript, is FirCodeFragment -> {
return emptyList()
}
else -> {
return null
}
}
}
private fun collectDesignationPathWithContainingClassByFirFile(
firFile: FirFile,
containingClassId: ClassId,
target: FirDeclaration,
): List<FirRegularClass>? = FirElementFinder.findClassPathToDeclaration(
firFile = firFile,
declarationContainerClassId = containingClassId,
targetMemberDeclaration = target,
)
private fun collectDesignationPathWithContainingClass(target: FirDeclaration, containingClassId: ClassId): List<FirRegularClass>? {
if (containingClassId.isLocal) {
return null
}
val firFile = target.getContainingFile()
if (firFile != null && firFile.packageFqName == containingClassId.packageFqName) {
// We should do fallback to the heavy implementation if something goes wrong.
// For example, we can't be able to find an on-air declaration by this way
collectDesignationPathWithContainingClassByFirFile(firFile, containingClassId, target)?.let {
return it
}
}
val useSiteSession = getTargetSession(target)
fun resolveChunk(classId: ClassId): FirRegularClass {
val declaration = if (useSiteSession is LLFirLibraryOrLibrarySourceResolvableModuleSession) {
useSiteSession.symbolProvider.getClassLikeSymbolByClassId(classId)?.fir
} else {
useSiteSession.firProvider.getFirClassifierByFqName(classId)
?: useSiteSession.nullableJavaSymbolProvider?.getClassLikeSymbolByClassId(classId)?.fir
?: findKotlinStdlibClass(classId, target)
}
checkWithAttachment(
declaration is FirRegularClass,
message = { "'FirRegularClass' expected as a containing declaration, got '${declaration?.javaClass?.name}'" },
buildAttachment = {
withEntry("chunk", "$classId in $containingClassId")
withFirEntry("target", target)
if (declaration != null) {
withFirEntry("foundDeclaration", declaration)
}
}
)
return declaration
}
val chunks = generateSequence(containingClassId) { it.outerClassId }.toList()
if (chunks.any { it.shortClassName.isSpecial }) {
val fallbackResult = collectDesignationPathWithTreeTraversal(target)
if (fallbackResult != null) {
return fallbackResult
}
}
return chunks
.dropWhile { it.shortClassName.isSpecial }
.map { resolveChunk(it) }
.asReversed()
}
/*
This implementation is certainly inefficient, however there seem to be no better way to implement designation collection for
anonymous outer classes unless FIR tree gets a way to get an element parent.
*/
private fun collectDesignationPathWithTreeTraversal(target: FirDeclaration): List<FirRegularClass>? {
val containingFile = target.getContainingFile() ?: return null
val path = ArrayDeque<FirElement>()
path.addLast(containingFile)
var result: List<FirRegularClass>? = null
val visitor = object : FirVisitorVoid() {
override fun visitElement(element: FirElement) {
if (result != null) {
return
} else if (element === target) {
result = path.filterIsInstance<FirRegularClass>()
} else {
try {
path.addLast(element)
element.acceptChildren(this)
} finally {
path.removeLast()
}
}
}
}
containingFile.accept(visitor)
return result
}
private fun getTargetSession(target: FirDeclaration): FirSession {
if (target is FirCallableDeclaration) {
val containingSymbol = target.containingClassLookupTag()?.toSymbol(target.moduleData.session)
if (containingSymbol != null) {
// Synthetic declarations might have a call site session
return containingSymbol.moduleData.session
}
}
return target.moduleData.session
}
private fun findKotlinStdlibClass(classId: ClassId, target: FirDeclaration): FirRegularClass? {
if (!classId.packageFqName.startsWith(StandardNames.BUILT_INS_PACKAGE_NAME)) {
return null
}
val firFile = target.getContainingFile() ?: return null
return FirElementFinder.findClassifierWithClassId(firFile, classId) as? FirRegularClass
}
fun FirElementWithResolveState.collectDesignation(firFile: FirFile): FirDesignationWithFile =
tryCollectDesignation(firFile) ?: errorWithAttachment("No designation of local declaration") {
withFirEntry("firFile", firFile)
}
fun FirElementWithResolveState.collectDesignation(): FirDesignation =
tryCollectDesignation()
?: errorWithAttachment("No designation of local declaration") {
withFirEntry("FirDeclaration", this@collectDesignation)
}
fun FirElementWithResolveState.collectDesignationWithFile(): FirDesignationWithFile =
tryCollectDesignationWithFile()
?: errorWithAttachment("No designation of local declaration") {
withFirEntry("FirDeclaration", this@collectDesignationWithFile)
}
fun FirElementWithResolveState.tryCollectDesignation(firFile: FirFile): FirDesignationWithFile? =
collectDesignationPath(this)?.let {
FirDesignationWithFile(it, this, firFile)
}
fun FirElementWithResolveState.tryCollectDesignation(): FirDesignation? =
collectDesignationPath(this)?.let {
FirDesignation(it, this)
}
fun FirElementWithResolveState.tryCollectDesignationWithFile(): FirDesignationWithFile? {
return when (this) {
is FirScript, is FirCodeFragment, is FirFileAnnotationsContainer -> {
val firFile = getContainingFile() ?: return null
FirDesignationWithFile(path = emptyList(), this, firFile)
}
is FirSyntheticProperty, is FirSyntheticPropertyAccessor -> unexpectedElementError<FirElementWithResolveState>(this)
is FirDeclaration -> {
val scriptDesignation = scriptDesignation()
if (scriptDesignation != null) return scriptDesignation
val path = collectDesignationPath(this) ?: return null
val firFile = path.lastOrNull()?.getContainingFile() ?: getContainingFile() ?: return null
FirDesignationWithFile(path, this, firFile)
}
else -> unexpectedElementError<FirElementWithResolveState>(this)
}
}
private fun FirDeclaration.scriptDesignation(): FirDesignationWithFile? {
if (this !is FirStatement || !isScriptDependentDeclaration) return null
val firFile = getContainingFile() ?: return null
val firScript = firFile.declarations.singleOrNull() as? FirScript ?: return null
return FirDesignationWithFile(path = emptyList(), firScript, firFile)
}
| 162
| null |
5729
| 46,436
|
c902e5f56504e8572f9bc13f424de8bfb7f86d39
| 11,916
|
kotlin
|
Apache License 2.0
|
domain/domain-usecase/src/main/java/com/odogwudev/example/domain_usecase/auth/LoginWithFacebookAccountUseCase.kt
|
odogwudev
| 592,877,753
| false
| null |
package com.odogwudev.example.domain_usecase.auth
import com.odogwudev.example.firebase_api.AuthenticationService
import kotlinx.coroutines.flow.filterNotNull
class LoginWithFacebookAccountUseCase(private val service: AuthenticationService) {
operator fun invoke() = service.loginWithFacebookAccount().filterNotNull()
}
| 0
|
Kotlin
|
0
| 4
|
82791abdcf1554d2a2cd498a19cd93952f90e53e
| 326
|
CinephilesCompanion
|
MIT License
|
games-impl/src/commonMain/kotlin/net/zomis/games/ur/RoyalGameOfUr.kt
|
Zomis
| 125,767,793
| false
| null |
package net.zomis.games.ur
/*
// 0 = Outside
// 4 = First flower
Fxxx Fx
xxxFxxxx
Fxxx Fx
*/
class RoyalGameOfUr {
constructor() {
this.currentPlayer = 0
this.roll = NOT_ROLLED
this.pieces = Array(2) { IntArray(7) }
}
constructor(currentPlayer: Int, roll: Int, pieces: Array<IntArray>) {
this.currentPlayer = currentPlayer
this.roll = roll
this.pieces = pieces.map { it.copyOf() }.toTypedArray()
}
var currentPlayer: Int private set
var roll: Int = NOT_ROLLED
private set
private val pieces: Array<IntArray>
// pieces[PLAYER][PIECE]
fun isRollTime(): Boolean {
return roll == NOT_ROLLED
}
val isMoveTime: Boolean
get() = roll > 0
val piecesCopy: Array<IntArray>
get() = this.pieces.map { arr -> arr.copyOf() }.toTypedArray()
val isFinished: Boolean
get() = winner != NO_WINNER
val winner: Int
get() {
for (i in this.pieces.indices) {
if (this.pieces[i].all { v -> v == EXIT }) {
return i
}
}
return NO_WINNER
}
fun randomBoolean(): Boolean {
return (0..1).shuffled().first() == 1
}
fun doRoll(): Int {
if (!isRollTime()) {
throw IllegalStateException("Not time to roll. Current roll is $roll")
}
val sum = (0..3).map { if (randomBoolean()) 1 else 0 }.sum()
return doRoll(sum)
}
fun doRoll(sum: Int): Int {
if (canMove(sum)) {
this.roll = sum
} else {
this.nextPlayer()
}
return sum
}
private fun nextPlayer() {
this.currentPlayer = (this.currentPlayer + 1) % 2
}
fun canMove(roll: Int): Boolean {
if (roll == 0) {
return false
}
// Loop through player's pieces and check if they can move `this.roll` steps.
for (i in 0 until this.pieces[currentPlayer].size) {
val position = this.pieces[currentPlayer][i]
val nextPosition = position + roll
if (canMoveTo(currentPlayer, nextPosition)) {
return true
}
}
return false
}
private fun canMoveTo(currentPlayer: Int, nextPosition: Int): Boolean {
if (isFinished) {
return false
}
if (nextPosition == EXIT) {
return true
}
if (nextPosition > EXIT) {
return false
}
if (nextPosition >= 5 && nextPosition <= EXIT - 3) {
// Shared area. Can knock out except on flower.
if (isFlower(nextPosition)) {
for (player in this.pieces.indices) {
if (playerOccupies(player, nextPosition)) {
return false
}
}
return true
} else {
return !playerOccupies(currentPlayer, nextPosition)
}
} else {
// Private area
return !playerOccupies(currentPlayer, nextPosition)
}
}
fun playerOccupies(currentPlayer: Int, position: Int): Boolean {
for (piece in 0 until this.pieces[currentPlayer].size) {
if (this.pieces[currentPlayer][piece] == position) {
return true
}
}
return false
}
fun canMove(playerIndex: Int, position: Int, steps: Int): Boolean {
return playerOccupies(playerIndex, position) && canMoveTo(playerIndex, position + steps)
}
fun move(playerIndex: Int, position: Int, steps: Int): Boolean {
if (isFinished) {
return false
}
if (!canMove(playerIndex, position, steps)) {
return false
}
for (i in 0 until this.pieces[playerIndex].size) {
if (this.pieces[playerIndex][i] == position) {
this.pieces[playerIndex][i] = position + steps
performKnockout(playerIndex, position + steps)
this.roll = NOT_ROLLED
if (!isFlower(position + steps)) {
this.nextPlayer()
}
return true
}
}
return false
}
private fun performKnockout(playerIndex: Int, position: Int) {
val opponent = (playerIndex + 1) % this.pieces.size
if (position <= 4 || position > 12) {
return
}
if (isFlower(position)) {
return
}
for (j in 0 until this.pieces[opponent].size) {
if (this.pieces[opponent][j] == position) {
this.pieces[opponent][j] = 0
}
}
}
fun isFlower(position: Int): Boolean {
return position == 4 || position == 8 || position == EXIT - 1
}
fun canKnockout(position: Int): Boolean {
return position > 4 && position < EXIT - 2 && !isFlower(position)
}
override fun toString(): String {
return "RoyalGameOfUr{" +
"pieces=" + pieces.contentDeepToString() +
", currentPlayer=" + currentPlayer +
", roll=" + roll +
'}'.toString()
}
fun toLong(): Long {
val cp = currentPlayer
val op = 1 - cp
var result: Long = 0
val numberHome1 = pieces[cp].filter { i -> i == 0 }.count()
val numberHome2 = pieces[op].filter { i -> i == 0 }.count()
val numberGoal1 = pieces[cp].filter { i -> i == EXIT }.count()
val numberGoal2 = pieces[op].filter { i -> i == EXIT }.count()
var dice = roll - 1 // 1..4 --> 0..3
if (isFinished) {
dice = 0
} else if (dice < 0 || dice >= 4) {
throw IllegalStateException("Invalid dice value for serializing: $dice")
}
val p1 = piecesToArray(pieces[cp])
val p2 = piecesToArray(pieces[op])
result += numberHome1.toLong()
result = result shl 3
result += numberHome2.toLong()
result = result shl 3
result += numberGoal1.toLong()
result = result shl 3
result += numberGoal2.toLong()
result = result shl 3
result += dice.toLong()
result = result shl 2
for (b in p1) {
result += (if (b) 1 else 0).toLong()
result = result shl 1
}
for (b in p2) {
result += (if (b) 1 else 0).toLong()
result = result shl 1
}
return result
}
private fun piecesToArray(pieces: IntArray): BooleanArray {
val result = BooleanArray(14)
for (p in pieces) {
if (p != 0 && p != 15) {
result[p - 1] = true
}
}
return result
}
fun toCompactString(): String {
val str = StringBuilder()
str.append(currentPlayer)
val p0 = pieces[0].copyOf()
p0.sort()
val p1 = pieces[1].copyOf()
p1.sort()
for (aP0 in p0) {
str.append(aP0)
}
for (aP1 in p1) {
str.append(aP1)
}
return str.toString()
}
fun copy(): RoyalGameOfUr {
return RoyalGameOfUr(this.currentPlayer, this.roll, piecesCopy)
}
companion object {
private val NOT_ROLLED = -1
private val NO_WINNER = -1
val EXIT = 15
}
}
| 89
| null |
5
| 17
|
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
| 7,440
|
Games
|
MIT License
|
app/src/main/java/com/perol/asdpl/pixivez/viewmodel/BlockViewModel.kt
|
ultranity
| 258,955,010
| false
| null |
package com.perol.asdpl.pixivez.viewmodel
import androidx.lifecycle.MutableLiveData
import com.perol.asdpl.pixivez.services.PxEZApp
import com.perol.asdpl.pixivez.sql.AppDatabase
import com.perol.asdpl.pixivez.sql.entity.BlockTagEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.LinkedList
object BlockViewModel{
private val appDatabase = AppDatabase.getInstance(PxEZApp.instance)
var allTags:MutableLiveData<LinkedList<BlockTagEntity>>? = null
private var allTagString:LinkedList<String>? = null
/*private val initTask: Job
init {
initTask = CoroutineScope(Dispatchers.IO).launch{
getAllTags()
}
}*/
fun getBlockTagString(): List<String> {
return allTagString?:
runBlocking(Dispatchers.IO){ fetchAllTags() }.map { it.name }.also { allTagString = LinkedList(it) }
}
fun getBlockTags(): List<String> {
return (allTags?.value?:runBlocking(Dispatchers.IO){ fetchAllTags() }).map { it.name }
}
suspend fun getAllTags() = withContext(Dispatchers.IO) {
//if (initTask.isActive)
// initTask.join()
(allTags?.value?:fetchAllTags()).map{ it.name }
}
suspend fun fetchAllTags() = withContext(Dispatchers.IO) {
allTags = MutableLiveData(LinkedList(appDatabase.blockTagDao().getAllTags()))
allTagString = LinkedList(allTags!!.value!!.map { it.name })
allTags!!.value!!
}
suspend fun deleteSingleTag(blockTagEntity: BlockTagEntity) = withContext(Dispatchers.IO) {
appDatabase.blockTagDao().deleteTag(blockTagEntity)
allTags!!.value!!.remove(blockTagEntity)
allTagString!!.remove(blockTagEntity.name)
}
suspend fun insertBlockTag(blockTagEntity: BlockTagEntity) = withContext(Dispatchers.IO) {
appDatabase.blockTagDao().insert(blockTagEntity)
allTags!!.value!!.addFirst(blockTagEntity)//.name)
allTagString!!.addFirst(blockTagEntity.name)
}
}
| 8
| null |
30
| 553
|
626986fa3c62ff01dc660a1afa993b25c01c24b8
| 2,044
|
Pix-EzViewer
|
MIT License
|
src/main/kotlin/ru/tanec/cookhelper/database/dao/ingredientDao/IngredientDaoImpl.kt
|
Tanexc
| 541,207,479
| false
|
{"Kotlin": 234073, "Procfile": 62}
|
package ru.tanec.cookhelper.database.dao.ingredientDao
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import ru.tanec.cookhelper.core.utils.getPage
import ru.tanec.cookhelper.database.factory.DatabaseFactory.dbQuery
import ru.tanec.cookhelper.database.model.Ingredients
import ru.tanec.cookhelper.enterprise.model.entity.recipe.Ingredient
class IngredientDaoImpl: IngredientDao {
private fun resultRowToIngredient(row: ResultRow): Ingredient = Ingredient(
id = row[Ingredients.id],
title = row[Ingredients.title]
)
private fun ResultRow.toIngredient() = Ingredient(
id=this[Ingredients.id],
title=this[Ingredients.title]
)
override suspend fun getAll(): List<Ingredient> = dbQuery {
Ingredients
.selectAll()
.map(::resultRowToIngredient)
}
override suspend fun getAll(offset: Int, limit: Int): List<Ingredient> = dbQuery {
Ingredients
.selectAll()
.map(::resultRowToIngredient)
.getPage(offset, limit)
}
override suspend fun getById(id: Long): Ingredient? = dbQuery {
Ingredients
.select { Ingredients.id eq id}
.map(::resultRowToIngredient)
.singleOrNull()
}
override suspend fun getByListId(listId: List<Long>, offset: Int, limit: Int): List<Ingredient> = dbQuery {
Ingredients
.select { Ingredients.id inList listId }
.sortedBy { it.toIngredient().title }
.getPage(limit, offset)
.map(::resultRowToIngredient)
}
}
| 0
|
Kotlin
|
2
| 16
|
cdf4edac9f701d3ff9b4afd91f51a4a433d188da
| 1,661
|
CookHelper
|
Apache License 2.0
|
src/test/kotlin/eZmaxApi/models/EzsigndocumentlogResponseTest.kt
|
eZmaxinc
| 271,950,932
| false
|
{"Kotlin": 6909939}
|
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import eZmaxApi.models.EzsigndocumentlogResponseCompound
import eZmaxApi.models.FieldEEzsigndocumentlogType
class EzsigndocumentlogResponseCompoundTest : ShouldSpec() {
init {
// uncomment below to create an instance of EzsigndocumentlogResponseCompound
//val modelInstance = EzsigndocumentlogResponseCompound()
// to test the property `dtEzsigndocumentlogDatetime` - The date and time at which the event was logged
should("test dtEzsigndocumentlogDatetime") {
// uncomment below to test the property
//modelInstance.dtEzsigndocumentlogDatetime shouldBe ("TODO")
}
// to test the property `eEzsigndocumentlogType`
should("test eEzsigndocumentlogType") {
// uncomment below to test the property
//modelInstance.eEzsigndocumentlogType shouldBe ("TODO")
}
// to test the property `sEzsigndocumentlogDetail` - The detail of the Ezsigndocumentlog
should("test sEzsigndocumentlogDetail") {
// uncomment below to test the property
//modelInstance.sEzsigndocumentlogDetail shouldBe ("TODO")
}
// to test the property `sEzsigndocumentlogLastname` - The last name of the User or Ezsignsigner
should("test sEzsigndocumentlogLastname") {
// uncomment below to test the property
//modelInstance.sEzsigndocumentlogLastname shouldBe ("TODO")
}
// to test the property `sEzsigndocumentlogFirstname` - The first name of the User or Ezsignsigner
should("test sEzsigndocumentlogFirstname") {
// uncomment below to test the property
//modelInstance.sEzsigndocumentlogFirstname shouldBe ("TODO")
}
// to test the property `sEzsigndocumentlogIP` - Represent an IP address.
should("test sEzsigndocumentlogIP") {
// uncomment below to test the property
//modelInstance.sEzsigndocumentlogIP shouldBe ("TODO")
}
// to test the property `fkiUserID` - The unique ID of the User
should("test fkiUserID") {
// uncomment below to test the property
//modelInstance.fkiUserID shouldBe ("TODO")
}
// to test the property `fkiEzsignsignerID` - The unique ID of the Ezsignsigner
should("test fkiEzsignsignerID") {
// uncomment below to test the property
//modelInstance.fkiEzsignsignerID shouldBe ("TODO")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
961c97a9f13f3df7986ea7ba55052874183047ab
| 2,860
|
eZmax-SDK-kotlin
|
MIT License
|
src/main/kotlin/jp/nephy/penicillin/endpoints/collections/entries/Remove.kt
|
colt005
| 186,767,944
| true
|
{"Kotlin": 1199305}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.collections.entries
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.session.post
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.CollectionEntries
import jp.nephy.penicillin.models.Collection
/**
* Remove the specified Tweet from a Collection.
* Use [POST collections/entries/curate](https://developer.twitter.com/en/docs/tweets/curate-a-collection/api-reference/post-collections-entries-curate) to remove Tweets from a Collection in bulk.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/tweets/curate-a-collection/api-reference/post-collections-entries-remove)
*
* @param id The identifier of the target Collection.
* @param tweetId The identifier of the Tweet to remove.
* @param options Optional. Custom parameters of this request.
* @receiver [CollectionEntries] endpoint instance.
* @return [JsonObjectApiAction] for [Collection.Entry.Result] model.
*/
fun CollectionEntries.remove(
id: String,
tweetId: Long,
vararg options: Option
) = client.session.post("/1.1/collections/entries/remove.json") {
body {
form {
add(
"id" to id,
"tweet_id" to tweetId,
*options
)
}
}
}.jsonObject<Collection.Entry.Result>()
| 0
|
Kotlin
|
0
| 0
|
d5860e3d9c7c95c7d7ec1879c080b114ca77e127
| 2,588
|
Penicillin
|
MIT License
|
shared/src/commonMain/kotlin/com/aglushkov/wordteacher/shared/features/cardset/vm/CardSetVM.kt
|
soniccat
| 302,971,014
| false
| null |
package com.aglushkov.wordteacher.shared.features.cardset.vm
import com.aglushkov.wordteacher.shared.events.Event
import com.aglushkov.wordteacher.shared.events.FocusViewItemEvent
import com.aglushkov.wordteacher.shared.features.definitions.vm.*
import com.aglushkov.wordteacher.shared.general.*
import com.aglushkov.wordteacher.shared.general.item.BaseViewItem
import com.aglushkov.wordteacher.shared.general.resource.Resource
import com.aglushkov.wordteacher.shared.model.*
import com.aglushkov.wordteacher.shared.repository.cardset.CardSetRepository
import com.aglushkov.wordteacher.shared.repository.db.WordFrequencyGradation
import com.aglushkov.wordteacher.shared.repository.db.WordFrequencyGradationProvider
import com.aglushkov.wordteacher.shared.workers.UPDATE_DELAY
import com.aglushkov.wordteacher.shared.res.MR
import com.aglushkov.wordteacher.shared.workers.DatabaseCardWorker
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import dev.icerock.moko.resources.desc.Resource
import dev.icerock.moko.resources.desc.StringDesc
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
interface CardSetVM: Clearable {
var router: CardSetRouter?
val state: State
val cardSet: StateFlow<Resource<out CardSet>>
val viewItems: StateFlow<Resource<List<BaseViewItem<*>>>>
val eventFlow: Flow<List<Event>>
fun onCardCreatePressed()
fun onCardDeleted(cardId: Long)
fun onPartOfSpeechChanged(newPartOfSpeech: WordTeacherWord.PartOfSpeech, cardId: Long)
fun onItemTextChanged(text: String, item: BaseViewItem<*>, cardId: Long)
fun onAddDefinitionPressed(cardId: Long)
fun onDefinitionRemoved(item: WordDefinitionViewItem, cardId: Long)
fun onAddExamplePressed(cardId: Long)
fun onExampleRemoved(item: WordExampleViewItem, cardId: Long)
fun onAddSynonymPressed(cardId: Long)
fun onSynonymRemoved(item: WordSynonymViewItem, cardId: Long)
fun onBackPressed()
fun onTryAgainClicked()
fun onInfoPressed()
fun getErrorText(res: Resource<List<BaseViewItem<*>>>): StringDesc?
fun getPlaceholder(viewItem: BaseViewItem<*>): StringDesc?
fun onStartLearningClicked()
@Parcelize
data class State (
val cardSetId: Long
): Parcelable
}
open class CardSetVMImpl(
override var state: CardSetVM.State,
private val repository: CardSetRepository,
wordFrequencyGradationProvider: WordFrequencyGradationProvider,
private val databaseCardWorker: DatabaseCardWorker,
private val timeSource: TimeSource,
private val idGenerator: IdGenerator
): ViewModel(), CardSetVM {
override var router: CardSetRouter? = null
private var pendingEvents = mutableListOf<PendingEvent>()
private val notHandledPendingEvents: List<PendingEvent>
get() {
pendingEvents.removeAll { it.isHandled }
return pendingEvents
}
// Contains cards being edited and haven't been synched with DB
private var inMemoryCardSet = MutableStateFlow<CardSet?>(null)
final override val cardSet: StateFlow<Resource<CardSet>> = combine(
repository.cardSet, inMemoryCardSet, databaseCardWorker.untilFirstEditingFlow(),
transform = { cardSet, inMemoryCardSet, state ->
if (state == DatabaseCardWorker.State.EDITING) {
if (inMemoryCardSet == null) {
cardSet
} else {
when (cardSet) {
is Resource.Loaded -> cardSet.copyWith(
mergeCardSets(
cardSet.data,
inMemoryCardSet
)
).also {
pruneInMemoryCardSet(cardSet.data)
}
else -> cardSet
}
}
} else {
Resource.Loading()
}
}).stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
private val events = MutableStateFlow<List<Event>>(emptyList())
override val eventFlow = events.map { eventList -> eventList.filter { !it.isHandled } }
override val viewItems = combine(
cardSet, wordFrequencyGradationProvider.gradationState,
transform = { cardSet, gradation ->
//Logger.v("build view items")
cardSet.copyWith(buildViewItems(cardSet, gradation))
}
).stateIn(viewModelScope, SharingStarted.Eagerly, Resource.Uninitialized())
init {
addClearable(databaseCardWorker.startEditing())
}
fun restore(newState: CardSetVM.State) {
state = newState
viewModelScope.launch {
repository.loadCardSet(state.cardSetId)
}
}
private fun buildViewItems(cardSetRes: Resource<out CardSet>, frequencyGradationRes: Resource<WordFrequencyGradation>): List<BaseViewItem<*>> {
return when (cardSetRes) {
is Resource.Loaded -> {
makeViewItems(cardSetRes.data, frequencyGradationRes.data())
}
else -> emptyList()
}
}
private fun mergeCardSets(dbCardSet: CardSet, inMemoryCardSet: CardSet): CardSet {
// replace db cards with in-memory cards
//Logger.v("merge cardSet $dbCardSet\n with $inMemoryCardSet")
return dbCardSet.copy(
cards = dbCardSet.cards.map {
inMemoryCardSet.findCard(it.id) ?: it
}
)
}
private fun pruneInMemoryCardSet(dbCardSet: CardSet) {
// remove equal sets from inMemoryCardSet
inMemoryCardSet.update {
it?.copy(
cards = it.cards.filter { inMemoryCard ->
dbCardSet.findCard(inMemoryCard.id) != inMemoryCard
}
)
}
}
private fun makeViewItems(loadedCardSet: CardSet, frequencyGradation: WordFrequencyGradation?): List<BaseViewItem<*>> {
val result = mutableListOf<BaseViewItem<*>>()
loadedCardSet.cards.onEach { card ->
var lastDefViewItem: BaseViewItem<*>? = null
var lastExViewItem: BaseViewItem<*>? = null
var lastSynViewItem: BaseViewItem<*>? = null
val cardViewItems = mutableListOf<BaseViewItem<*>>()
val gradationLevelAndRatio = frequencyGradation?.gradationLevelAndRatio(card.termFrequency)
cardViewItems += WordTitleViewItem(
card.term,
providers = emptyList(),
cardId = card.id,
frequencyLevelAndRatio = gradationLevelAndRatio,
)
cardViewItems += WordTranscriptionViewItem(card.transcription.orEmpty(), cardId = card.id)
cardViewItems += WordPartOfSpeechViewItem(card.partOfSpeech.toStringDesc(), card.partOfSpeech, cardId = card.id)
if (card.definitions.isEmpty()) {
cardViewItems += WordDefinitionViewItem("", index = 0, isLast = true, cardId = card.id)
} else {
card.definitions.onEachIndexed { index, def ->
cardViewItems += WordDefinitionViewItem(def, index = index, isLast = index == card.definitions.size - 1, cardId = card.id).also {
lastDefViewItem = it
}
}
}
// Examples
cardViewItems += WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_examples),
Indent.SMALL,
isOnlyHeader = card.examples.isEmpty(),
contentType = WordSubHeaderViewItem.ContentType.EXAMPLES,
cardId = card.id
)
card.examples.onEachIndexed { index, example ->
cardViewItems += WordExampleViewItem(example, Indent.SMALL, index, isLast = index == card.examples.size - 1, cardId = card.id).also {
lastExViewItem = it
}
}
// Synonyms
cardViewItems += WordSubHeaderViewItem(
StringDesc.Resource(MR.strings.word_section_synonyms),
Indent.SMALL,
isOnlyHeader = card.synonyms.isEmpty(),
contentType = WordSubHeaderViewItem.ContentType.SYNONYMS,
cardId = card.id
)
card.synonyms.onEachIndexed { index, synonym ->
cardViewItems += WordSynonymViewItem(synonym, Indent.SMALL, index, isLast = index == card.synonyms.size - 1, cardId = card.id).also {
lastSynViewItem = it
}
}
result += cardViewItems
result += WordDividerViewItem()
makeFocusEvents(card.id, lastDefViewItem, lastExViewItem, lastSynViewItem)
}
result += CreateCardViewItem()
generateIds(result)
return result
}
private fun makeFocusEvents(cardId: Long, lastDefViewItem: BaseViewItem<*>?, lastExViewItem: BaseViewItem<*>?, lastSynViewItem: BaseViewItem<*>?) {
val filteredEvents = this.events.value.filter { it !is FocusViewItemEvent }
this.notHandledPendingEvents.onEach {
when (val e = it) {
is PendingEvent.FocusLast -> {
lastDefViewItem?.let { safeItem ->
if (e.type == FocusLastType.Definition && e.cardId == cardId) {
events.value = filteredEvents + e.makeEvent(safeItem)
}
}
lastExViewItem?.let { safeItem ->
if (e.type == FocusLastType.Example && e.cardId == cardId) {
events.value = filteredEvents + e.makeEvent(safeItem)
}
}
lastSynViewItem?.let { safeItem ->
if (e.type == FocusLastType.Synonym && e.cardId == cardId) {
events.value = filteredEvents + e.makeEvent(safeItem)
}
}
}
}
}
}
private fun generateIds(items: MutableList<BaseViewItem<*>>) {
val prevItems = viewItems.value.data().orEmpty()
if (items.size == prevItems.size) { // keep ids not to recompose text fields being edited
prevItems.onEachIndexed { index, baseViewItem ->
items[index].id = baseViewItem.id
}
} else { // regenerate not to mix up with current ids where swipeable cells are in hidden state
items.onEach {
it.id = idGenerator.nextId()
}
}
}
override fun onTryAgainClicked() {
// TODO: do sth with articlesRepository
}
override fun onInfoPressed() {
router?.openCardSetInfo(state.cardSetId)
}
override fun onItemTextChanged(text: String, item: BaseViewItem<*>, cardId: Long) {
editCard(cardId) { card ->
val newCard = when (item) {
is WordTitleViewItem ->
card.copy(
term = if (card.term != text) {
text
} else {
card.term
},
)
is WordTranscriptionViewItem ->
card.copy(
transcription = if (card.transcription != text) {
text
} else {
card.transcription
},
)
is WordDefinitionViewItem -> {
card.copy(
definitions = if (card.definitions.isEmpty()) {
listOf(text)
} else {
card.definitions.mapIndexed { index, s ->
if (item.index == index) {
text
} else {
s
}
}
},
needToUpdateDefinitionSpans = true,
)
}
is WordExampleViewItem ->
card.copy(
examples = card.examples.mapIndexed { index, s ->
if (item.index == index) {
text
} else {
s
}
},
needToUpdateExampleSpans = true,
)
is WordSynonymViewItem ->
card.copy(
synonyms = card.synonyms.mapIndexed { index, s ->
if (item.index == index) {
text
} else {
s
}
},
)
else -> card
}
if (newCard != card) {
updateCard(newCard)
}
newCard
}
}
private fun editCard(cardId: Long, transform: (card: Card) -> Card) {
val cardSet = obtainInMemoryCardSet(cardId) ?: return
inMemoryCardSet.update {
cardSet.copy(
cards = cardSet.cards.map {
if (it.id == cardId) {
transform(it)
} else {
it
}
},
)
}
}
private fun obtainInMemoryCardSet(cardId: Long): CardSet? {
val resultSet = inMemoryCardSet.value ?: cardSet.value.data()?.copy(cards = emptyList()) ?: return null
val inMemoryCard = inMemoryCardSet.value?.findCard(cardId)
val modifiedSet = if (inMemoryCard != null) {
resultSet
} else {
val cardSetCard = cardSet.value.data()?.findCard(cardId) ?: return null
resultSet.copy(
cards = resultSet.cards + cardSetCard
)
}
inMemoryCardSet.update { modifiedSet }
return modifiedSet
}
override fun onAddDefinitionPressed(cardId: Long) {
pendingEvents.add(PendingEvent.FocusLast(FocusLastType.Definition, cardId))
return editCard(cardId) {
it.copy(
definitions = if (it.definitions.lastOrNull() != "") {
it.definitions + ""
} else {
it.definitions
},
)
}
}
override fun onDefinitionRemoved(item: WordDefinitionViewItem, cardId: Long) =
editCard(cardId) {
it.copy(
definitions = if (it.definitions.size <= 1) {
listOf("")
} else {
it.definitions.filterIndexed { i, _ -> i != item.index }
},
needToUpdateDefinitionSpans = true,
).apply {
updateCard(this, delay = 0)
}
}
override fun onAddExamplePressed(cardId: Long) {
pendingEvents.add(PendingEvent.FocusLast(FocusLastType.Example, cardId))
return editCard(cardId) {
it.copy(
examples = if (it.examples.lastOrNull() != "") {
it.examples + ""
} else {
it.examples
},
)
}
}
override fun onExampleRemoved(item: WordExampleViewItem, cardId: Long) =
editCard(cardId) {
it.copy(
examples = it.examples.filterIndexed { i, _ -> i != item.index },
needToUpdateExampleSpans = true,
).apply {
updateCard(this, delay = 0)
}
}
override fun onAddSynonymPressed(cardId: Long) {
pendingEvents.add(PendingEvent.FocusLast(FocusLastType.Synonym, cardId))
editCard(cardId) {
it.copy(
synonyms = if (it.synonyms.lastOrNull() != "") {
it.synonyms + ""
} else {
it.synonyms
},
)
}
}
override fun onSynonymRemoved(item: WordSynonymViewItem, cardId: Long) =
editCard(cardId) {
it.copy(
synonyms = it.synonyms.filterIndexed { i, _ -> i != item.index },
).apply {
updateCard(this, delay = 0)
}
}
override fun onCardCreatePressed() {
viewModelScope.launch {
repository.createCard()
}
}
override fun onCardDeleted(cardId: Long) {
findCard(cardId)?.let { card ->
viewModelScope.launch {
databaseCardWorker.deleteCard(card, timeSource.timeInMilliseconds())
}
}
}
override fun onPartOfSpeechChanged(newPartOfSpeech: WordTeacherWord.PartOfSpeech, cardId: Long) =
editCard(cardId) {
it.copy(
partOfSpeech = newPartOfSpeech,
).apply {
updateCard(this)
}
}
private fun updateCard(card: Card, delay: Long = UPDATE_DELAY) {
databaseCardWorker.updateCardCancellable(card, delay, timeSource.timeInMilliseconds())
}
override fun onBackPressed() {
router?.closeCardSet()
}
override fun getErrorText(res: Resource<List<BaseViewItem<*>>>): StringDesc? {
return StringDesc.Resource(MR.strings.article_error)
}
override fun getPlaceholder(viewItem: BaseViewItem<*>): StringDesc? {
return when (val v = viewItem) {
is WordTitleViewItem -> StringDesc.Resource(MR.strings.card_title_placeholder)
is WordTranscriptionViewItem -> StringDesc.Resource(MR.strings.card_transcription_placeholder)
else -> null
}
}
private fun findCard(id: Long): Card? =
inMemoryCardSet.value?.findCard(id) ?: cardSet.value.data()?.findCard(id)
override fun onStartLearningClicked() {
viewModelScope.launch {
try {
cardSet.value.data()?.let { set ->
val allCardIds = set.cards.filter {
it.progress.isReadyToLearn(timeSource)
}.map { it.id }
router?.openLearning(allCardIds)
}
} catch (e: Throwable) {
// TODO: handle error
}
}
}
enum class FocusLastType {
Definition,
Example,
Synonym
}
sealed class PendingEvent(var isHandled: Boolean = false) {
data class FocusLast(val type: FocusLastType, val cardId: Long): PendingEvent() {
var prevEvent: FocusViewItemEvent? = null
fun makeEvent(viewItem: BaseViewItem<*>): FocusViewItemEvent {
prevEvent?.markAsHandled()
val newEvent = object : FocusViewItemEvent(viewItem) {
override fun markAsHandled() {
super.markAsHandled()
this@FocusLast.isHandled = true
}
}
prevEvent = newEvent
return newEvent
}
}
}
}
| 0
| null |
1
| 3
|
d853cd31e7a609777bffb6ceef18461cccf8222d
| 19,498
|
WordTeacher
|
MIT License
|
app/src/main/java/com/android/saman/sample/androidmvvm/repository/RetrofitService.kt
|
samesl
| 277,223,969
| false
| null |
package com.android.saman.sample.androidmvvm.repository
class RetrofitService() {
//TODO : TO BE COMPLETED
}
| 1
|
Kotlin
|
1
| 0
|
d8ab01e692b285c630b5e7feca2fd01e812b3125
| 117
|
Android-MVVM
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ec2/CfnNetworkInsightsAnalysisDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.ec2
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.services.ec2.CfnNetworkInsightsAnalysis
import software.constructs.Construct
/**
* Specifies a network insights analysis.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ec2.*;
* CfnNetworkInsightsAnalysis cfnNetworkInsightsAnalysis =
* CfnNetworkInsightsAnalysis.Builder.create(this, "MyCfnNetworkInsightsAnalysis")
* .networkInsightsPathId("networkInsightsPathId")
* // the properties below are optional
* .additionalAccounts(List.of("additionalAccounts"))
* .filterInArns(List.of("filterInArns"))
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html)
*/
@CdkDslMarker
public class CfnNetworkInsightsAnalysisDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnNetworkInsightsAnalysis.Builder =
CfnNetworkInsightsAnalysis.Builder.create(scope, id)
private val _additionalAccounts: MutableList<String> = mutableListOf()
private val _filterInArns: MutableList<String> = mutableListOf()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* The member accounts that contain resources that the path can traverse.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-additionalaccounts)
*
* @param additionalAccounts The member accounts that contain resources that the path can
* traverse.
*/
public fun additionalAccounts(vararg additionalAccounts: String) {
_additionalAccounts.addAll(listOf(*additionalAccounts))
}
/**
* The member accounts that contain resources that the path can traverse.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-additionalaccounts)
*
* @param additionalAccounts The member accounts that contain resources that the path can
* traverse.
*/
public fun additionalAccounts(additionalAccounts: Collection<String>) {
_additionalAccounts.addAll(additionalAccounts)
}
/**
* The Amazon Resource Names (ARN) of the resources that the path must traverse.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-filterinarns)
*
* @param filterInArns The Amazon Resource Names (ARN) of the resources that the path must
* traverse.
*/
public fun filterInArns(vararg filterInArns: String) {
_filterInArns.addAll(listOf(*filterInArns))
}
/**
* The Amazon Resource Names (ARN) of the resources that the path must traverse.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-filterinarns)
*
* @param filterInArns The Amazon Resource Names (ARN) of the resources that the path must
* traverse.
*/
public fun filterInArns(filterInArns: Collection<String>) {
_filterInArns.addAll(filterInArns)
}
/**
* The ID of the path.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-networkinsightspathid)
*
* @param networkInsightsPathId The ID of the path.
*/
public fun networkInsightsPathId(networkInsightsPathId: String) {
cdkBuilder.networkInsightsPathId(networkInsightsPathId)
}
/**
* The tags to apply.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-tags)
*
* @param tags The tags to apply.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* The tags to apply.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinsightsanalysis.html#cfn-ec2-networkinsightsanalysis-tags)
*
* @param tags The tags to apply.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnNetworkInsightsAnalysis {
if (_additionalAccounts.isNotEmpty()) cdkBuilder.additionalAccounts(_additionalAccounts)
if (_filterInArns.isNotEmpty()) cdkBuilder.filterInArns(_filterInArns)
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 4
| null |
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 5,481
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
radiolib/src/main/java/com/brins/radiolib/fragment/RadioRecFragment.kt
|
BrinsLee
| 297,821,918
| false
| null |
package com.brins.radiolib.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import com.brins.baselib.cache.login.LoginCache
import com.brins.baselib.fragment.BaseMvvmFragment
import com.brins.baselib.module.BaseData
import com.brins.baselib.module.ITEM_RADIO_RECOMMEND_DATA
import com.brins.baselib.mvp.IModel
import com.brins.baselib.mvvm.BaseViewModel
import com.brins.baselib.route.ARouterUtils
import com.brins.baselib.route.RouterHub
import com.brins.baselib.utils.convertNumMillion
import com.brins.baselib.utils.glidehelper.GlideHelper
import com.brins.networklib.helper.ApiHelper
import com.brins.networklib.model.follow.FollowData
import com.brins.networklib.model.personal.PersonalizedMusicList
import com.brins.networklib.model.radio.Radio
import com.brins.networklib.model.radio.RadioData
import com.brins.radiolib.R
import com.brins.radiolib.viewmodel.RadioViewModel
import com.chad.library.adapter.base2.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base2.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.fragment_radio_rec.*
class RadioRecFragment : BaseMvvmFragment<RadioViewModel>() {
private var mRadioDataObserver: Observer<MutableList<Radio>>? = null
private var mAdapter: RadioAdapter? = null
override fun getViewModel(): BaseViewModel<out IModel>? {
return RadioViewModel.getInstance(mActivity!!.application)
}
override fun getLayoutResID(): Int {
return R.layout.fragment_radio_rec
}
override fun reLoad() {
}
override fun needParent(): Boolean {
return false
}
override fun useEventBus(): Boolean {
return false
}
override fun init(savedInstanceState: Bundle?) {
super.init(savedInstanceState)
mAdapter = RadioAdapter()
rv_recommend_radio.adapter = mAdapter
rv_recommend_radio.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
val snapHelper = PagerSnapHelper()
snapHelper.attachToRecyclerView(rv_recommend_radio)
mRadioDataObserver = Observer {
val list = mutableListOf<BaseData>()
list.addAll(it)
mAdapter!!.setNewData(list)
}
mViewModel?.getRadioLiveData()?.observe(this, mRadioDataObserver!!)
ApiHelper.launch({
mViewModel?.getRecommendRadio()
}, {})
}
class RadioAdapter : BaseMultiItemQuickAdapter<BaseData, BaseViewHolder>() {
init {
addItemType(ITEM_RADIO_RECOMMEND_DATA, R.layout.radio_item_recommend_radio)
}
override fun convert(helper: BaseViewHolder, item: BaseData) {
when (item.itemType) {
ITEM_RADIO_RECOMMEND_DATA -> {
helper.setText(R.id.name, (item as Radio).name)
helper.setText(R.id.playCount, "${convertNumMillion(item.playCount)}")
GlideHelper.setRoundImageResource(helper.getView(R.id.cover), item.picUrl, 10)
helper.getView<View>(R.id.rootLayout).setOnClickListener {
val bundle = Bundle()
bundle.putInt(
"mPos", helper.adapterPosition
)
bundle.putString(
"mRadioId", item.id
)
ARouterUtils.go(RouterHub.RADIODETAILACTIVITY, bundle)
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
}
}
| 0
|
Kotlin
|
0
| 1
|
37cbd7448ebfc23475c00462018f6d70c74631e1
| 3,842
|
Music
|
Apache License 2.0
|
app/src/main/java/com/caron/instagram/data/NotificationsRepository.kt
|
iamCaron
| 301,796,709
| false
| null |
package com.caron.instagram.data
import android.arch.lifecycle.LiveData
import com.caron.instagram.models.Notification
import com.google.android.gms.tasks.Task
interface NotificationsRepository {
fun createNotification(uid: String, notification: Notification): Task<Unit>
fun getNotifications(uid: String): LiveData<List<Notification>>
fun setNotificationsRead(uid: String, ids: List<String>, read: Boolean): Task<Unit>
}
| 0
|
Kotlin
|
0
| 0
|
1af9710a74ca414490012438806c3510c7eb6a17
| 435
|
Instagram-Clone-Kotlin-master
|
MIT License
|
src/main/kotlin/io/github/dockyardmc/protocol/packets/login/LoginHandler.kt
|
DockyardMC
| 650,731,309
| false
|
{"Kotlin": 1019371}
|
package io.github.dockyardmc.protocol.packets.login
import cz.lukynka.prettylog.LogType
import cz.lukynka.prettylog.log
import io.github.dockyardmc.DockyardServer
import io.github.dockyardmc.config.ConfigManager
import io.github.dockyardmc.entities.EntityManager
import io.github.dockyardmc.extentions.sendPacket
import io.github.dockyardmc.player.*
import io.github.dockyardmc.player.kick.KickReason
import io.github.dockyardmc.player.kick.getSystemKickMessage
import io.github.dockyardmc.protocol.ChannelHandlers
import io.github.dockyardmc.protocol.PlayerNetworkManager
import io.github.dockyardmc.protocol.cryptography.PacketDecryptionHandler
import io.github.dockyardmc.protocol.cryptography.PacketEncryptionHandler
import io.github.dockyardmc.protocol.packets.PacketHandler
import io.github.dockyardmc.protocol.packets.ProtocolState
import io.github.dockyardmc.protocol.packets.handshake.ServerboundHandshakePacket
import io.github.dockyardmc.runnables.AsyncRunnable
import io.github.dockyardmc.utils.MojangUtil
import io.github.dockyardmc.utils.debug
import io.github.dockyardmc.world.WorldManager
import io.ktor.util.network.*
import io.netty.channel.ChannelHandlerContext
import java.security.KeyPairGenerator
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
class LoginHandler(var processor: PlayerNetworkManager) : PacketHandler(processor) {
fun handleHandshake(packet: ServerboundHandshakePacket, connection: ChannelHandlerContext) {
processor.playerProtocolVersion = packet.version
processor.state = ProtocolState.LOGIN
}
fun handleLoginStart(packet: ServerboundLoginStartPacket, connection: ChannelHandlerContext) {
val name = packet.name
val uuid = packet.uuid
debug("Received login start packet with name $name and UUID $uuid", logType = LogType.DEBUG)
if (!DockyardServer.allowAnyVersion) {
val playerVersion = processor.playerProtocolVersion
val requiredVersion = DockyardServer.minecraftVersion.protocolId
if (processor.playerProtocolVersion != requiredVersion) {
connection.sendPacket(
ClientboundLoginDisconnectPacket(
getSystemKickMessage(
"You are using incompatible version <red>($playerVersion)<gray>. Please use version <yellow>${DockyardServer.minecraftVersion.versionName}<gray>",
KickReason.INCOMPATIBLE_VERSION.name
)
), processor
)
return
}
}
val dummyCrypto = PlayerCrypto()
val player = Player(
username = name,
entityId = EntityManager.entityIdCounter.incrementAndGet(),
uuid = uuid,
world = WorldManager.mainWorld,
address = connection.channel().remoteAddress().address,
crypto = dummyCrypto,
connection = connection,
networkManager = processor
)
PlayerManager.add(player, processor)
EntityManager.entities.add(player)
if (ConfigManager.config.useMojangAuth) {
val generator = KeyPairGenerator.getInstance("RSA")
generator.initialize(1024)
val keyPair = generator.generateKeyPair()
val privateKey = keyPair.private
val publicKey = keyPair.public
val secureRandom = SecureRandom()
val verificationToken = ByteArray(4)
secureRandom.nextBytes(verificationToken)
val playerCrypto = PlayerCrypto(publicKey, privateKey, verificationToken)
player.crypto = playerCrypto
// pre-cache the skin
val asyncRunnable = AsyncRunnable {
MojangUtil.getSkinFromUUID(player.uuid)
}
asyncRunnable.run()
val out = ClientboundEncryptionRequestPacket("", publicKey.encoded, verificationToken, true)
connection.sendPacket(out, processor)
} else {
finishEncryption(player)
}
}
fun handleEncryptionResponse(packet: ServerboundEncryptionResponsePacket, connection: ChannelHandlerContext) {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.DECRYPT_MODE, processor.player.crypto.privateKey)
val verifyToken = cipher.doFinal(packet.verifyToken)
val sharedSecret = cipher.doFinal(packet.sharedSecret)
if (!verifyToken.contentEquals(processor.player.crypto.verifyToken)) log(
"Verify Token of player ${processor.player.username} does not match!",
LogType.ERROR
)
processor.player.crypto.sharedSecret = SecretKeySpec(sharedSecret, "AES")
processor.player.crypto.isConnectionEncrypted = true
processor.encryptionEnabled = true
val pipeline = connection.channel().pipeline()
pipeline.addBefore(ChannelHandlers.FRAME_DECODER, ChannelHandlers.PACKET_DECRYPTOR, PacketDecryptionHandler(processor.player.crypto))
pipeline.addBefore(ChannelHandlers.PACKET_DECRYPTOR, ChannelHandlers.PACKET_ENCRYPTOR, PacketEncryptionHandler(processor.player.crypto))
val player = processor.player
finishEncryption(player)
}
fun handleLoginAcknowledge(packet: ServerboundLoginAcknowledgedPacket, connection: ChannelHandlerContext) {
processor.state = ProtocolState.CONFIGURATION
}
fun finishEncryption(player: Player) {
val list = mutableListOf<ProfilePropertyMap>()
val texturesProperty = ProfileProperty("textures", "", true, "")
val texturesPropertyMap = ProfilePropertyMap(player.username, mutableListOf(texturesProperty))
list.add(texturesPropertyMap)
player.profile = texturesPropertyMap
player.sendPacket(ClientboundSetCompressionPacket(-1))
player.sendPacket(ClientboundLoginSuccessPacket(player.uuid, player.username, list))
}
}
| 9
|
Kotlin
|
7
| 55
|
9a0eb8f3184123b79b835356ddde526d9eb6df65
| 6,012
|
Dockyard
|
MIT License
|
app/src/main/java/com/fappslab/rickandmortygraphql/Application.kt
|
F4bioo
| 585,168,438
| false
| null |
package com.fappslab.rickandmortygraphql
import android.app.Application
import com.fappslab.rickandmortygraphql.core.data.local.di.LocalModule
import com.fappslab.rickandmortygraphql.features.details.di.DetailsModule
import com.fappslab.rickandmortygraphql.di.AppModule
import com.fappslab.rickandmortygraphql.features.filter.di.FilterModule
import com.fappslab.rickandmortygraphql.features.home.di.HomeModule
import com.fappslab.rickandmortygraphql.core.data.hubsrc.di.HubSrcModule
import com.fappslab.rickandmortygraphql.core.data.remote.di.RemoteModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.loadKoinModules
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.core.context.unloadKoinModules
import org.koin.core.logger.Level
import org.koin.core.module.Module
import org.koin.dsl.KoinAppDeclaration
class Application : Application() {
private val modules by lazy {
AppModule.modules +
HubSrcModule.modules +
LocalModule.modules +
RemoteModule.modules +
HomeModule.modules +
DetailsModule.modules +
FilterModule.modules
}
override fun onCreate() {
super.onCreate()
startKoin(appDeclaration = appDeclaration())
modules.load()
}
override fun onTerminate() {
modules.unload()
stopKoin()
super.onTerminate()
}
private fun appDeclaration(): KoinAppDeclaration = {
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(androidContext = this@Application)
}
private fun List<Module>.load() {
loadKoinModules(modules = this)
}
private fun List<Module>.unload() {
unloadKoinModules(modules = this)
}
}
| 0
|
Kotlin
|
0
| 0
|
b2a46bb919d7159c8417832a731798fdb9d159e9
| 1,887
|
RickAndMorty-GraphQL
|
MIT License
|
app/src/main/java/com/ardakazanci/weatherapp/data/ResponseClasses.kt
|
ardakazanci
| 226,705,095
| false
| null |
package com.ardakazanci.weatherapp.data
data class ForecastResult(val city: City, val list: List<Forecast>)
data class City(val id: Long,
val name: String,
val coord: Coordinates,
val country: String,
val population: Int)
data class Coordinates(val lon: Float,
val lat: Float)
data class Forecast(val dt: Long,
val temp: Temperature,
val pressure: Float,
val humidity: Int,
val weather: List<Weather>,
val speed: Float,
val deg: Int,
val clouds: Int,
val rain: Float)
data class Temperature(val day: Float,
val min: Float,
val max: Float,
val night: Float,
val eve: Float,
val morn: Float)
data class Weather(val id: Long,
val main: String,
val description: String,
val icon: String)
| 1
| null |
1
| 1
|
f5da890cdab37b562afa6992ceaa87f90a0deda2
| 1,109
|
KotlinForForecast
|
Apache License 2.0
|
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day08.kt
|
jmerle
| 434,010,865
| false
|
{"Kotlin": 60581}
|
package com.jaspervanmerle.aoc2021.day
class Day08 : Day("321", "1028926") {
private data class Entry(val signalPatterns: List<String>, val outputPatterns: List<String>)
private val entries = input
.lines()
.map { it.split(" | ") }
.map { Entry(it[0].split(" "), it[1].split(" ")) }
private val segmentIndicesByDigit = mapOf(
0 to listOf(0, 1, 2, 4, 5, 6),
1 to listOf(2, 5),
2 to listOf(0, 2, 3, 4, 6),
3 to listOf(0, 2, 3, 5, 6),
4 to listOf(1, 2, 3, 5),
5 to listOf(0, 1, 3, 5, 6),
6 to listOf(0, 1, 3, 4, 5, 6),
7 to listOf(0, 2, 5),
8 to listOf(0, 1, 2, 3, 4, 5, 6),
9 to listOf(0, 1, 2, 3, 5, 6)
)
override fun solvePartOne(): Any {
return entries
.flatMap { it.outputPatterns }
.map { it.length }
.count { it == 2 || it == 4 || it == 3 || it == 7 }
}
override fun solvePartTwo(): Any {
val segmentsPermutations = generateSegmentsPermutations()
return entries.sumOf { entry ->
val segments = segmentsPermutations.find { segments ->
entry.signalPatterns.all { patternToDigit(it, segments) != null }
}!!
(0 until 4)
.map { patternToDigit(entry.outputPatterns[it], segments) }
.joinToString("")
.toInt()
}
}
private fun generateSegmentsPermutations(
prefix: String = "abcdefg",
suffix: String = "",
generatedPermutations: MutableList<String> = mutableListOf()
): List<String> {
if (prefix.isEmpty()) {
generatedPermutations.add(suffix)
} else {
for (i in prefix.indices) {
generateSegmentsPermutations(
prefix.substring(0, i) + prefix.substring(i + 1),
suffix + prefix[i],
generatedPermutations
)
}
}
return generatedPermutations
}
private fun patternToDigit(pattern: String, segments: String): Int? {
outer@ for ((digit, segmentIndices) in segmentIndicesByDigit) {
if (pattern.length != segmentIndices.size) {
continue
}
for (index in segmentIndices) {
if (segments[index] !in pattern) {
continue@outer
}
}
return digit
}
return null
}
}
| 0
|
Kotlin
|
0
| 0
|
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
| 2,515
|
advent-of-code-2021
|
MIT License
|
lib/src/main/kotlin/ca/objectobject/hexlr/eval/patterns/Lists.kt
|
object-Object
| 785,042,451
| false
|
{"Kotlin": 71222, "ANTLR": 3483, "Makefile": 227}
|
package ca.objectobject.hexlr.eval.patterns
import ca.objectobject.hexlr.eval.*
import ca.objectobject.hexlr.eval.iotas.Iota
import ca.objectobject.hexlr.eval.iotas.ListIota
import ca.objectobject.hexlr.eval.iotas.NumberIota
import ca.objectobject.hexlr.eval.iotas.toIota
data object OpEmptyList : ConstPattern(ListIota())
data object OpSingletonList : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(iota: Iota) = ListIota(iota)
}
data object OpSlurpList : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(runtime: Runtime, length: NumberIota): ListIota {
val values = pop(runtime, length.value.toInt())
return ListIota(values)
}
}
data object OpSplatList : TypedPatternMulti() {
override val eval: EvalMulti = ::eval
fun eval(list: ListIota) = list.values
}
data object OpSelect : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, index: NumberIota) = list.values[index.value.toInt()]
}
data object OpSlice : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, from: NumberIota, to: NumberIota) =
ListIota(list.values.subList(from.value.toInt(), to.value.toInt()))
}
data object OpAppend : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, iota: Iota) = ListIota(list.values + iota)
}
data object OpConcat : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(left: ListIota, right: ListIota) = ListIota(left.values + right.values)
}
data object OpListLen : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota) = list.values.count().toIota()
}
data object OpReverse : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota) = ListIota(list.values.asReversed())
}
data object OpIndexOf : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, iota: Iota) = list.values.indexOf(iota).toIota()
}
data object OpRemove : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, index: NumberIota) = ListIota(list.values.toMutableList().apply {
removeAt(index.value.toInt())
})
}
data object OpInsert : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, index: NumberIota, iota: Iota) = ListIota(list.values.toMutableList().apply {
set(index.value.toInt(), iota)
})
}
data object OpPushFirst : TypedPatternSingle() {
override val eval: EvalSingle = ::eval
fun eval(list: ListIota, iota: Iota) = ListIota(listOf(iota) + list.values)
}
data object OpPopFirst : TypedPatternMulti() {
override val eval: EvalMulti = ::eval
fun eval(list: ListIota) = list.values.run {
listOf(ListIota(subList(1, lastIndex + 1)), get(0))
}
}
| 0
|
Kotlin
|
0
| 0
|
1e37e162dc41b1a7fbcfa32c9700f33f8e8c187d
| 2,948
|
compilers-course-project
|
MIT License
|
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/AnnotationLowering.kt
|
walltz556
| 224,251,838
| true
|
{"Kotlin": 39975052, "Java": 7599429, "JavaScript": 160572, "HTML": 75060, "Lex": 23159, "TypeScript": 21255, "IDL": 11582, "ANTLR": 9803, "CSS": 8084, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "Scala": 80}
|
/*
* Copyright 2010-2018 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.backend.jvm.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.phaser.makeIrFilePhase
import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrConstructor
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.util.isAnnotationClass
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
internal val annotationPhase = makeIrFilePhase<JvmBackendContext>(
{ AnnotationLowering() },
name = "Annotation",
description = "Remove constructors of annotation classes"
)
/**
* Remove the constructors from annotation classes.
*/
private class AnnotationLowering : FileLoweringPass, IrElementTransformerVoid() {
override fun lower(irFile: IrFile) = irFile.transformChildrenVoid(this)
override fun visitClass(declaration: IrClass): IrStatement {
if (!declaration.isAnnotationClass) return super.visitClass(declaration)
declaration.declarations.removeIf {
it is IrConstructor
}
return declaration
}
}
| 0
| null |
0
| 1
|
89d49479abab76ea1d4ffe5e45826f3b076c6f68
| 1,503
|
kotlin
|
Apache License 2.0
|
core/src/commonMain/kotlin/maryk/core/extensions/bytes/Int.kt
|
marykdb
| 290,454,412
| false
|
{"Kotlin": 3313154, "JavaScript": 1004}
|
package maryk.core.extensions.bytes
import maryk.lib.exceptions.ParseException
import kotlin.experimental.and
import kotlin.experimental.xor
/** Write the bytes of this Int to a [writer] */
internal fun Int.writeBytes(writer: (byte: Byte) -> Unit, length: Int = 4) {
if (length !in 3..4) {
throw IllegalArgumentException("Length should be within range of 3 to 4")
}
for (it in 0 until length) {
val b = (this shr (length - 1 - it) * 8 and 0xFF).toByte()
writer(
if (it == 0) b xor SIGN_BYTE else b
)
}
}
/** Creates Integer by reading bytes from [reader] */
internal fun initInt(reader: () -> Byte, length: Int = 4): Int {
var int = 0
val firstByte = reader()
// Skip bytes if below certain length
if (length < 4) {
if (firstByte and SIGN_BYTE != SIGN_BYTE) { // Set to max byte to have correct value if negative
int = int xor 0xFF
}
int = int shl 8 * (8 - length)
}
int = int xor ((firstByte xor SIGN_BYTE).toInt() and 0xFF)
for (it in 1 until length) {
int = int shl 8
int = int xor (reader().toInt() and 0xFF)
}
return int
}
/**
* Encodes the Int in zigzag pattern so negative values are
* able to encode much more efficiently into varInt
*/
internal fun Int.encodeZigZag() = this shl 1 xor (this shr 31)
/** Decodes the Int out of zigzag pattern so bytes have the normal native order again */
internal fun Int.decodeZigZag() = this ushr 1 xor -(this and 1)
/** Write the bytes of this Int as a variable int to a [writer] */
fun Int.writeVarBytes(writer: (byte: Byte) -> Unit) {
var value = this
while (true) {
if (value and 0x7F.inv() == 0) {
writer(value.toByte())
return
} else {
writer((value and 0x7F or 0x80).toByte())
value = value ushr 7
}
}
}
/** Convert Int to byte array with variable encoding */
fun Int.toVarBytes() =
ByteArray(this.calculateVarByteLength()).also { bytes ->
var index = 0
this.writeVarBytes {
bytes[index++] = it
}
}
/** Creates Integer by reading bytes encoded with variable length from [reader] */
fun initIntByVar(reader: () -> Byte): Int {
var shift = 0
var result = 0
while (shift < 32) {
val b = reader().toInt()
result = result or ((b and 0x7F) shl shift)
if (b and 0x80 == 0) {
return result
}
shift += 7
}
throw ParseException("Malformed varInt")
}
/** Calculates the byte length of the variable int */
fun Int.calculateVarByteLength(): Int = when {
this and (Int.MAX_VALUE shl 7) == 0 -> 1
this and (Int.MAX_VALUE shl 14) == 0 -> 2
this and (Int.MAX_VALUE shl 21) == 0 -> 3
this and (Int.MAX_VALUE shl 28) == 0 -> 4
else -> 5
}
/** Write the bytes of this Int in little endian order to a [writer] */
internal fun Int.writeLittleEndianBytes(writer: (byte: Byte) -> Unit) {
for (it in 0..3) {
writer(
(this shr it * 8 and 0xFF).toByte()
)
}
}
/** Creates Integer by reading bytes in little endian order from [reader] */
internal fun initIntLittleEndian(reader: () -> Byte) =
(reader().toInt() and 0xff) or
((reader().toInt() and 0xff) shl 8) or
((reader().toInt() and 0xff) shl 16) or
((reader().toInt() and 0xff) shl 24)
/** Write the key for ProtoBuf field */
internal fun Int.writeVarIntWithExtraInfo(extraInfo: Byte, writer: (byte: Byte) -> Unit) {
val byteSize = this.calculateVarIntWithExtraInfoByteSize()
// Write Int (I) + Extra Info (X) + potential sign byte (S) (SIII IXXX)
writer(
(
((this shl 3).toByte() and 0b0111_1000) // Add first part of tag to byte
xor (extraInfo and 0b111) // Add ExtraInfo to byte
) xor if (byteSize > 1) SIGN_BYTE else ZERO_BYTE // Add Sign byte if total is longer than 5 bytes
)
// Write any needed extra byte for the Int as a VarInt
if (byteSize > 1) {
for (it in 1 until byteSize) {
val isLast = it == byteSize - 1
writer(
(this shr (7*it-3)).toByte() and SEVEN_BYTES xor if(isLast) ZERO_BYTE else SIGN_BYTE
)
}
}
}
/**
* Reads a var Int from [reader] with extra info encoded in last 3 bytes
* which is forwarded as Int to [objectCreator] to create object of type [T] with first the normal Int
* and then the extra info Int
*
* This is based on ProtoBuf encoding
*/
internal fun <T> initIntByVarWithExtraInfo(reader: () -> Byte, objectCreator: (Int, Byte) -> T): T {
var byte = reader()
val wireTypeByte = byte and 0b111
var result = (byte and 0b0111_1000).toInt() shr 3
if (byte and SIGN_BYTE == ZERO_BYTE) {
return objectCreator(result, wireTypeByte)
}
var shift = 4
while (shift < 35) {
byte = reader()
result = result or ((byte and 0b0111_1111).toInt() shl shift)
if (byte and SIGN_BYTE == ZERO_BYTE) {
return objectCreator(result, wireTypeByte)
}
shift += 7
}
throw ParseException("Too big tag")
}
/** Calculates the byte length of the variable int with extra info */
fun Int.calculateVarIntWithExtraInfoByteSize(): Int = when {
this and (Int.MAX_VALUE shl 4) == 0 -> 1
this and (Int.MAX_VALUE shl 11) == 0 -> 2
this and (Int.MAX_VALUE shl 18) == 0 -> 3
this and (Int.MAX_VALUE shl 25) == 0 -> 4
else -> 5
}
| 1
|
Kotlin
|
1
| 8
|
7d71064056cdff61fa01feb1f3a9201dc0c9ec34
| 5,495
|
maryk
|
Apache License 2.0
|
app/src/main/java/com/initiatetech/initiate_news/viewmodel/UserViewModel.kt
|
Gemnnn
| 747,026,324
| false
|
{"Kotlin": 104052}
|
package com.initiatetech.initiate_news.viewmodel
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.initiatetech.initiate_news.api.RetrofitClient
import com.initiatetech.initiate_news.model.ApiResponse
import com.initiatetech.initiate_news.model.PreferenceData
import com.initiatetech.initiate_news.model.PreferenceResponse
import com.initiatetech.initiate_news.model.User
import com.initiatetech.initiate_news.repository.PreferenceRepository
import com.initiatetech.initiate_news.repository.UserRepository
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.ref.WeakReference
class UserViewModel(private val userRepository: UserRepository,
private val preferenceRepository: PreferenceRepository,
context: Context?
) : ViewModel() {
private val contextRef: WeakReference<Context> = WeakReference(context)
private val context: Context?
get() = contextRef.get()
// LiveData for login status
private val _loginStatus = MutableLiveData<LoginStatus>()
val loginStatus: LiveData<LoginStatus> = _loginStatus
// LiveData for registration status
private val _registrationStatus = MutableLiveData<RegistrationStatus>()
val registrationStatus: LiveData<RegistrationStatus> = _registrationStatus
// LiveData for logout status
private val _logoutStatus = MutableLiveData<LogoutStatus>()
val logoutStatus: LiveData<LogoutStatus> = _logoutStatus
val preferenceUpdateStatus = MutableLiveData<Boolean>()
fun loginUser(email: String, password: String) {
val loginInfo = User(email, password) // Assuming UserLogin is similar or use User directly if same attributes
Log.d("Login", "Start")
userRepository.loginUser(loginInfo).enqueue(object : Callback<ApiResponse> {
override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
if (response.isSuccessful && response.body()?.isSuccess == true) {
// Store the user's email upon successful login
saveUserEmail(loginInfo.email)
Log.d("Login", "success")
_loginStatus.value = LoginStatus.SUCCESS
} else {
Log.d("Login", "fail")
_loginStatus.value = LoginStatus.FAILURE
}
}
override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
_loginStatus.value = LoginStatus.ERROR
}
})
}
private fun saveUserEmail(email: String) {
val sharedPref = context?.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
val editor = sharedPref?.edit()
editor?.putString("user_email", email)
editor?.apply()
}
public fun getUserEmail(): String? {
val sharedPref = context?.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
return sharedPref?.getString("user_email", null)
}
fun getProvince(): String {
val sharedPref = contextRef.get()?.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
return sharedPref?.getString("user_province", "Unknown Province") ?: "Unknown Province"
}
fun logoutUser() {
userRepository.logoutUser().enqueue(object : Callback<ApiResponse> {
override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
if (response.isSuccessful && response.body()?.isSuccess == true) {
Log.d("Logout", "success")
_logoutStatus.value = LogoutStatus.SUCCESS
} else {
Log.d("Logout", "fail")
_logoutStatus.value = LogoutStatus.FAILURE
}
}
override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
_logoutStatus.value = LogoutStatus.ERROR
}
})
}
fun registerUser(email: String, password: String) {
val newUser = User(email, password) // Corrected to create a new User instance
Log.d("Registration", "Start")
userRepository.registerUser(newUser).enqueue(object : Callback<ApiResponse> { // Corrected to pass newUser
override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
if (response.isSuccessful && response.body()?.isSuccess == true) {
Log.d("Registration", "success")
_registrationStatus.value = RegistrationStatus.SUCCESS
} else {
Log.d("Registration", "fail")
_registrationStatus.value = RegistrationStatus.FAILURE
}
}
override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
_registrationStatus.value = RegistrationStatus.ERROR
}
})
}
fun getPreferences(callback: (PreferenceResponse?) -> Unit) {
val userEmail = getUserEmail()
if (userEmail != null) {
RetrofitClient.instance.getPreferences(userEmail).enqueue(object : Callback<PreferenceResponse> {
override fun onResponse(call: Call<PreferenceResponse>, response: Response<PreferenceResponse>) {
if (response.isSuccessful) {
response.body()?.let {
// Check for null and provide a default value if needed
val province = it.province ?: "Unknown Province"
saveProvince(province)
}
callback(response.body())
} else {
callback(null)
}
}
override fun onFailure(call: Call<PreferenceResponse>, t: Throwable) {
callback(null)
}
})
} else {
callback(null)
}
}
fun setPreferences(language: String, province: String, country: String, newsGenerationTime: String, isSetPreference: Boolean) {
val preferences = PreferenceData(language, province, country, newsGenerationTime, getUserEmail(), isSetPreference)
Log.d("Preferences", "setPreferences Start")
preferenceRepository.setPreferences(preferences).enqueue(object : Callback<ApiResponse> {
override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
if (response.isSuccessful && response.body()?.isSuccess == true) {
Log.d("Preferences", "setPreferences Successful response")
preferenceUpdateStatus.postValue(true)
saveProvince(province)
} else {
Log.d("Preferences", "setPreferences failed response")
preferenceUpdateStatus.postValue(false)
}
}
override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
Log.e("Preferences", "setPreferences Error", t)
preferenceUpdateStatus.postValue(false)
}
})
}
private fun saveProvince(province: String) {
val sharedPref = contextRef.get()?.getSharedPreferences("my_prefs", Context.MODE_PRIVATE) ?: return
with(sharedPref.edit()) {
putString("user_province", province)
apply()
}
}
enum class LoginStatus {
SUCCESS,
FAILURE,
ERROR
}
enum class RegistrationStatus {
SUCCESS,
FAILURE,
ERROR
}
enum class LogoutStatus {
SUCCESS,
FAILURE,
ERROR
}
class UserViewModelFactory(private val userRepository: UserRepository,
private val preferenceRepository: PreferenceRepository,
private val context: Context?
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return UserViewModel(userRepository, preferenceRepository, context) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
}
| 1
|
Kotlin
|
0
| 1
|
b1d106bfde7e90ac3bbee22e349f32d2b7a11bf5
| 8,524
|
Initiate-News
|
MIT License
|
catalog-updater/src/main/kotlin/io/datalbry/plugin/catalog/updater/CatalogUpdaterPlugin.kt
|
datalbry
| 403,714,662
| false
|
{"Kotlin": 21074}
|
package io.datalbry.plugin.catalog.updater
import org.gradle.api.Plugin
import org.gradle.api.Project
@Suppress("unused")
class CatalogUpdaterPlugin: Plugin<Project> {
override fun apply(project: Project) {
setupExtensions(project)
setupTasks(project)
}
private fun setupExtensions(project: Project) {
project.extensions.create(EXTENSION_NAME, CatalogUpdaterPluginExtension::class.java, project)
}
private fun setupTasks(project: Project) {
project.tasks.register("updateCatalog", CatalogUpdateTask::class.java)
}
companion object {
const val EXTENSION_NAME = "catalogUpdater"
}
}
| 0
|
Kotlin
|
1
| 1
|
e5451c32343806646954e9b5d9e258fd50240783
| 659
|
gradle-plugin-version-catalog-updater
|
Apache License 2.0
|
app/src/main/java/com/devmartyniuk/nasa/api/implementation/layer/ui/main/ViewModelMain.kt
|
Igor-Martynyuk
| 598,247,560
| false
| null |
package com.devmartyniuk.nasa.api.implementation.layer.ui.main
import androidx.lifecycle.*
import com.devmartyniuk.nasa.api.implementation.layer.data.rest.neo.ws.RetrofitGatewayNeoWS
import com.devmartyniuk.nasa.api.implementation.layer.domain.get.neo.CaseGetNearEarthObjectList
import com.devmartyniuk.nasa.api.implementation.layer.domain.get.neo.dto.NearEarthObject
import com.hadilq.liveevent.LiveEvent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
class ViewModelMain : ViewModel() {
private val _errorData = LiveEvent<Throwable?>()
val errorData = _errorData as LiveData<Throwable?>
private val _isInProgressData = MutableLiveData(false)
val isInProgressData get() = _isInProgressData as LiveData<Boolean>
private val _nearEarthObjectsData = MutableLiveData(listOf<NearEarthObject>())
val nearEarthObjectsData get() = _nearEarthObjectsData as LiveData<List<NearEarthObject>>
private val httpClient = OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.addInterceptor {
it.proceed(
it.request()
.newBuilder()
.addHeader("ContentScope-Type", "application/json")
.build()
)
}
.addInterceptor {
val original = it.request()
it.proceed(
original.newBuilder()
.url(
original
.url
.newBuilder()
.addQueryParameter(
"api_key",
"b5E4vg5K4TTksRxgaZzjSldHlnKhM1TfbsW7Cg9K"
)
.build(),
)
.build()
)
}
.build()
private val gateway: RetrofitGatewayNeoWS = RetrofitGatewayNeoWS(
Retrofit.Builder()
.client(httpClient)
.baseUrl("https://api.nasa.gov/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
)
fun onViewReady() = viewModelScope.launch {
_nearEarthObjectsData.value = CaseGetNearEarthObjectList(gateway)
.prepare(Unit)
.flowOn(Dispatchers.IO)
.onStart { _isInProgressData.value = true }
.onCompletion { _isInProgressData.value = false }
.catch { _errorData.value = it }
.toList()
}
}
| 0
|
Kotlin
|
0
| 0
|
a0e950f50ade6c328c87f3f3227a8acc4873a067
| 2,896
|
NASA-API-Implementation
|
Apache License 2.0
|
app/src/main/java/com/mindhub/view/composables/MeasureViewWidth.kt
|
grupo-bala
| 682,555,434
| false
|
{"Kotlin": 293077, "HTML": 179400}
|
package com.mindhub.view.composables
import androidx.compose.runtime.Composable
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
@Composable
fun MeasureViewWidth(
viewToMeasure: @Composable () -> Unit,
content: @Composable (measuredWidth: Dp) -> Unit,
) {
SubcomposeLayout() { constraints ->
val measuredWidth = subcompose("viewToMeasure", viewToMeasure)[0]
.measure(Constraints()).width.toDp()
val contentPlaceable = subcompose("content") {
content(measuredWidth)
}[0].measure(constraints)
layout(contentPlaceable.width, contentPlaceable.height) {
contentPlaceable.place(0, 0)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
83fac46be55e0003c5dd52914811976ca263029f
| 760
|
mindhub-android
|
MIT License
|
sample-app-resources/src/full/java/com/flaviofaria/catalog/sample/resources/FullActivity.kt
|
flavioarfaria
| 491,564,487
| false
|
{"Kotlin": 151002, "Shell": 314}
|
package com.flaviofaria.catalog.sample.resources
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.flaviofaria.catalog.runtime.resources.Plurals
class FullActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Plurals.somePlural(1, 2, 3)
}
}
| 0
|
Kotlin
|
2
| 143
|
04948f5d5dd6894c59802e60a263391e332b03e4
| 357
|
Catalog
|
Apache License 2.0
|
frontend/screen/manual/src/commonMain/kotlin/com/mindovercnc/linuxcnc/screen/manual/turning/ui/axis/AxisCoordinates.kt
|
85vmh
| 543,628,296
| false
| null |
package com.mindovercnc.linuxcnc.screen.manual.root.axis
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.unit.dp
import com.mindovercnc.model.CoordinatesUiData
import com.mindovercnc.model.CoordinateAxis
private val axisItemModifier = Modifier.fillMaxWidth().height(80.dp).padding(8.dp)
@Composable
fun AxisCoordinates(
uiData: CoordinatesUiData,
xToolOffsetsClicked: () -> Unit,
zToolOffsetsClicked: () -> Unit,
onZeroPosX: () -> Unit,
onZeroPosZ: () -> Unit,
onToggleAbsRelX: () -> Unit,
onToggleAbsRelZ: () -> Unit,
modifier: Modifier = Modifier,
) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(bottomEnd = 8.dp),
border = BorderStroke(0.5.dp, SolidColor(Color.DarkGray)),
color = MaterialTheme.colorScheme.surfaceVariant
) {
Column {
uiData.x?.let { xCoordinate ->
AxisCoordinate(
CoordinateAxis.X,
uiModel = xCoordinate,
isDiameterMode = true,
zeroPosClicked = onZeroPosX,
absRelClicked = onToggleAbsRelX,
toolOffsetsClicked = xToolOffsetsClicked,
modifier = axisItemModifier,
)
}
// uiData.y?.let {
// AxisCoordinate(
// CoordinateAxis.Y,
// zeroPosClicked = onZeroPosZ,
// absRelClicked = onToggleAbsRelZ,
// toolOffsetsClicked = zToolOffsetsClicked,
// modifier = axisItemModifier,
// )
// }
uiData.z?.let { zCoordinate ->
AxisCoordinate(
CoordinateAxis.Z,
uiModel = zCoordinate,
zeroPosClicked = onZeroPosZ,
absRelClicked = onToggleAbsRelZ,
toolOffsetsClicked = zToolOffsetsClicked,
modifier = axisItemModifier,
)
}
}
}
}
| 0
| null |
1
| 3
|
5cf42426895ba8691c9b53ba1b97c274bbdabc07
| 2,636
|
mindovercnclathe
|
Apache License 2.0
|
wrapper/godot-library/src/main/kotlin/godot/generated/PathFollow2D.kt
|
payload
| 189,718,948
| true
|
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
|
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch")
package godot
import godot.gdnative.*
import godot.core.*
import godot.utils.*
import godot.icalls.*
import kotlinx.cinterop.*
// NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG
open class PathFollow2D : Node2D {
constructor() : super("PathFollow2D")
constructor(variant: Variant) : super(variant)
internal constructor(mem: COpaquePointer) : super(mem)
internal constructor(name: String) : super(name)
// Enums
// Signals
class Signal {
companion object {
}
}
companion object {
infix fun from(other: Node2D): PathFollow2D = PathFollow2D("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: CanvasItem): PathFollow2D = PathFollow2D("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Node): PathFollow2D = PathFollow2D("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Object): PathFollow2D = PathFollow2D("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Variant): PathFollow2D = fromVariant(PathFollow2D(""), other)
// Constants
}
// Properties
open var offset: Double
get() = _icall_Double(getOffsetMethodBind, this.rawMemory)
set(value) = _icall_Unit_Double(setOffsetMethodBind, this.rawMemory, value)
open var unitOffset: Double
get() = _icall_Double(getUnitOffsetMethodBind, this.rawMemory)
set(value) = _icall_Unit_Double(setUnitOffsetMethodBind, this.rawMemory, value)
open var hOffset: Double
get() = _icall_Double(getHOffsetMethodBind, this.rawMemory)
set(value) = _icall_Unit_Double(setHOffsetMethodBind, this.rawMemory, value)
open var vOffset: Double
get() = _icall_Double(getVOffsetMethodBind, this.rawMemory)
set(value) = _icall_Unit_Double(setVOffsetMethodBind, this.rawMemory, value)
open var rotate: Boolean
get() = _icall_Boolean(isRotatingMethodBind, this.rawMemory)
set(value) = _icall_Unit_Boolean(setRotateMethodBind, this.rawMemory, value)
open var cubicInterp: Boolean
get() = _icall_Boolean(getCubicInterpolationMethodBind, this.rawMemory)
set(value) = _icall_Unit_Boolean(setCubicInterpolationMethodBind, this.rawMemory, value)
open var loop: Boolean
get() = _icall_Boolean(hasLoopMethodBind, this.rawMemory)
set(value) = _icall_Unit_Boolean(setLoopMethodBind, this.rawMemory, value)
open var lookahead: Double
get() = _icall_Double(getLookaheadMethodBind, this.rawMemory)
set(value) = _icall_Unit_Double(setLookaheadMethodBind, this.rawMemory, value)
// Methods
private val setOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_offset") }
open fun setOffset(offset: Double) {
_icall_Unit_Double(setOffsetMethodBind, this.rawMemory, offset)
}
private val getOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_offset") }
open fun getOffset(): Double {
return _icall_Double(getOffsetMethodBind, this.rawMemory)
}
private val setHOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_h_offset") }
open fun setHOffset(hOffset: Double) {
_icall_Unit_Double(setHOffsetMethodBind, this.rawMemory, hOffset)
}
private val getHOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_h_offset") }
open fun getHOffset(): Double {
return _icall_Double(getHOffsetMethodBind, this.rawMemory)
}
private val setVOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_v_offset") }
open fun setVOffset(vOffset: Double) {
_icall_Unit_Double(setVOffsetMethodBind, this.rawMemory, vOffset)
}
private val getVOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_v_offset") }
open fun getVOffset(): Double {
return _icall_Double(getVOffsetMethodBind, this.rawMemory)
}
private val setUnitOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_unit_offset") }
open fun setUnitOffset(unitOffset: Double) {
_icall_Unit_Double(setUnitOffsetMethodBind, this.rawMemory, unitOffset)
}
private val getUnitOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_unit_offset") }
open fun getUnitOffset(): Double {
return _icall_Double(getUnitOffsetMethodBind, this.rawMemory)
}
private val setRotateMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_rotate") }
open fun setRotate(enable: Boolean) {
_icall_Unit_Boolean(setRotateMethodBind, this.rawMemory, enable)
}
private val isRotatingMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "is_rotating") }
open fun isRotating(): Boolean {
return _icall_Boolean(isRotatingMethodBind, this.rawMemory)
}
private val setCubicInterpolationMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_cubic_interpolation") }
open fun setCubicInterpolation(enable: Boolean) {
_icall_Unit_Boolean(setCubicInterpolationMethodBind, this.rawMemory, enable)
}
private val getCubicInterpolationMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_cubic_interpolation") }
open fun getCubicInterpolation(): Boolean {
return _icall_Boolean(getCubicInterpolationMethodBind, this.rawMemory)
}
private val setLoopMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_loop") }
open fun setLoop(loop: Boolean) {
_icall_Unit_Boolean(setLoopMethodBind, this.rawMemory, loop)
}
private val hasLoopMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "has_loop") }
open fun hasLoop(): Boolean {
return _icall_Boolean(hasLoopMethodBind, this.rawMemory)
}
private val setLookaheadMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "set_lookahead") }
open fun setLookahead(lookahead: Double) {
_icall_Unit_Double(setLookaheadMethodBind, this.rawMemory, lookahead)
}
private val getLookaheadMethodBind: CPointer<godot_method_bind> by lazy { getMB("PathFollow2D", "get_lookahead") }
open fun getLookahead(): Double {
return _icall_Double(getLookaheadMethodBind, this.rawMemory)
}
}
| 0
|
Kotlin
|
1
| 2
|
70473f9b9a0de08d82222b735e7f9b07bbe91700
| 6,685
|
kotlin-godot-wrapper
|
Apache License 2.0
|
app/src/main/java/wannabit/io/cosmostaion/database/model/BaseAccount.kt
|
cosmostation
| 418,314,439
| false
| null |
package wannabit.io.cosmostaion.database.model
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import net.i2p.crypto.eddsa.Utils
import wannabit.io.cosmostaion.chain.CosmosLine
import wannabit.io.cosmostaion.chain.EthereumLine
import wannabit.io.cosmostaion.chain.allCosmosLines
import wannabit.io.cosmostaion.chain.allEvmLines
import wannabit.io.cosmostaion.common.BaseKey
import wannabit.io.cosmostaion.common.CosmostationConstants
import wannabit.io.cosmostaion.database.AppDatabase
import wannabit.io.cosmostaion.database.CryptoHelper
import wannabit.io.cosmostaion.database.Prefs
import java.math.BigDecimal
import java.util.UUID
@Entity(tableName = "account")
@Parcelize
data class BaseAccount(
@ColumnInfo(name = "uuid") var uuid: String,
@ColumnInfo(name = "resource") var resource: String,
@ColumnInfo(name = "spec") var spec: String,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "type") var type: BaseAccountType = BaseAccountType.NONE,
@ColumnInfo(name = "lastHDPath") var lastHDPath: String,
@ColumnInfo(name = "sortOrder") var sortOrder: Long = 999
) : Parcelable {
@IgnoredOnParcel
@PrimaryKey(autoGenerate = true)
var id: Long = 0
@IgnoredOnParcel
@delegate:Ignore
val seed: ByteArray? by lazy {
CryptoHelper.doDecryptData(
CosmostationConstants.ENCRYPT_MNEMONIC_KEY + uuid, resource, spec
)?.let { hexEntropy ->
BaseKey.getHDSeed(Utils.hexToBytes(hexEntropy))
}
}
@IgnoredOnParcel
@delegate:Ignore
val privateKey: ByteArray? by lazy {
Utils.hexToBytes(
CryptoHelper.doDecryptData(
CosmostationConstants.ENCRYPT_PRIVATE_KEY + uuid, resource, spec
)
)
}
@IgnoredOnParcel
@Ignore
var allEvmLineChains: MutableList<EthereumLine> = mutableListOf()
@IgnoredOnParcel
@Ignore
var allCosmosLineChains: MutableList<CosmosLine> = mutableListOf()
fun initAccount() {
allEvmLineChains = allEvmLines()
allCosmosLineChains = allCosmosLines()
if (type == BaseAccountType.PRIVATE_KEY) {
allCosmosLineChains =
allCosmosLines().filter { it.isDefault || it.tag == "okt996_Secp" }.toMutableList()
}
sortLine()
}
fun sortedDisplayEvmLines(): MutableList<EthereumLine> {
val displayNames = Prefs.getDisplayEvmChains(this)
return allEvmLineChains.associateBy { line ->
displayNames.firstOrNull { it == line.tag }
}.filterKeys { it != null }.map { it.value }.toMutableList()
}
fun sortLine() {
val displayEvmChains = Prefs.getDisplayEvmChains(this)
val displayCosmosChains = Prefs.getDisplayChains(this)
allEvmLineChains.sortWith { o1, o2 ->
when {
o1.tag == "ethereum60" -> -1
o2.tag == "ethereum60" -> 1
lastValue(o1.tag) > lastValue(o2.tag) -> -1
lastValue(o1.tag) < lastValue(o2.tag) -> 1
else -> 0
}
}
allEvmLineChains.sortWith { o1, o2 ->
when {
o1.tag == "ethereum60" -> -1
o2.tag == "ethereum60" -> 1
displayEvmChains.contains(o1.tag) && !displayEvmChains.contains(o2.tag) -> -1
displayEvmChains.contains(o2.tag) && !displayEvmChains.contains(o1.tag) -> 1
else -> 0
}
}
allCosmosLineChains.sortWith { o1, o2 ->
when {
o1.tag == "cosmos118" -> -1
o2.tag == "cosmos118" -> 1
lastValue(o1.tag) > lastValue(o2.tag) -> -1
lastValue(o1.tag) < lastValue(o2.tag) -> 1
else -> 0
}
}
allCosmosLineChains.sortWith { o1, o2 ->
when {
o1.tag == "cosmos118" -> -1
o2.tag == "cosmos118" -> 1
displayCosmosChains.contains(o1.tag) && !displayCosmosChains.contains(o2.tag) -> -1
displayCosmosChains.contains(o2.tag) && !displayCosmosChains.contains(o1.tag) -> 1
else -> 0
}
}
}
fun sortedDisplayCosmosLines(): MutableList<CosmosLine> {
val displayNames = Prefs.getDisplayChains(this)
return allCosmosLineChains.associateBy { line ->
displayNames.firstOrNull { it == line.tag }
}.filterKeys { it != null }.map { it.value }.toMutableList()
}
fun updateAllValue() {
sortedDisplayCosmosLines().forEach { line ->
line.allValue(false)
}
}
private fun lastValue(tag: String): BigDecimal {
return AppDatabase.getInstance().refAddressDao().selectRefAddress(id, tag)?.lastUsdValue()
?: BigDecimal.ZERO
}
fun reSortEvmChains(): MutableList<CosmosLine> {
val sortedList = allEvmLineChains.sortedWith { o1, o2 ->
when {
o1.tag == "ethereum60" -> -1
o2.tag == "ethereum60" -> 1
else -> o2.allValue(true).compareTo(o1.allValue(true))
}
}
return sortedList.toMutableList()
}
fun reSortCosmosChains(): MutableList<CosmosLine> {
val sortedList = allCosmosLineChains.sortedWith { o1, o2 ->
when {
o1.tag == "cosmos118" -> -1
o2.tag == "cosmos118" -> 1
else -> o2.allValue(true).compareTo(o1.allValue(true))
}
}
return sortedList.toMutableList()
}
companion object {
fun createByMnemonic(name: String, mnemonic: String, lastHDPath: String): BaseAccount? {
val uuid = UUID.randomUUID().toString()
val encR = CryptoHelper.doEncryptData(
CosmostationConstants.ENCRYPT_MNEMONIC_KEY + uuid, mnemonic, false
)
return if (encR != null) {
BaseAccount(
uuid,
encR.encDataString!!,
encR.ivDataString!!,
name,
BaseAccountType.MNEMONIC,
lastHDPath
)
} else {
null
}
}
fun createByPrivate(name: String, privateKey: String): BaseAccount? {
val uuid = UUID.randomUUID().toString()
val encR = CryptoHelper.doEncryptData(
CosmostationConstants.ENCRYPT_PRIVATE_KEY + uuid, privateKey, false
)
return if (encR != null) {
BaseAccount(
uuid,
encR.encDataString!!,
encR.ivDataString!!,
name,
BaseAccountType.PRIVATE_KEY,
"0"
)
} else {
null
}
}
}
}
enum class BaseAccountType { MNEMONIC, PRIVATE_KEY, LEDGER, NONE }
| 1
| null |
43
| 76
|
4d2de2e7f06bd98c156f7695f8da363d5a402762
| 7,164
|
cosmostation-android
|
MIT License
|
mobile/src/test/java/lt/neworld/randomdecision2/extensions/IntKtTest.kt
|
neworld
| 55,846,624
| false
| null |
package lt.neworld.randomdecision2.extensions
import org.junit.Test
import kotlin.test.assertEquals
/**
* @author <NAME>
* *
* @since 2016-04-17
*/
class IntKtTest {
@Test
fun testNormalize() {
assertEquals(-1, -50.normalize())
assertEquals(0, 0.normalize())
assertEquals(1, 40.normalize())
}
}
| 1
|
Kotlin
|
0
| 0
|
bf87e3ee97a905e374432e4e17911ccfae7c0bf3
| 337
|
random-decision
|
Apache License 2.0
|
app/src/main/java/vinova/henry/com/hotfilm/server/ServiceGenerator.kt
|
henryduong26
| 120,248,676
| false
|
{"Kotlin": 175185, "Java": 1151}
|
package vinova.henry.com.hotfilm.server
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import vinova.henry.com.hotfilm.BASE_URL
class ServiceGenerator{
companion object {
val theMovieDBService: ITheMovieDBService = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build().create(ITheMovieDBService::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
97db98daa63c275b69cbb4b8e9887af6f9d16ada
| 454
|
HotFilm
|
Apache License 2.0
|
sample/src/main/java/com/anggrayudi/materialpreference/sample/App.kt
|
anggrayudi
| 139,258,858
| false
| null |
package com.anggrayudi.materialpreference.sample
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Environment
import com.anggrayudi.materialpreference.PreferenceManager
import com.anggrayudi.materialpreference.PreferenceManager.Companion.KEY_HAS_SET_DEFAULT_VALUES
import com.anggrayudi.materialpreference.migration.MigrationPlan
import com.anggrayudi.materialpreference.migration.PreferenceMigration
import org.koin.android.ext.android.get
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import org.koin.dsl.module
class App : Application() {
override fun onCreate() {
super.onCreate()
initKoin()
initSharedPreferences()
}
private fun initSharedPreferences() {
/*
DO NOT USE THIS METHOD to set your preferences' default value. It is inefficient!!!
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
USE THE FOLLOWING TECHNIQUE INSTEAD
*/
val preferences = get<SharedPreferences>()
if (preferences.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {
/*
You can use PreferenceMigration if you want to update your SharedPreferences.
This commented method migrates your SharedPreferences in background thread,
hence there'is no guarantee that it will be completed before activity creation.
Since my main activity is SettingsActivity, I wont call this method here because it may
causes crash while SettingsActivity is rendering preferences layout and the migration
is in progress. In real case, your main activity might not be a settings activity,
so you should not worry about this.
PreferenceMigration.setupMigration(MyPreferenceMigration(), preferences, PREFERENCE_VERSION)
*/
} else {
preferences.edit()
.putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true)
// Always set preference version to the latest for the first time
.putInt(PreferenceMigration.DEFAULT_PREFERENCE_VERSION_KEY, PREFERENCE_VERSION)
.apply()
setDefaultPreferenceValues(this)
}
}
private fun initKoin() {
// Koin Dependency Injection
startKoin {
androidContext(applicationContext)
val preferencesHelperModule = module {
factory { PreferenceManager.getDefaultSharedPreferences(get()) }
factory { SharedPreferencesHelper(get()) }
}
modules(preferencesHelperModule)
}
}
private inner class MyPreferenceMigration : PreferenceMigration {
override fun migrate(plan: MigrationPlan, currentPreferenceVersion: Int) {
var currentVersionTemp = currentPreferenceVersion
if (currentVersionTemp == 0) {
plan.updateValue(PrefKey.ENABLE_DARK_THEME, false)
currentVersionTemp++
}
if (currentVersionTemp == 1) {
plan.updateValue(PrefKey.ENABLE_DARK_THEME, "yes")
currentVersionTemp++
}
// Last IF condition must be "PREFERENCE_VERSION - 1", i.e. 2
if (currentVersionTemp == 2) {
plan.renameKey(PrefKey.ENABLE_DARK_THEME, "useDarkTheme")
currentVersionTemp++
}
}
override fun onNewOS(plan: MigrationPlan, previousOSVersion: Int) {
/*
For example:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
// do your action, such as removing preferences
}
*/
}
override fun onMigrationCompleted(preferences: SharedPreferences) {
//no-op
}
}
companion object {
private const val PREFERENCE_VERSION = 3
/**
* Create custom `setDefaultPreferenceValues()` where setting some default values require
* logic and does not covered by [SharedPreferencesHelper.setDefaultPreferenceValues].
*/
@Suppress("DEPRECATION")
fun setDefaultPreferenceValues(context: Context) {
SharedPreferencesHelper.setDefaultPreferenceValues(context)
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
preferences.edit()
.putString("backupLocation", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
.putInt("themeColor", Color.parseColor("#37474F"))
.apply()
}
}
}
| 0
| null |
21
| 92
|
34b2b884d8742a3cbd6c4f1c87604d77f15464d7
| 4,743
|
MaterialPreference
|
Apache License 2.0
|
src/main/kotlin/io/github/tassiluca/scalaextras/ScalaExtrasPlugin.kt
|
tassiluca
| 823,219,684
| false
|
{"Kotlin": 10522, "Scala": 1300, "JavaScript": 807}
|
package io.github.tassiluca.scalaextras
import cz.augi.gradle.scalafmt.ScalafmtPlugin
import io.github.cosmicsilence.scalafix.ScalafixExtension
import io.github.cosmicsilence.scalafix.ScalafixPlugin
import io.github.cosmicsilence.scalafix.ScalafixTask
import io.github.tassiluca.scalaextras.ScalaCompilerOptions.FAIL_ON_WARNINGS
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.scala.ScalaCompile
import cz.augi.gradle.scalafmt.PluginExtension as ScalafmtExtension
/** The scala extras plugin entry point. */
class ScalaExtrasPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project.plugins) {
apply(ScalafmtPlugin::class.java)
apply(ScalafixPlugin::class.java)
}
val extension = project.extensions.create("scalaExtras", ScalaExtrasExtension::class.java, project)
project.configureScalaFmt(extension.qa.scalafmtConfiguration)
project.configureScalafix(extension.qa.scalafixConfiguration)
project.configureFormatTask()
project.configureCompilerOptions(extension)
}
private fun Project.configureScalaFmt(configuration: ScalafmtConfiguration) {
configureExtension<ScalafmtExtension> {
configFilePath = configuration.generatedConfigurationFile.absolutePath
}
val populateTask = populateConfigurationTask(configuration)
tasks.filter { it.name.contains("scalafmt", ignoreCase = true) && it.name != populateTask.get().name }
.forEach { it.dependsOn(populateTask) }
tasks.findByName(CHECK_TASK)?.dependsOn(CHECK_SCALAFMT_TASK)
}
private fun Project.configureScalafix(configuration: ScalafixConfiguration) {
configureExtension<ScalafixExtension> {
setConfigFile(configuration.generatedConfigurationFile.absolutePath)
}
val populateTask = populateConfigurationTask(configuration)
tasks.withType(ScalafixTask::class.java) { it.dependsOn(populateTask) }
}
private fun Project.populateConfigurationTask(configuration: Configuration): TaskProvider<Task> =
tasks.register("populate${configuration.javaClass.simpleName}") {
it.doLast {
logger.info("Picking up configuration ${configuration.resolvedConfiguration.get()}")
configuration.generatedConfigurationFile.createWithContent(configuration.resolvedConfiguration.get())
}
}
private fun Project.configureFormatTask() = tasks.apply {
register("format") {
it.group = "Verification"
it.description = "Format the Scala codebase using linting tools."
it.dependsOn(SCALAFIX_TASK, SCALAFMT_TASK)
}
getByName(SCALAFMT_TASK).mustRunAfter(SCALAFIX_TASK)
}
private fun Project.configureCompilerOptions(extension: ScalaExtrasExtension) = afterEvaluate {
val options = extension.options
.plus(extension.qa.scalafixConfiguration.defaultCompilationOptions())
.run { if (extension.qa.allWarningsAsErrors.get()) plus(FAIL_ON_WARNINGS) else this }
logger.info("Additional compiler options: $options")
tasks.withType(ScalaCompile::class.java) { compileTask ->
compileTask.scalaCompileOptions.additionalParameters = options.toList()
}
}
private companion object {
private const val SCALAFIX_TASK = "scalafix"
private const val SCALAFMT_TASK = "scalafmtAll"
private const val CHECK_TASK = "check"
private const val CHECK_SCALAFMT_TASK = "checkScalafmtAll"
private inline fun <reified T : Any> Project.configureExtension(crossinline action: T.() -> Unit) {
extensions.configure(T::class.java) { it.action() }
}
}
}
| 2
|
Kotlin
|
0
| 0
|
9594d864a5708992094a5f1162450cfd64b007d2
| 3,867
|
gradle-scala-extras
|
Apache License 2.0
|
app/src/main/java/com/mincor/viamframework/viam/base/Listener.kt
|
Rasalexman
| 132,627,165
| false
| null |
package com.mincor.viamframework.viam.base
import com.mincor.viamframework.viam.core.IListener
abstract class Listener(override val name: String = "", override var type: String = "") : IListener
| 0
|
Kotlin
|
0
| 0
|
4c6fa3bb2a8b2335d2b9562f0f879185f0931f77
| 196
|
ViamFramework
|
Apache License 2.0
|
compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/Constraints.kt
|
androidx
| 256,589,781
| false
| null |
/*
* Copyright 2019 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.compose.ui.unit
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.unit.Constraints.Companion.Infinity
import kotlin.jvm.JvmInline
import kotlin.math.min
/**
* Immutable constraints for measuring layouts, used by [layouts][androidx.compose.ui.layout.Layout]
* or [layout modifiers][androidx.compose.ui.layout.LayoutModifier] to measure their layout
* children. The parent chooses the [Constraints] defining a range, in pixels, within which the
* measured layout should choose a size:
* - `minWidth` <= `chosenWidth` <= `maxWidth`
* - `minHeight` <= `chosenHeight` <= `maxHeight`
*
* For more details about how layout measurement works, see
* [androidx.compose.ui.layout.MeasurePolicy] or
* [androidx.compose.ui.layout.LayoutModifier.measure].
*
* A set of [Constraints] can have infinite maxWidth and/or maxHeight. This is a trick often used by
* parents to ask their children for their preferred size: unbounded constraints force children
* whose default behavior is to fill the available space (always size to maxWidth/maxHeight) to have
* an opinion about their preferred size. Most commonly, when measured with unbounded [Constraints],
* these children will fallback to size themselves to wrap their content, instead of expanding to
* fill the available space (this is not always true as it depends on the child layout model, but is
* a common behavior for core layout components).
*
* [Constraints] uses a [Long] to represent four values, [minWidth], [minHeight], [maxWidth], and
* [maxHeight]. The range of the values varies to allow for at most 256K in one dimension. There are
* four possible maximum ranges, 13 bits/18 bits, and 15 bits/16 bits for either width or height,
* depending on the needs. For example, a width could range up to 18 bits and the height up to 13
* bits. Alternatively, the width could range up to 16 bits and the height up to 15 bits. The height
* and width requirements can be reversed, with a height of up to 18 bits and width of 13 bits or
* height of 16 bits and width of 15 bits. Any constraints exceeding this range will fail.
*/
@Immutable
@JvmInline
value class Constraints(@PublishedApi internal val value: Long) {
/**
* Indicates how the bits are assigned. One of:
* - MinFocusWidth
* - MaxFocusWidth
* - MinFocusHeight
* - MaxFocusHeight
*/
private inline val focusIndex
get() = (value and FocusMask).toInt()
/** The minimum width that the measurement can take, in pixels. */
val minWidth: Int
get() {
val mask = widthMask(indexToBitOffset(focusIndex))
return ((value shr 2).toInt() and mask)
}
/**
* The maximum width that the measurement can take, in pixels. This will either be a positive
* value greater than or equal to [minWidth] or [Constraints.Infinity].
*/
val maxWidth: Int
get() {
val mask = widthMask(indexToBitOffset(focusIndex))
val width = ((value shr 33).toInt() and mask)
return if (width == 0) Infinity else width - 1
}
/** The minimum height that the measurement can take, in pixels. */
val minHeight: Int
get() {
val bitOffset = indexToBitOffset(focusIndex)
val mask = heightMask(bitOffset)
val offset = minHeightOffsets(bitOffset)
return (value shr offset).toInt() and mask
}
/**
* The maximum height that the measurement can take, in pixels. This will either be a positive
* value greater than or equal to [minHeight] or [Constraints.Infinity].
*/
val maxHeight: Int
get() {
val bitOffset = indexToBitOffset(focusIndex)
val mask = heightMask(bitOffset)
val offset = minHeightOffsets(bitOffset) + 31
val height = (value shr offset).toInt() and mask
return if (height == 0) Infinity else height - 1
}
/**
* `false` when [maxWidth] is [Infinity] and `true` if [maxWidth] is a non-[Infinity] value.
*
* @see hasBoundedHeight
*/
val hasBoundedWidth: Boolean
get() {
val mask = widthMask(indexToBitOffset(focusIndex))
return ((value shr 33).toInt() and mask) != 0
}
/**
* `false` when [maxHeight] is [Infinity] and `true` if [maxHeight] is a non-[Infinity] value.
*
* @see hasBoundedWidth
*/
val hasBoundedHeight: Boolean
get() {
val bitOffset = indexToBitOffset(focusIndex)
val mask = heightMask(bitOffset)
val offset = minHeightOffsets(bitOffset) + 31
return ((value shr offset).toInt() and mask) != 0
}
/** Whether there is exactly one width value that satisfies the constraints. */
@Stable
val hasFixedWidth: Boolean
get() {
val mask = widthMask(indexToBitOffset(focusIndex))
val minWidth = ((value shr 2).toInt() and mask)
val maxWidth =
((value shr 33).toInt() and mask).let { if (it == 0) Infinity else it - 1 }
return minWidth == maxWidth
}
/** Whether there is exactly one height value that satisfies the constraints. */
@Stable
val hasFixedHeight: Boolean
get() {
val bitOffset = indexToBitOffset(focusIndex)
val mask = heightMask(bitOffset)
val offset = minHeightOffsets(bitOffset)
val minHeight = (value shr offset).toInt() and mask
val maxHeight =
((value shr (offset + 31)).toInt() and mask).let {
if (it == 0) Infinity else it - 1
}
return minHeight == maxHeight
}
/**
* Whether the area of a component respecting these constraints will definitely be 0. This is
* true when at least one of maxWidth and maxHeight are 0.
*/
@Stable
val isZero: Boolean
get() {
val bitOffset = indexToBitOffset(focusIndex)
// No need to special case width == 0 -> Infinity, instead we let it go to -1
// and fail the test that follows
val maxWidth = ((value shr 33).toInt() and widthMask(bitOffset)) - 1
if (maxWidth == 0) return true
// Same here
val offset = minHeightOffsets(bitOffset) + 31
val maxHeight = ((value shr offset).toInt() and heightMask(bitOffset)) - 1
return maxHeight == 0
}
/**
* Copies the existing [Constraints], replacing some of [minWidth], [minHeight], [maxWidth], or
* [maxHeight] as desired. [minWidth] and [minHeight] must be positive and [maxWidth] and
* [maxHeight] must be greater than or equal to [minWidth] and [minHeight], respectively, or
* [Infinity].
*/
fun copy(
minWidth: Int = this.minWidth,
maxWidth: Int = this.maxWidth,
minHeight: Int = this.minHeight,
maxHeight: Int = this.maxHeight
): Constraints {
requirePrecondition(minHeight >= 0 && minWidth >= 0) {
"minHeight($minHeight) and minWidth($minWidth) must be >= 0"
}
// if maxWidth == Infinity, the test passes
requirePrecondition(maxWidth >= minWidth) {
"maxWidth($maxWidth) must be >= minWidth($minWidth)"
}
// if maxHeight == Infinity, the test passes
requirePrecondition(maxHeight >= minHeight) {
"maxHeight($maxHeight) must be >= minHeight($minHeight)"
}
return createConstraints(minWidth, maxWidth, minHeight, maxHeight)
}
override fun toString(): String {
val maxWidth = maxWidth
val maxWidthStr = if (maxWidth == Infinity) "Infinity" else maxWidth.toString()
val maxHeight = maxHeight
val maxHeightStr = if (maxHeight == Infinity) "Infinity" else maxHeight.toString()
return "Constraints(minWidth = $minWidth, maxWidth = $maxWidthStr, " +
"minHeight = $minHeight, maxHeight = $maxHeightStr)"
}
companion object {
/**
* A value that [maxWidth] or [maxHeight] will be set to when the constraint should be
* considered infinite. [hasBoundedWidth] or [hasBoundedHeight] will be `false` when
* [maxWidth] or [maxHeight] is [Infinity], respectively.
*/
const val Infinity = Int.MAX_VALUE
/** Creates constraints for fixed size in both dimensions. */
@Stable
fun fixed(width: Int, height: Int): Constraints {
requirePrecondition(width >= 0 && height >= 0) {
"width($width) and height($height) must be >= 0"
}
return createConstraints(width, width, height, height)
}
/** Creates constraints for fixed width and unspecified height. */
@Stable
fun fixedWidth(width: Int): Constraints {
requirePrecondition(width >= 0) { "width($width) must be >= 0" }
return createConstraints(
minWidth = width,
maxWidth = width,
minHeight = 0,
maxHeight = Infinity
)
}
/** Creates constraints for fixed height and unspecified width. */
@Stable
fun fixedHeight(height: Int): Constraints {
requirePrecondition(height >= 0) { "height($height) must be >= 0" }
return createConstraints(
minWidth = 0,
maxWidth = Infinity,
minHeight = height,
maxHeight = height
)
}
// This should be removed before the next release
@Deprecated(
"Replace with fitPrioritizingWidth",
replaceWith =
ReplaceWith(
"Constraints.fitPrioritizingWidth(minWidth, maxWidth, minHeight, maxHeight)"
)
)
@Stable
fun restrictConstraints(
minWidth: Int,
maxWidth: Int,
minHeight: Int,
maxHeight: Int,
prioritizeWidth: Boolean = true
): Constraints {
return if (prioritizeWidth) {
fitPrioritizingWidth(minWidth, maxWidth, minHeight, maxHeight)
} else {
fitPrioritizingHeight(minWidth, maxWidth, minHeight, maxHeight)
}
}
/**
* Returns [Constraints] that match as close as possible to the values passed. If the
* dimensions are outside of those that can be represented, the constraints are limited to
* those that can be represented.
*
* [Constraints] is a `value class` based on a [Long] and 4 integers must be limited to fit
* within its size. The larger dimension has up to 18 bits (262,143) and the smaller as few
* as 13 bits (8191). The width is granted as much space as it needs or caps the size to 18
* bits. The height is given the remaining space.
*
* This can be useful when layout constraints are possible to be extremely large, but not
* everything is possible to display on the device. For example a text layout where an
* entire chapter of a book is measured in one Layout and it isn't possible to break up the
* content to show in a `LazyColumn`.
*/
@Stable
fun fitPrioritizingWidth(
minWidth: Int,
maxWidth: Int,
minHeight: Int,
maxHeight: Int,
): Constraints {
val minW = min(minWidth, MaxFocusMask - 1)
val maxW =
if (maxWidth == Infinity) {
Infinity
} else {
min(maxWidth, MaxFocusMask - 1)
}
val consumed = if (maxW == Infinity) minW else maxW
val maxAllowed = maxAllowedForSize(consumed)
val maxH = if (maxHeight == Infinity) Infinity else min(maxAllowed, maxHeight)
val minH = min(maxAllowed, minHeight)
return Constraints(minW, maxW, minH, maxH)
}
/**
* Returns [Constraints] that match as close as possible to the values passed. If the
* dimensions are outside of those that can be represented, the constraints are limited to
* those that can be represented.
*
* [Constraints] is a `value class` based on a [Long] and 4 integers must be limited to fit
* within its size. The larger dimension has up to 18 bits (262,143) and the smaller as few
* as 13 bits (8191). The height is granted as much space as it needs or caps the size to 18
* bits. The width is given the remaining space.
*
* This can be useful when layout constraints are possible to be extremely large, but not
* everything is possible to display on the device. For example a text layout where an
* entire chapter of a book is measured in one Layout and it isn't possible to break up the
* content to show in a `LazyColumn`.
*/
@Stable
fun fitPrioritizingHeight(
minWidth: Int,
maxWidth: Int,
minHeight: Int,
maxHeight: Int,
): Constraints {
val minH = min(minHeight, MaxFocusMask - 1)
val maxH =
if (maxHeight == Infinity) {
Infinity
} else {
min(maxHeight, MaxFocusMask - 1)
}
val consumed = if (maxH == Infinity) minH else maxH
val maxAllowed = maxAllowedForSize(consumed)
val maxW = if (maxWidth == Infinity) Infinity else min(maxAllowed, maxWidth)
val minW = min(maxAllowed, minWidth)
return Constraints(minW, maxW, minH, maxH)
}
}
}
// Redefinition of Constraints.Infinity to bypass the companion object
private const val Infinity = Int.MAX_VALUE
/**
* The bit distribution when the focus of the bits should be on the width, but only a minimal
* difference in focus.
*
* 16 bits assigned to width, 15 bits assigned to height.
*/
private const val MinFocusWidth = 0x02
/**
* The bit distribution when the focus of the bits should be on the width, and a maximal number of
* bits assigned to the width.
*
* 18 bits assigned to width, 13 bits assigned to height.
*/
private const val MaxFocusWidth = 0x03
/**
* The bit distribution when the focus of the bits should be on the height, but only a minimal
* difference in focus.
*
* 15 bits assigned to width, 16 bits assigned to height.
*/
private const val MinFocusHeight = 0x01
/**
* The bit distribution when the focus of the bits should be on the height, and a a maximal number
* of bits assigned to the height.
*
* 13 bits assigned to width, 18 bits assigned to height.
*/
private const val MaxFocusHeight = 0x00
/**
* The mask to retrieve the focus ([MinFocusWidth], [MaxFocusWidth], [MinFocusHeight],
* [MaxFocusHeight]).
*/
private const val FocusMask = 0x03L
/** The number of bits used for the focused dimension when there is minimal focus. */
private const val MinFocusBits = 16
private const val MaxAllowedForMinFocusBits = (1 shl (31 - MinFocusBits)) - 2
/** The mask to use for the focused dimension when there is minimal focus. */
private const val MinFocusMask = 0xFFFF // 64K (16 bits)
/** The number of bits used for the non-focused dimension when there is minimal focus. */
private const val MinNonFocusBits = 15
private const val MaxAllowedForMinNonFocusBits = (1 shl (31 - MinNonFocusBits)) - 2
/** The mask to use for the non-focused dimension when there is minimal focus. */
private const val MinNonFocusMask = 0x7FFF // 32K (15 bits)
/** The number of bits to use for the focused dimension when there is maximal focus. */
private const val MaxFocusBits = 18
private const val MaxAllowedForMaxFocusBits = (1 shl (31 - MaxFocusBits)) - 2
/** The mask to use for the focused dimension when there is maximal focus. */
private const val MaxFocusMask = 0x3FFFF // 256K (18 bits)
/** The number of bits to use for the non-focused dimension when there is maximal focus. */
private const val MaxNonFocusBits = 13
private const val MaxAllowedForMaxNonFocusBits = (1 shl (31 - MaxNonFocusBits)) - 2
/** The mask to use for the non-focused dimension when there is maximal focus. */
private const val MaxNonFocusMask = 0x1FFF // 8K (13 bits)
// Wrap those throws in functions to avoid inlining the string building at the call sites
private fun invalidConstraint(widthVal: Int, heightVal: Int) {
throw IllegalArgumentException(
"Can't represent a width of $widthVal and height of $heightVal in Constraints"
)
}
private fun invalidSize(size: Int): Nothing {
throw IllegalArgumentException("Can't represent a size of $size in Constraints")
}
/** Creates a [Constraints], only checking that the values fit in the packed Long. */
internal fun createConstraints(
minWidth: Int,
maxWidth: Int,
minHeight: Int,
maxHeight: Int
): Constraints {
val heightVal = if (maxHeight == Infinity) minHeight else maxHeight
val heightBits = bitsNeedForSizeUnchecked(heightVal)
val widthVal = if (maxWidth == Infinity) minWidth else maxWidth
val widthBits = bitsNeedForSizeUnchecked(widthVal)
if (widthBits + heightBits > 31) {
invalidConstraint(widthVal, heightVal)
}
// Same as if (maxWidth == Infinity) 0 else maxWidth + 1 but branchless
// in DEX and saves 2 instructions on aarch64. Relies on integer overflow
// since Infinity == Int.MAX_VALUE
var maxWidthValue = maxWidth + 1
maxWidthValue = maxWidthValue and (maxWidthValue shr 31).inv()
var maxHeightValue = maxHeight + 1
maxHeightValue = maxHeightValue and (maxHeightValue shr 31).inv()
val focus =
when (widthBits) {
MinNonFocusBits -> MinFocusHeight
MinFocusBits -> MinFocusWidth
MaxNonFocusBits -> MaxFocusHeight
MaxFocusBits -> MaxFocusWidth
else -> 0x00 // can't happen, widthBits is computed from bitsNeedForSizeUnchecked()
}
val minHeightOffset = minHeightOffsets(indexToBitOffset(focus))
val maxHeightOffset = minHeightOffset + 31
val value =
focus.toLong() or
(minWidth.toLong() shl 2) or
(maxWidthValue.toLong() shl 33) or
(minHeight.toLong() shl minHeightOffset) or
(maxHeightValue.toLong() shl maxHeightOffset)
return Constraints(value)
}
private fun bitsNeedForSizeUnchecked(size: Int): Int {
return when {
size < MaxNonFocusMask -> MaxNonFocusBits
size < MinNonFocusMask -> MinNonFocusBits
size < MinFocusMask -> MinFocusBits
size < MaxFocusMask -> MaxFocusBits
else -> 255
}
}
private fun maxAllowedForSize(size: Int): Int {
return when {
size < MaxNonFocusMask -> MaxAllowedForMaxNonFocusBits
size < MinNonFocusMask -> MaxAllowedForMinNonFocusBits
size < MinFocusMask -> MaxAllowedForMinFocusBits
size < MaxFocusMask -> MaxAllowedForMaxFocusBits
else -> invalidSize(size)
}
}
/**
* Create a [Constraints]. [minWidth] and [minHeight] must be positive and [maxWidth] and
* [maxHeight] must be greater than or equal to [minWidth] and [minHeight], respectively, or
* [Infinity][Constraints.Infinity].
*/
@Stable
fun Constraints(
minWidth: Int = 0,
maxWidth: Int = Constraints.Infinity,
minHeight: Int = 0,
maxHeight: Int = Constraints.Infinity
): Constraints {
requirePrecondition(maxWidth >= minWidth) {
"maxWidth($maxWidth) must be >= than minWidth($minWidth)"
}
requirePrecondition(maxHeight >= minHeight) {
"maxHeight($maxHeight) must be >= than minHeight($minHeight)"
}
requirePrecondition(minWidth >= 0 && minHeight >= 0) {
"minWidth($minWidth) and minHeight($minHeight) must be >= 0"
}
return createConstraints(minWidth, maxWidth, minHeight, maxHeight)
}
/**
* Takes [otherConstraints] and returns the result of coercing them in the current constraints. Note
* this means that any size satisfying the resulting constraints will satisfy the current
* constraints, but they might not satisfy the [otherConstraints] when the two set of constraints
* are disjoint. Examples (showing only width, height works the same): (minWidth=2,
* maxWidth=10).constrain(minWidth=7, maxWidth=12) -> (minWidth = 7, maxWidth = 10) (minWidth=2,
* maxWidth=10).constrain(minWidth=11, maxWidth=12) -> (minWidth=10, maxWidth=10) (minWidth=2,
* maxWidth=10).constrain(minWidth=5, maxWidth=7) -> (minWidth=5, maxWidth=7)
*/
fun Constraints.constrain(otherConstraints: Constraints) =
Constraints(
minWidth = otherConstraints.minWidth.coerceIn(minWidth, maxWidth),
maxWidth = otherConstraints.maxWidth.coerceIn(minWidth, maxWidth),
minHeight = otherConstraints.minHeight.coerceIn(minHeight, maxHeight),
maxHeight = otherConstraints.maxHeight.coerceIn(minHeight, maxHeight)
)
/** Takes a size and returns the closest size to it that satisfies the constraints. */
@Stable
fun Constraints.constrain(size: IntSize) =
IntSize(
width = size.width.coerceIn(minWidth, maxWidth),
height = size.height.coerceIn(minHeight, maxHeight)
)
/** Takes a width and returns the closest size to it that satisfies the constraints. */
@Stable fun Constraints.constrainWidth(width: Int) = width.coerceIn(minWidth, maxWidth)
/** Takes a height and returns the closest size to it that satisfies the constraints. */
@Stable fun Constraints.constrainHeight(height: Int) = height.coerceIn(minHeight, maxHeight)
/** Takes a size and returns whether it satisfies the current constraints. */
@Stable
fun Constraints.isSatisfiedBy(size: IntSize): Boolean {
return size.width in minWidth..maxWidth && size.height in minHeight..maxHeight
}
/** Returns the Constraints obtained by offsetting the current instance with the given values. */
@Stable
fun Constraints.offset(horizontal: Int = 0, vertical: Int = 0) =
Constraints(
(minWidth + horizontal).coerceAtLeast(0),
addMaxWithMinimum(maxWidth, horizontal),
(minHeight + vertical).coerceAtLeast(0),
addMaxWithMinimum(maxHeight, vertical)
)
private fun addMaxWithMinimum(max: Int, value: Int): Int {
return if (max == Constraints.Infinity) {
max
} else {
(max + value).coerceAtLeast(0)
}
}
// NOTE: The functions below are not on the companion object to avoid unnecessary
// static resolutions. Even inlined, calling these functions requires a
// static inline access in case initialization is required. Making them top
// level functions addresses this issues.
// The following describes the computations performed by the 4 functions below.
// Each function is a mapping from an index to a value.
//
// index = 0 -> MaxFocusHeight = 15
// index = 1 -> MinFocusHeight = 17
// index = 2 -> MinFocusWidth = 18
// index = 3 -> MaxFocusWidth = 20
//
// MinHeightOffsets = 2 + 13 + (index and 0x1 shl 1) + ((index and 0x2 shr 1) * 3)
//
// The sub-expression `(index and 0x1 shl 1) + ((index and 0x2 shr 1) * 3)` applies
// the following mapping:
//
// 0 -> 0
// 1 -> 2
// 2 -> 3
// 3 -> 5
//
// From this mapping we can build all the other mappings:
//
// index = 0 -> MaxNonFocusMask = 0x1fff (13 bits)
// index = 1 -> MinNonFocusMask = 0x7fff (15 bits)
// index = 2 -> MinFocusMask = 0xffff (16 bits)
// index = 3 -> MaxFocusMask = 0x3ffff (18 bits)
//
// WidthMask = (1 shl (13 + (index and 0x1 shl 1) + ((index and 0x2 shr 1) * 3))) - 1
//
// Here we used the pattern `(1 << n) - 1` to set all first n bits to 1.
//
// index = 0 -> MaxFocusMask = 0x3ffff
// index = 1 -> MinFocusMask = 0xffff
// index = 2 -> MinNonFocusMask = 0x7fff
// index = 3 -> MaxNonFocusMask = 0x1fff
//
// HeightMask = (1 shl (18 - (index and 0x1 shl 1) - ((index and 0x2 shr 1) * 3))) - 1
//
// To optimize computations, the common part that follows is factored into the
// `indexToBitOffset` function:
//
// (index and 0x1 shl 1) + ((index and 0x2 shr 1) * 3)
//
// We are therefore left with:
//
// MinHeightOffsets = 15 + indexToBitOffset(index)
// WidthMask = (1 shl (13 + indexToBitOffset(index))) - 1
// HeightMask = (1 shl (18 - indexToBitOffset(index))) - 1
/**
* Maps an index (MaxFocusHeight, MinFocusHeight, MinFocusWidth, MaxFocusWidth) to a "bit offset":
* 0, 2, 3 or 5. That bit offset is used by [minHeightOffsets], [widthMask], and [heightMask] to
* compute other values without the need of lookup tables. For instance, [minHeightOffsets] returns
* `2 + 13 + bitOffset`.
*/
@Suppress("NOTHING_TO_INLINE")
private inline fun indexToBitOffset(index: Int) =
(index and 0x1 shl 1) + ((index and 0x2 shr 1) * 3)
/**
* Minimum Height shift offsets into Long value, indexed by FocusMask Max offsets are these + 31
* Width offsets are always either 2 (min) or 33 (max)
*/
@Suppress("NOTHING_TO_INLINE") private inline fun minHeightOffsets(bitOffset: Int) = 15 + bitOffset
/** The mask to use for both minimum and maximum width. */
@Suppress("NOTHING_TO_INLINE")
private inline fun widthMask(bitOffset: Int) = (1 shl (13 + bitOffset)) - 1
/** The mask to use for both minimum and maximum height. */
@Suppress("NOTHING_TO_INLINE")
private inline fun heightMask(bitOffset: Int) = (1 shl (18 - bitOffset)) - 1
| 30
| null |
984
| 5,256
|
b4f2ba144b1330987d46dda7707499423171642b
| 26,158
|
androidx
|
Apache License 2.0
|
src/jsMain/kotlin/normalize.kt
|
xorgy
| 395,143,226
| false
| null |
actual fun normalizeNFD (s: String) : String {
return js("s.normalize('NFD')").toString();
};
| 0
|
Kotlin
|
0
| 0
|
603beebecb67f62f9f520639d44d9b1a5bb9d84c
| 97
|
hotfuzz
|
ISC License
|
app/src/main/java/com/yly/sunnyweather/MyApplication.kt
|
Mayo92
| 260,641,362
| false
| null |
package com.yly.sunnyweather
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
/*
* 项目名: SunnyWeather
* 包 名: com.yly.sunnyweather
* 文件名: MyApplication
* 创建者: YLY
* 时 间: 2020-05-02 16:53
* 描 述: TODO
*/
class MyApplication : Application() {
companion object{
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
const val TOKEN = "sFnjrbRdi0dxUFl3"//彩云token
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
}
| 0
|
Kotlin
|
0
| 0
|
c0b2378290d18b5f2a6318eca73597cae9014563
| 564
|
SunnyWeather
|
Apache License 2.0
|
core/common/src/main/kotlin/cn/wj/android/cashbook/core/common/Symbol.kt
|
WangJie0822
| 365,932,300
| false
|
{"Kotlin": 1323186, "Java": 1271087}
|
package cn.wj.android.cashbook.core.common
object Symbol {
/** 人民币符号 CNY */
val CNY: String
get() = "¥"
}
| 0
|
Kotlin
|
7
| 23
|
004fb1d6e81ff60fd9e8cb46dc131107a720bbe5
| 123
|
Cashbook
|
Apache License 2.0
|
liteapi-tl/src/liteserver/LiteServerQueryPrefix.kt
|
ton-community
| 448,983,229
| false
|
{"Kotlin": 1194581}
|
package org.ton.lite.api.liteserver
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.ton.tl.TlCodec
import org.ton.tl.TlConstructor
import org.ton.tl.TlReader
import org.ton.tl.TlWriter
@Serializable
@SerialName("liteServer.queryPrefix")
public object LiteServerQueryPrefix : TlCodec<LiteServerQueryPrefix> by LiteServerQueryPrefixTlConstructor
private object LiteServerQueryPrefixTlConstructor : TlConstructor<LiteServerQueryPrefix>(
schema = "liteServer.queryPrefix = Object"
) {
override fun decode(reader: TlReader): LiteServerQueryPrefix = LiteServerQueryPrefix
override fun encode(writer: TlWriter, value: LiteServerQueryPrefix) {}
}
| 21
|
Kotlin
|
24
| 80
|
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
| 699
|
ton-kotlin
|
Apache License 2.0
|
SKIE/common/configuration/api/src/commonMain/kotlin/co/touchlab/skie/configuration/ConfigurationScope.kt
|
touchlab
| 685,579,240
| false
|
{"Kotlin": 1644009, "Swift": 6029, "Shell": 1040}
|
package co.touchlab.skie.configuration
interface ConfigurationScope {
interface Global : ConfigurationScope
interface Module : ConfigurationScope
interface Package : ConfigurationScope
interface File : ConfigurationScope
interface Class : ConfigurationScope
interface Constructor : ConfigurationScope
interface SimpleFunction : ConfigurationScope
interface Property : ConfigurationScope
interface ValueParameter : ConfigurationScope
interface Function : SimpleFunction, Constructor
interface CallableDeclaration : Function, Property
interface AllExceptCallableDeclarations : Global, Module, Package, File, Class
interface AllExceptConstructorsAndProperties : AllExceptCallableDeclarations, SimpleFunction
interface All : AllExceptConstructorsAndProperties, CallableDeclaration, ValueParameter
}
| 9
|
Kotlin
|
8
| 735
|
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
| 866
|
SKIE
|
Apache License 2.0
|
app/src/main/java/com/example/mobile/top_action_bar/SortBy.kt
|
City-Zouitel
| 576,223,915
| false
| null |
package com.example.graph.top_action_bar
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.size
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.PopupProperties
import com.example.common_ui.Cons.DEFAULT_ORDER
import com.example.common_ui.Cons.FOCUS_NAVIGATION
import com.example.common_ui.Cons.KEY_CLICK
import com.example.common_ui.Cons.NAME_ORDER
import com.example.common_ui.Cons.NEWEST_ORDER
import com.example.common_ui.Cons.OLDEST_ORDER
import com.example.common_ui.Cons.ORDER_BY_NAME
import com.example.common_ui.Cons.ORDER_BY_NEWEST
import com.example.common_ui.Cons.ORDER_BY_OLDEST
import com.example.common_ui.Cons.ORDER_BY_PRIORITY
import com.example.common_ui.Cons.ORDER_BY_REMINDER
import com.example.common_ui.Cons.PRIORITY_ORDER
import com.example.common_ui.Cons.REMINDING_ORDER
import com.example.common_ui.Icons.INTERLINING_ICON
import com.example.common_ui.Icons.SORT_ALPHA_DOWN_ICON
import com.example.common_ui.Icons.SORT_AMOUNT_DOWN_ICON
import com.example.common_ui.Icons.SORT_AMOUNT_UP_ICON
import com.example.common_ui.Icons.SORT_ICON
import com.example.common_ui.Icons.SORT_NUMERIC_ICON
import com.example.datastore.Cons.ORDER_BY_DEFAULT
import com.example.datastore.DataStore
import com.example.graph.sound
import kotlinx.coroutines.launch
@Composable
internal fun SortBy(
isShow: MutableState<Boolean>?,
dataStore: DataStore?
) {
val ctx = LocalContext.current
val thereIsSoundEffect = DataStore(ctx).thereIsSoundEffect.collectAsState(false).value
val scope = rememberCoroutineScope()
val currentSortIcon = when(dataStore?.getOrder?.collectAsState(null)?.value) {
ORDER_BY_NAME -> SORT_ALPHA_DOWN_ICON
ORDER_BY_OLDEST -> SORT_AMOUNT_UP_ICON
ORDER_BY_NEWEST -> SORT_AMOUNT_DOWN_ICON
ORDER_BY_PRIORITY -> INTERLINING_ICON
ORDER_BY_REMINDER -> SORT_NUMERIC_ICON
else -> SORT_ICON
}
Icon(
painterResource(currentSortIcon),
contentDescription = null,
modifier = Modifier
.size(24.dp)
.clickable {
sound.makeSound.invoke(ctx, FOCUS_NAVIGATION, thereIsSoundEffect)
isShow?.value = true
}
)
if (isShow != null) {
DropdownMenu(
expanded = isShow.value,
onDismissRequest = {
isShow.value = false
},
properties = PopupProperties(
focusable = true
)
) {
DropdownMenuItem(
text = { Text(DEFAULT_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(
painter = painterResource(id = SORT_ICON),
null,
modifier = Modifier.size(24.dp)
) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_DEFAULT)
}
}
)
DropdownMenuItem(
text = { Text(NEWEST_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(painter = painterResource(id = SORT_AMOUNT_DOWN_ICON), null ) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_NEWEST)
}
}
)
DropdownMenuItem(
text = { Text(OLDEST_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(painter = painterResource(id = SORT_AMOUNT_UP_ICON), null ) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_OLDEST)
}
}
)
DropdownMenuItem(
text = { Text(NAME_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(painter = painterResource(id = SORT_ALPHA_DOWN_ICON), null ) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_NAME)
}
}
)
DropdownMenuItem(
text = { Text(REMINDING_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(painterResource(SORT_NUMERIC_ICON), null ) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_REMINDER)
}
}
)
DropdownMenuItem(
text = { Text(PRIORITY_ORDER, fontSize = 17.sp) },
leadingIcon = { Icon(painter = painterResource(id = INTERLINING_ICON), null ) },
onClick = {
sound.makeSound.invoke(ctx, KEY_CLICK, thereIsSoundEffect)
isShow.value = false
scope.launch {
dataStore?.saveOrder(ORDER_BY_PRIORITY)
}
}
)
}
}
}
| 20
| null |
4
| 25
|
8b9da426250b75670832d170ee9d77c793b9881e
| 6,122
|
JetNote
|
Apache License 2.0
|
kotlin-antd/antd-samples/src/main/kotlin/samples/slider/Event.kt
|
oxiadenine
| 206,398,615
| false
|
{"Kotlin": 1619835, "HTML": 1515}
|
package samples.slider
import antd.slider.slider
import react.RBuilder
import react.dom.div
import styled.css
import styled.styledDiv
private fun handleChange(value: Array<Number>) {
console.log("onChange: ", value)
}
private fun handleAfterChange(value: Array<Number>) {
console.log("onAfterChange: ", value)
}
fun RBuilder.event() {
styledDiv {
css { +SliderStyles.event }
div {
slider {
attrs {
defaultValue = 30
onChange = ::handleChange
onAfterChange = ::handleAfterChange
}
}
slider {
attrs {
range = true
step = 10
defaultValue = arrayOf(20, 50)
onChange = ::handleChange
onAfterChange = ::handleAfterChange
}
}
}
}
}
| 1
|
Kotlin
|
8
| 50
|
e0017a108b36025630c354c7663256347e867251
| 941
|
kotlin-js-wrappers
|
Apache License 2.0
|
src/main/kotlin/ar/edu/unq/pds03backend/dto/course/SimpleCourseResponseDTO.kt
|
cassa10
| 478,695,193
| false
|
{"Kotlin": 387344, "Shell": 2326, "Dockerfile": 168}
|
package ar.edu.unq.pds03backend.dto.course
import ar.edu.unq.pds03backend.dto.semester.SemesterResponseDTO
import ar.edu.unq.pds03backend.dto.subject.SimpleSubjectResponseDTO
class SimpleCourseResponseDTO(
val id: Long,
val semester: SemesterResponseDTO,
val subject: SimpleSubjectResponseDTO,
val name: String,
val assigned_teachers: String,
val hours: List<HourResponseDTO>,
val totalQuotes: Int
)
| 0
|
Kotlin
|
1
| 0
|
2e61373e3b06ba75399dc429683eec6281f405e9
| 429
|
pds03-backend
|
MIT License
|
src/main/kotlin/dev/ekvedaras/laravelquery/reference/ForeignKeyPsiReference.kt
|
ekvedaras
| 325,768,601
| false
| null |
package dev.ekvedaras.laravelquery.reference
import com.intellij.database.util.DbUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceBase
import dev.ekvedaras.laravelquery.models.DbReferenceExpression
class ForeignKeyPsiReference(element: PsiElement) : PsiReferenceBase<PsiElement>(element) {
override fun resolve(): PsiElement? {
val target = DbReferenceExpression(element, DbReferenceExpression.Companion.Type.ForeignKey)
val tables = target.tablesAndAliases.values.map { it.first }
rangeInElement = target.ranges.last()
DbUtil.getDataSources(element.project).forEach { dataSource ->
val dbForeignKey = dataSource.findElement(target.foreignKey.find { tables.contains(it.table?.name) })
if (dbForeignKey != null) {
return dbForeignKey
}
}
return null
}
}
| 3
|
Kotlin
|
3
| 33
|
fd4c1f4496a0ddeb91154ee20181c47dd339854e
| 893
|
laravel-query-intellij
|
MIT License
|
idea/tests/testData/codeInsight/generate/testFrameworkSupport/junit3/tearDownExists.kt
|
JetBrains
| 278,369,660
| false
| null |
// ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateTestSupportActionBase$TearDown
// NOT_APPLICABLE
// CONFIGURE_LIBRARY: JUnit
import junit.framework.TestCase
class A : TestCase() {<caret>
override fun tearDown() {
super.tearDown()
}
}
| 0
|
Kotlin
|
30
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 276
|
intellij-kotlin
|
Apache License 2.0
|
plugins/parcelize/parcelize-compiler/testData/box/nestedSparseArrays2.kt
|
JetBrains
| 3,432,266
| false
| null |
// IGNORE_BACKEND: JVM
// See https://issuetracker.google.com/177856512
// WITH_RUNTIME
@file:JvmName("TestKt")
package test
import kotlinx.parcelize.*
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.SparseArray
@Parcelize
class Data(val values: SparseArray<SparseArray<Parcelable>>) : Parcelable
fun box() = parcelTest { parcel ->
val innerArray = SparseArray<Parcelable>()
innerArray.append(20, Bundle())
var array = SparseArray<SparseArray<Parcelable>>()
array.append(10, innerArray)
val first = Data(array)
first.writeToParcel(parcel, 0)
val bytes = parcel.marshall()
parcel.unmarshall(bytes, 0, bytes.size)
parcel.setDataPosition(0)
val second = readFromParcel<Data>(parcel)
assert(second.values.size() == 1)
val secondInnerArray = second.values.get(10)
assert(secondInnerArray.size() == 1)
val innerBundle = secondInnerArray.get(20)
assert(innerBundle is Bundle)
assert((innerBundle as Bundle).size() == 0)
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,037
|
kotlin
|
Apache License 2.0
|
shared/src/commonMain/kotlin/org/mifos/pisp/usecase/fetchTransactionById/FetchTransactionByIdRequest.kt
|
openMF
| 665,697,141
| false
|
{"Kotlin": 84180, "Swift": 343}
|
package org.mifos.pisp.usecase.fetchTransactionById
import org.mifos.pisp.usecase.base.BaseRequest
class FetchTransactionByIdRequest(
val token: String,
val bankId: String,
val accountId: String,
val transactionId: String
) :
BaseRequest {
override fun validate(): Boolean {
return true
}
}
| 1
|
Kotlin
|
2
| 2
|
6b45d62c23bbe2f7672b38a1d6952b883bcd190b
| 331
|
pisp-app
|
Apache License 2.0
|
domain/src/main/java/com/team_ia/domain/usecase/admin/ReadNoticeUseCase.kt
|
Idea-Archive
| 613,424,839
| false
| null |
package com.team_ia.domain.usecase.admin
import com.team_ia.domain.repository.AdminRepository
import javax.inject.Inject
class ReadNoticeUseCase @Inject constructor(
private val adminRepository: AdminRepository
) {
suspend operator fun invoke() = kotlin.runCatching {
adminRepository.readNotice()
}
}
| 7
|
Kotlin
|
0
| 9
|
d11e2779e95e63d84139631969ee4e3036303036
| 323
|
Idea-Archive-Android
|
MIT License
|
sample/src/main/java/pyxis/uzuki/live/richutilssample/LocationActivity.kt
|
vooratarun
| 104,946,801
| true
|
{"Kotlin": 115613, "Java": 29096}
|
package pyxis.uzuki.live.richutilssample
import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.location.Location
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_location.*
import pyxis.uzuki.live.richutilskt.service.RLocationService
import pyxis.uzuki.live.richutilskt.utils.RPermission
import pyxis.uzuki.live.richutilskt.utils.asString
import java.util.*
@SuppressLint("SetTextI18n")
class LocationActivity : AppCompatActivity() {
lateinit var locationService: RLocationService
var mBound = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location)
txtLocation.text = "Ready for fetch... \nnow time is ${Calendar.getInstance().time.asString()}\n========================="
val arrays: Array<String> = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
val isGranted = RPermission.getInstance(this).checkPermission(array = arrays, callback = { _: Int, _: ArrayList<String> ->
start()
})
if (isGranted) {
start()
}
}
private fun start() {
val serviceIntent = Intent(applicationContext, RLocationService::class.java)
startService(serviceIntent)
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE)
}
private fun init() {
locationService.setLocationCallback({ location: Location ->
txtLocation.text =
"${txtLocation.text} \n Location changed! -> \n lat: ${location.latitude}\n " +
"lng: ${location.longitude}\n provider: ${location.provider}\n " +
"time: ${Calendar.getInstance().time.asString()}"
})
if (locationService.currentBestLocation != null) {
val location = locationService.currentBestLocation
txtLocation.text =
"${txtLocation.text}\n Location fetch! -> \n lat: ${location?.latitude}\n " +
"lng: ${location?.longitude}\n provider: ${location?.provider}\n " +
"time: ${Calendar.getInstance().time.asString()}"
} else {
txtLocation.text = "${txtLocation.text}\nNot fetched..."
}
}
override fun onDestroy() {
super.onDestroy()
if (mBound) {
locationService.stopUpdates()
unbindService(mConnection)
mBound = false
}
}
private val mConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
val binder = service as RLocationService.LocalBinder
locationService = binder.service
mBound = true
println("service connected!")
if (mBound)
init()
}
override fun onServiceDisconnected(arg0: ComponentName) {
mBound = false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
aecfd5c2175c3c448b29169455e57e76c9c2259f
| 3,275
|
RichUtilsKt
|
Apache License 2.0
|
src/main/kotlin/org/microjservice/lark/api/im/v1/ImageUploadApi.kt
|
MicroJService
| 358,535,254
| false
| null |
package org.microjservice.lark.api.im.v1
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.client.multipart.MultipartBody
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import jakarta.inject.Singleton
import java.io.File
import java.io.InputStream
import java.net.URI
/**
* ImageUploadApi
*
* @author <NAME>
* @since 0.1.5
*/
@Singleton
class ImageUploadApi(
private val imageApi: ImageApi,
private val rxHttpClient: RxHttpClient,
) {
companion object {
const val IMAGE_TYPE_FIELD_NAME: String = "image_type"
const val IMAGE_FIELD_NAME: String = "image"
}
enum class ImageType {
MESSAGE, AVATAR;
override fun toString(): String {
return super.toString().toLowerCase()
}
}
fun uploadImage(imageType: ImageType, file: File): Single<String> {
return imageApi.uploadImage(
MultipartBody.builder()
.addPart(IMAGE_TYPE_FIELD_NAME, imageType.toString())
.addPart(IMAGE_FIELD_NAME, file)
.build()
)
.map { it.data.imageKey }
}
fun uploadImage(imageType: ImageType, imageName: String, data: ByteArray): Single<String> {
return imageApi.uploadImage(
MultipartBody.builder()
.addPart(IMAGE_TYPE_FIELD_NAME, imageType.toString())
.addPart(IMAGE_FIELD_NAME, imageName, data)
.build()
)
.map { it.data.imageKey }
}
fun uploadImage(
imageType: ImageType,
imageName: String,
data: InputStream,
contentLength: Long
): Single<String> {
return imageApi.uploadImage(
MultipartBody.builder()
.addPart(IMAGE_TYPE_FIELD_NAME, imageType.toString())
.addPart(IMAGE_FIELD_NAME, imageName, data, contentLength)
.build()
)
.map { it.data.imageKey }
}
fun uploadImage(imageType: ImageType, uri: URI): Single<String> {
return rxHttpClient.retrieve(
HttpRequest.GET<Any>(uri),
ByteArray::class.java
)
.subscribeOn(Schedulers.io())
.publish()
.autoConnect()
.firstOrError()
.flatMap {
uploadImage(imageType, File(uri.path).name, it)
}
}
}
| 1
|
Kotlin
|
1
| 2
|
6f4d4befc3373b486616c19a632e2c9bbb8997c6
| 2,437
|
lark-api
|
Apache License 2.0
|
src/test/java/dev/kensa/ActionPerformer.kt
|
kensa-dev
| 515,073,953
| false
|
{"Kotlin": 285836, "ANTLR": 97482, "JavaScript": 54770, "Java": 38466, "SCSS": 7515, "Makefile": 1815, "HTML": 427}
|
package dev.kensa
class ActionPerformer {
fun perform(actionName: String): String = "Performed: $actionName"
}
| 6
|
Kotlin
|
1
| 7
|
bcac9b2120a4d35fcc67137314074ec685011052
| 115
|
kensa
|
Apache License 2.0
|
app/src/main/kotlin/com/hivian/pokedex/MainActivity.kt
|
hivian
| 245,177,544
| false
| null |
package hu.tvarga.picsum
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
configureNavController()
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
private fun configureNavController() {
navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
}
}
| 0
| null |
1
| 5
|
5525c2330e52dae04c5bda1bae2d9e5edafc9fb1
| 1,168
|
PokeApex
|
MIT License
|
src/main/kotlin/org/jetbrains/teamcity/github/WebHooksStorage.kt
|
younghyunjo
| 325,715,711
| true
|
{"Kotlin": 225627, "Java": 63489, "JavaScript": 24706, "CSS": 1130, "Ruby": 511}
|
/*
* Copyright 2000-2020 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.teamcity.github
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.intellij.openapi.diagnostic.Logger
import jetbrains.buildServer.serverSide.BuildServerAdapter
import jetbrains.buildServer.serverSide.BuildServerListener
import jetbrains.buildServer.serverSide.ServerPaths
import jetbrains.buildServer.serverSide.TeamCityProperties
import jetbrains.buildServer.serverSide.impl.FileWatcherFactory
import jetbrains.buildServer.util.EventDispatcher
import jetbrains.buildServer.util.FileUtil
import jetbrains.buildServer.util.cache.CacheProvider
import org.eclipse.egit.github.core.RepositoryHook
import org.eclipse.egit.github.core.RepositoryId
import org.jetbrains.teamcity.github.controllers.Status
import org.jetbrains.teamcity.github.controllers.bad
import org.jetbrains.teamcity.github.json.HookInfoTypeAdapter
import org.jetbrains.teamcity.github.json.SimpleDateTypeAdapter
import java.io.File
import java.util.*
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/**
* Webhooks info storage
* Backend: 'commit-hooks/webhooks.json' file under pluginData folder
*
* Data loaded from disk only on server start
* Data persisted onto disk only on server stop
*/
class WebHooksStorage(cacheProvider: CacheProvider,
fileWatcherFactory: FileWatcherFactory,
private val myServerPaths: ServerPaths,
private val myServerEventDispatcher: EventDispatcher<BuildServerListener>) {
companion object {
private val LOG: Logger = Util.getLogger(WebHooksStorage::class.java)
private val VERSION: Int = 1
private val hooksListType = object : TypeToken<List<HookInfo>>() {}.type
val gson: Gson = GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Date::class.java, SimpleDateTypeAdapter)
.registerTypeAdapter(HookInfo::class.java, HookInfoTypeAdapter)
.create()!!
internal fun getJsonObjectFromData(data: List<HookInfo>): JsonObject {
val list = data.toHashSet().toMutableList()
list.sortWith(Comparator { a, b -> a.key.toString().compareTo(b.key.toString()) })
val obj = JsonObject()
obj.addProperty("version", VERSION)
obj.add("hooks", gson.toJsonTree(list, hooksListType))
return obj
}
internal fun getDataFromJsonObject(obj: JsonObject): Map<MapKey, List<HookInfo>>? {
val version = obj.getAsJsonPrimitive("version").asInt
if (version != VERSION) {
LOG.warn("Stored data have outdated version $version")
return null
}
val array = obj.getAsJsonArray("hooks")
val hooks = gson.fromJson<List<HookInfo>>(array, hooksListType)
return hooks.groupBy { it.key.toMapKey() }
}
}
// URLs:
// https://teamcity-github-enterprise.labs.intellij.net/api/v3/repos/Vlad/test/hooks/88
// https://api.github.com/repos/VladRassokhin/intellij-hcl/hooks/9124004
// Keys:
// teamcity-github-enterprise.labs.intellij.net/Vlad/test/88
// github.com/VladRassokhin/intellij-hcl/9124004
data class Key(val server: String, val owner: String, val name: String, val id: Long) {
companion object {
fun fromString(serialized: String): Key {
val split = serialized.split('/')
if (split.size < 4) throw IllegalArgumentException("Not an proper key: \"$serialized\"")
val id = split[split.lastIndex].toLong()
val name = split[split.lastIndex - 1]
val owner = split[split.lastIndex - 2]
val server = split.dropLast(3).joinToString("/")
return Key(server, owner, name, id)
}
fun fromHookUrl(hookUrl: String): Key {
val split = ArrayDeque(hookUrl.split('/'))
assert(split.size >= 8)
val id = split.pollLast().toLong()
split.pollLast() // "hooks"
val name = split.pollLast()
val owner = split.pollLast()
split.pollLast() // "repos"
val serverOfV3 = split.pollLast()
val server: String
if (serverOfV3 == "api.github.com") {
server = "github.com"
} else {
split.pollLast()
server = split.pollLast()
}
return Key(server, owner, name, id)
}
}
override fun toString(): String {
return "$server/$owner/$name/$id"
}
fun toMapKey(): MapKey {
return MapKey(server.trimEnd('/'), owner, name)
}
}
/**
* It's highly recommended not to modify any 'var' field outside of WebHooksStorage#update methods
* since modifications may be not stored on disk
*/
class HookInfo(val url: String, // API URL
val callbackUrl: String, // TC URL (GitHubWebHookListener)
val key: Key = Key.fromHookUrl(url),
val id: Long = key.id,
var status: Status,
var lastUsed: Date? = null,
var lastBranchRevisions: MutableMap<String, String>? = null
) {
companion object {
private fun oneFromJson(string: String): HookInfo? = gson.fromJson(string, HookInfo::class.java)
private fun listFromJson(string: String): List<HookInfo> = gson.fromJson(string, hooksListType) ?: emptyList()
fun fromJson(json: String): List<HookInfo> {
if (json.startsWith("{")) {
return listOf(HookInfo.oneFromJson(json)).filterNotNull()
} else if (json.startsWith("[")) {
return HookInfo.listFromJson(json)
} else {
throw IllegalArgumentException("Unexpected content: $json")
}
}
fun toJson(hooks: List<HookInfo>): String {
return gson.toJson(hooks)
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("")
fun toJson(): String = gson.toJson(this)
fun isSame(hook: RepositoryHook): Boolean {
return id == hook.id && url == hook.url && callbackUrl == hook.callbackUrl
}
fun getUIUrl(): String {
return "https://${key.server}/${key.owner}/${key.name}/settings/hooks/$id"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as HookInfo
if (url != other.url) return false
if (callbackUrl != other.callbackUrl) return false
return true
}
override fun hashCode(): Int {
var result = url.hashCode()
result = 31 * result + callbackUrl.hashCode()
return result
}
fun updateBranchMapping(update: Map<String, String>): Map<String, String> {
if (lastBranchRevisions == null) lastBranchRevisions = HashMap()
lastBranchRevisions!!.putAll(update)
return lastBranchRevisions!!
}
override fun toString(): String {
return "HookInfo(url='$url', callbackUrl='$callbackUrl', status=$status, lastUsed=$lastUsed)"
}
}
data class MapKey internal constructor(val server: String, val owner: String, val name: String) {
private val hashCode: Int;
constructor(server: String, repo: RepositoryId) : this(server.trimEnd('/'), repo.owner, repo.name)
init {
hashCode = Objects.hash(server.toLowerCase(), owner.toLowerCase(), name.toLowerCase());
}
override fun toString(): String {
return "$server/$owner/$name"
}
fun toInfo(): GitHubRepositoryInfo = GitHubRepositoryInfo(server, owner, name)
override fun equals(other: Any?): Boolean {
return if (other is MapKey) {
server.equals(other.server, true) && owner.equals(other.owner, true) && name.equals(other.name, true);
} else {
false
}
}
override fun hashCode(): Int {
return hashCode;
}
}
private val myData = HashMap<MapKey, MutableList<HookInfo>>()
private val myDataLock = ReentrantReadWriteLock()
private val myFileWatcher = fileWatcherFactory.createSingleFilesWatcher(getStorageFile(), TeamCityProperties.getInteger("teamcity.commitHooks.webHookStorage.watchInterval", 5000))
private val myServerListener = object : BuildServerAdapter() {
override fun serverStartup() {
load()
myFileWatcher.registerListener {
load()
}
myFileWatcher.start()
// Drop old caches from pre-release versions of plugin
try {
cacheProvider.destroyCache("WebHooksCache")
cacheProvider.destroyCache("WebHooksAuthCache")
} catch(e: Exception) {
}
}
override fun serverShutdown() {
persist()
myFileWatcher.stop()
}
}
fun init() {
myServerEventDispatcher.addListener(myServerListener)
}
fun destroy() {
myServerEventDispatcher.removeListener(myServerListener)
}
/**
* Adds hook if it not existed previously
*/
fun getOrAdd(created: RepositoryHook): HookInfo {
val key = Key.fromHookUrl(created.url)
val mapKey = key.toMapKey()
val hooks = getHooks(mapKey)
val hook = hooks.firstOrNull { it.isSame(created) }
if (hook != null) {
LOG.info("Already exist $hook")
return hook
}
myDataLock.write {
@Suppress("NAME_SHADOWING")
var hooks = myData[mapKey]
@Suppress("NAME_SHADOWING")
val hook = hooks?.firstOrNull { it.isSame(created) }
if (hook != null) return hook
val toAdd = WebHooksStorage.HookInfo(url = created.url, callbackUrl = created.callbackUrl!!, key = key, status = created.getStatus())
if (hooks == null || hooks.isEmpty()) {
hooks = mutableListOf(toAdd)
myData.put(mapKey, hooks)
} else {
hooks = hooks
hooks.add(toAdd)
myData.put(mapKey, hooks)
}
LOG.info("Added $toAdd")
return toAdd
}
}
fun delete(hookInfo: HookInfo) {
LOG.info("Removing $hookInfo")
myDataLock.write {
myData[hookInfo.key.toMapKey()]?.remove(hookInfo)
}
}
fun delete(info: GitHubRepositoryInfo, deleteFilter: (HookInfo) -> Boolean) {
if (!getHooks(info).any { deleteFilter(it) }) return
val key = MapKey(info.server, info.getRepositoryId())
myDataLock.write {
val hooks = myData[key]?.toMutableList() ?: return
val filtered = hooks.filter { !deleteFilter(it) }.toMutableList()
if (filtered.isEmpty()) {
myData.remove(key)
} else {
myData.put(key, filtered)
}
}
}
fun update(server: String, repo: RepositoryId, update: (HookInfo) -> Unit): Boolean {
val key = MapKey(server, repo)
val hooks = myDataLock.read {
myData[key]?.toMutableList() ?: return false
}
for (hook in hooks) {
update(hook)
}
return true
}
fun getHooks(info: GitHubRepositoryInfo): List<WebHooksStorage.HookInfo> {
return getHooks(info.server, info.getRepositoryId())
}
fun getHooks(server: String, repo: RepositoryId): List<WebHooksStorage.HookInfo> {
return getHooks(MapKey(server, repo))
}
private fun getHooks(key: MapKey): List<HookInfo> {
return myDataLock.read {
myData[key]?.let { it.toList(); }
} ?: emptyList()
}
fun isHasIncorrectHooks(): Boolean {
myDataLock.read {
for (value in myData.values) {
if (value.any { it.status.bad }) return true
}
}
return false
}
fun getIncorrectHooks(): List<Pair<GitHubRepositoryInfo, WebHooksStorage.HookInfo>> {
val result = ArrayList<Pair<GitHubRepositoryInfo, WebHooksStorage.HookInfo>>()
myDataLock.read {
for ((key, hooks) in myData) {
val bad = hooks.filter { it.status.bad }
if (bad.isNotEmpty()) {
val info = key.toInfo()
bad.map { info to it }.toCollection(result)
}
}
}
return result
}
fun getAll(): List<Pair<GitHubRepositoryInfo, HookInfo>> {
val result = ArrayList<Pair<GitHubRepositoryInfo, WebHooksStorage.HookInfo>>()
myDataLock.read {
for ((key, hooks) in myData) {
val info = key.toInfo()
hooks.map { info to it }.toCollection(result)
}
}
return result
}
private fun getStorageFile(): File {
return File(myServerPaths.pluginDataDirectory, "commit-hooks/webhooks.json")
}
private fun persist() {
myFileWatcher.runActionWithDisabledObserver {
persistImpl()
}
}
@Synchronized
private fun persistImpl() {
val obj = myDataLock.read {
getJsonObjectFromData(myData.values.flatten())
}
val file = getStorageFile()
try {
FileUtil.createParentDirs(file)
val writer = file.writer(Charsets.UTF_8).buffered()
writer.use {
gson.toJson(obj, it)
}
} catch(e: Exception) {
LOG.warnAndDebugDetails("Cannot write auth-data to file '${file.absolutePath}'", e)
}
}
@Synchronized private fun load(): Boolean {
val file = getStorageFile()
val obj: JsonObject?
try {
FileUtil.createParentDirs(file)
if (!file.isFile) return false
obj = file.reader(Charsets.UTF_8).buffered().use {
gson.fromJson<JsonObject>(it, JsonObject::class.java)
}
} catch(e: Exception) {
LOG.warnAndDebugDetails("Cannot read auth-data from file '${file.absolutePath}'", e)
return false
}
if (obj == null) {
LOG.warn("Stored object is null")
return false
}
val data = getDataFromJsonObject(obj) ?: return false
myDataLock.write {
myData.clear()
for ((key, value) in data) {
myData.put(key, value.toMutableList())
}
}
return true
}
}
| 0
|
Kotlin
|
0
| 0
|
a0d74933f3257ab5b37095a8953b8cc40c489313
| 15,788
|
teamcity-commit-hooks
|
Apache License 2.0
|
kotlin/legacy/legacy-workflow-rx2/src/test/java/com/squareup/workflow/legacy/rx2/WorkerIntegrationTest.kt
|
arriolac
| 208,501,497
| false
| null |
/*
* Copyright 2017 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.workflow.rx2
import com.squareup.workflow.Worker
import com.squareup.workflow.WorkflowPool
import io.reactivex.observers.TestObserver
import io.reactivex.subjects.SingleSubject
import kotlinx.coroutines.experimental.channels.Channel
import org.assertj.core.api.Java6Assertions.assertThat
import org.junit.Test
import java.io.IOException
class WorkerIntegrationTest {
private val pool = WorkflowPool()
private val single = SingleSubject.create<String>()
private val worker = single.asWorker()
@Test fun `when call succeeds`() {
val reaction = pool.workerResult(worker, Unit)
reaction.assertNotTerminated()
single.onSuccess("bar")
reaction.assertValue("bar")
}
@Test fun `when call fails`() {
val reaction = pool.workerResult(worker, Unit)
reaction.assertNotTerminated()
single.onError(IOException("network fail"))
val failure = reaction.errors()
.single()
assertThat(failure).isInstanceOf(IOException::class.java)
}
@Test fun `when worker cancelled`() {
val reaction = pool.workerResult(worker, Unit)
reaction.assertNotTerminated()
pool.abandonWorker(worker)
// The rx2 version of nextProcessResult will never complete the single if the workflow is
// cancelled.
reaction.assertNoValues()
reaction.assertNoErrors()
}
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified I : Any, reified O : Any> WorkflowPool.workerResult(
worker: Worker<I, O>,
input: I
): TestObserver<O> = Channel<Nothing>().asEventChannel()
.select<O> { onWorkerResult(worker, input) { it } }
.test() as TestObserver<O>
| 0
| null |
0
| 1
|
8acff486c2fc80b1de2e1956170819f03fa0eafd
| 2,225
|
workflow
|
Apache License 2.0
|
engine/src/main/kotlin/kotli/engine/extensions/dev.kt
|
kotlitecture
| 741,006,904
| false
|
{"Kotlin": 47005}
|
package kotli.engine.extensions
import kotli.engine.TemplateContext
import kotli.engine.TemplateMaker
import java.nio.file.Path
/**
* Checks if current system is windows or not.
*/
fun isWindows(): Boolean {
return runCatching {
System.getProperty("os.name").lowercase().startsWith("windows")
}.getOrElse { false }
}
/**
* Choose the right gradle script to run based on the system.
*/
fun gradlew(): String {
return if (isWindows()) "gradlew" else "./gradlew"
}
/**
* Executes given set of #commands in the directory #dir.
*/
fun exec(dir: Path, vararg commands: String) {
val args = if (isWindows()) mutableListOf("cmd.exe", "/C") else mutableListOf()
args.addAll(commands.toList())
val process = ProcessBuilder()
.directory(dir.toFile())
.command(args)
.inheritIO()
.start()
val exitCode = process.waitFor()
if (exitCode != 0) throw IllegalStateException("wrong exit code $exitCode")
}
/**
* Applies template engine to the 'gradle/libs.versions.toml' in the root of the target folder.
*/
fun TemplateContext.applyVersionCatalog(block: TemplateMaker.() -> Unit) {
apply("gradle/libs.versions.toml", block)
}
| 0
|
Kotlin
|
0
| 0
|
fca48f75106b7bcce41738b6714e39615b5bb050
| 1,197
|
kotli-engine
|
MIT License
|
src/main/kotlin/net/inherency/finances/controller/dto/CreateTransactionCmd.kt
|
scottygaydos
| 278,980,273
| false
|
{"Kotlin": 199344, "HTML": 2360, "JavaScript": 1723}
|
package net.inherency.finances.controller.dto
data class CreateTransactionCmd(
val transactionDateString: String?,
val transactionTypeId: Int, //named for legacy front end code; maps to budget category id
val description: String,
val creditAccountId: Int,
val debitAccountId: Int,
val authorizedAmount: String,
val settledAmount: String?,
val canReconcile: Boolean
)
| 2
|
Kotlin
|
0
| 0
|
825dd8a5e36ce88b45aa3585871faee8734ae750
| 431
|
finance_budget_and_reconciler
|
Apache License 2.0
|
wallet/src/main/java/com/android/identity/issuance/CredentialExtensions.kt
|
openwallet-foundation-labs
| 248,844,077
| false
| null |
package com.android.identity.issuance
import com.android.identity.credential.Credential
import com.android.identity.credential.CredentialUtil
import com.android.identity.securearea.SecureArea
import com.android.identity.util.Logger
import com.android.identity.util.Timestamp
import java.lang.IllegalArgumentException
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit
import kotlin.time.toDuration
/**
* A set of extensions on the [Credential] type for working with the [IssuingAuthority]
* and related classes.
*/
object CredentialExtensions {
const val TAG = "CredentialExtensions"
/** The identifier for the [IssuingAuthority] the credential belongs to */
var Credential.issuingAuthorityIdentifier: String
get() = applicationData.getString("issuingAuthorityIdentifier")
set(value) { applicationData.setString("issuingAuthorityIdentifier", value) }
/**
* The identifier for the credential, as assigned by the issuer
*
* This is the _credentialId_ value used in [IssuingAuthority] when communicating
* with the issuing authority.
*/
var Credential.credentialIdentifier: String
get() = applicationData.getString("credentialIdentifier")
set(value) { applicationData.setString("credentialIdentifier", value) }
/** The [CredentialConfiguration] received from the issuer */
var Credential.credentialConfiguration: CredentialConfiguration
get() = CredentialConfiguration.fromCbor(applicationData.getData("credentialConfiguration"))
set(value) { applicationData.setData("credentialConfiguration", value.toCbor()) }
/**
* The most recent [CredentialState] received from the issuer.
*
* This doesn't ping the issuer so the information may be stale. Applications can consult
* the [CredentialState.timestamp] field to figure out the age of the state and use
* [Credential.refreshState] to refresh it directly from the issuer server.
*/
var Credential.state: CredentialState
get() = CredentialState.fromCbor(applicationData.getData("credentialState"))
set(value) { applicationData.setData("credentialState", value.toCbor()) }
/**
* Gets the credential state from the Issuer and updates the [.state] property with the value.
*
* Unlike reading from the [.state] property, this performs network I/O to communicate
* with the issuer.
*
* @param issuingAuthorityRepository a repository of issuing authorities.
* @return The [CredentialState] retrieved from the issuer.
* @throws IllegalArgumentException if the issuer isn't know.
*/
suspend fun Credential.refreshState(issuingAuthorityRepository: IssuingAuthorityRepository): CredentialState {
val issuer = issuingAuthorityRepository.lookupIssuingAuthority(issuingAuthorityIdentifier)
?: throw IllegalArgumentException("No issuer with id $issuingAuthorityIdentifier")
state = issuer.credentialGetState(credentialIdentifier)
return state
}
/**
* This performs all the essential bits of housekeeping for the credential, including
* requesting CPOs, checking for PII updates, and so on.
*
* Throttling is implemented internally meaning that this will only reach out to the
* issuer every N hours or after a network change meaning this is safe to call at
* from the application at any time, e.g. application start-up, or when a network
* change has been detected. (TODO: spell out policy and make it customizable.)
*
* @param issuingAuthorityRepository a repository of issuing authorities.
* @param forceUpdate if true, throttling will be bypassed.
* @return The [CredentialState] retrieved from the issuer.
* @throws IllegalArgumentException if the issuer isn't know.
*/
suspend fun Credential.housekeeping(
issuingAuthorityRepository: IssuingAuthorityRepository,
forceUpdate: Boolean,
numAuthKeys: Int,
minValidTimeMillis: Long,
secureArea: SecureArea,
authKeyDomain: String
) {
if (forceUpdate) {
Logger.d(TAG, "housekeeping: Forcing update")
} else {
val limit = 4.hours
val sinceLastUpdate = (state.timestamp - System.currentTimeMillis()).toDuration(DurationUnit.MILLISECONDS)
if (sinceLastUpdate.inWholeHours < 4) {
Logger.d(
TAG,
"housekeeping: Last update was ${sinceLastUpdate.inWholeSeconds} " +
"seconds ago, skipping (limit: ${limit.inWholeSeconds})"
)
return
}
Logger.d(
TAG,
"housekeeping: Last update was ${sinceLastUpdate.inWholeSeconds} " +
"seconds ago, proceeding (limit: ${limit.inWholeSeconds} seconds)"
)
}
val issuer = issuingAuthorityRepository.lookupIssuingAuthority(issuingAuthorityIdentifier)
?: throw IllegalArgumentException("No issuer with id $issuingAuthorityIdentifier")
// OK, let's see if configuration is available
refreshState(issuingAuthorityRepository)
if (state.condition == CredentialCondition.CONFIGURATION_AVAILABLE) {
// TODO: delete all existing CPOs
Logger.d(TAG, "housekeeping: Configuration available, downloading")
credentialConfiguration = issuer.credentialGetConfiguration(credentialIdentifier)
refreshState(issuingAuthorityRepository)
}
// Request new CPOs if needed
if (state.condition == CredentialCondition.READY) {
val now = Timestamp.now()
// First do a dry-run to see how many pending authentication keys will be created
val numPendingAuthKeysToCreate = CredentialUtil.managedAuthenticationKeyHelper(
this,
secureArea,
null,
authKeyDomain,
now,
numAuthKeys,
1,
minValidTimeMillis,
true)
if (numPendingAuthKeysToCreate > 0) {
Logger.d(TAG, "Need to request $numPendingAuthKeysToCreate CPOs")
val requestCpoFlow = issuer.credentialRequestPresentationObjects(credentialIdentifier)
val authKeyConfig = requestCpoFlow.getAuthenticationKeyConfiguration()
// TODO: add e.g. user authentication to AuthKey
val authKeySettings = SecureArea.CreateKeySettings(authKeyConfig.challenge)
CredentialUtil.managedAuthenticationKeyHelper(
this,
secureArea,
authKeySettings,
authKeyDomain,
now,
numAuthKeys,
1,
minValidTimeMillis,
false)
val credentialPresentationRequests = mutableListOf<CredentialPresentationRequest>()
for (pendingAuthKey in pendingAuthenticationKeys) {
credentialPresentationRequests.add(
CredentialPresentationRequest(
CredentialPresentationFormat.MDOC_MSO,
pendingAuthKey.attestation
)
)
}
requestCpoFlow.sendAuthenticationKeys(credentialPresentationRequests)
refreshState(issuingAuthorityRepository)
}
}
if (state.numAvailableCPO > 0) {
Logger.d(TAG, "Fetching ${state.numAvailableCPO} CPOs")
for (cpo in issuer.credentialGetPresentationObjects(credentialIdentifier)) {
val pendingAuthKey = pendingAuthenticationKeys.find {
it.attestation[0].publicKey.equals(cpo.authenticationKey) }
if (pendingAuthKey == null) {
Logger.w(TAG, "No PendingAuthenticationKey for pubkey ${cpo.authenticationKey}")
continue
}
pendingAuthKey.certify(
cpo.presentationData,
Timestamp.ofEpochMilli(cpo.validFromMillis),
Timestamp.ofEpochMilli(cpo.validUntilMillis))
}
refreshState(issuingAuthorityRepository)
}
}
}
| 98
| null |
73
| 130
|
f2b4ef2dc2cd7185b063670199a2e47ecf8e21af
| 8,461
|
identity-credential
|
Apache License 2.0
|
domain/src/main/java/com/movingmaker/domain/model/UiState.kt
|
Comment-Diary
| 458,682,004
| false
| null |
package com.movingmaker.domain.model
sealed class UiState<out T> {
data class Success<T>(val data: T) : UiState<T>()
data class Fail(val message: String) : UiState<Nothing>()
data class Error(val message: String) : UiState<Nothing>()
}
fun <T> UiState<T>.toModel(): T {
return (this as UiState.Success).data
}
private fun <R> changeUiState(replaceData: R): UiState<R> {
return UiState.Success(replaceData)
}
//BaseResponse 사용 시 success 분리
suspend fun <T, R> UiState<T>.mapUiState(getData: suspend (T) -> R): UiState<R> {
return when (this) {
is UiState.Success -> changeUiState(getData(toModel()))
is UiState.Fail -> this
is UiState.Error -> this
}
}
| 9
| null |
1
| 2
|
cf9f329970d83181c41a6cfc0470cd2712301f6f
| 706
|
CommentDiary-AOS
|
MIT License
|
app/src/main/kotlin/com/example/valorantandroid/agent/ui/viewmodel/AgentDetailsViewModel.kt
|
jamesdpli
| 680,617,148
| false
|
{"Kotlin": 52872}
|
package com.example.valorantandroid.agent.ui.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.valorantandroid.agent.data.repository.AgentsRepository
import com.example.valorantandroid.agent.domain.model.AgentDetailDomainModel
import com.example.valorantandroid.core.utils.constants.Constants
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
sealed interface AgentDetailsUiState {
data class Success(val agent: AgentDetailDomainModel) : AgentDetailsUiState
object Loading : AgentDetailsUiState
data class Error(val message: String) : AgentDetailsUiState
}
@HiltViewModel
class AgentDetailsViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val repository: AgentsRepository
) : ViewModel() {
private val uuidNavArg: String = checkNotNull(
savedStateHandle[Constants.NavArgs.AGENT_UUID]
)
private var _agentDetailsUiState =
MutableStateFlow<AgentDetailsUiState>(AgentDetailsUiState.Loading)
val agentDetailsUiState = _agentDetailsUiState.asStateFlow()
init {
getAgentDetails(uuidNavArg)
}
private fun getAgentDetails(uuid: String) = viewModelScope.launch {
try {
val agent = repository.getAgentByUuidFromNetwork(uuid)
_agentDetailsUiState.update {
return@update AgentDetailsUiState.Success(agent = agent)
}
} catch (e: Exception) {
_agentDetailsUiState.update {
return@update AgentDetailsUiState.Error(message = e.message.toString())
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ee60d85023b055fcd105531edb40fd616ca86fdd
| 1,852
|
ValorantAndroid
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/auth/Authentication.kt
|
navikt
| 303,972,532
| false
| null |
package no.nav.syfo.auth
import com.auth0.jwk.JwkProviderBuilder
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.auth.jwt.*
import io.ktor.routing.*
import no.nav.syfo.AuthEnv
import no.nav.syfo.api.admin.registerAdminApi
import no.nav.syfo.api.bruker.registerBrukerApi
import no.nav.syfo.api.job.registerJobTriggerApi
import no.nav.syfo.job.VarselSender
import no.nav.syfo.service.ReplanleggingService
import no.nav.syfo.service.VarselSendtService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.net.URL
import java.util.concurrent.TimeUnit
val log: Logger = LoggerFactory.getLogger("no.nav.syfo.varsel.JwtValidation")
fun Application.setupAuthentication(
authEnv: AuthEnv
) {
val wellKnown = getWellKnown(authEnv.loginserviceDiscoveryUrl)
val jwkProvider = JwkProviderBuilder(URL(wellKnown.jwks_uri))
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
install(Authentication) {
jwt(name = "loginservice") {
verifier(jwkProvider, wellKnown.issuer)
validate { credentials ->
when {
hasLoginserviceIdportenClientIdAudience(credentials, authEnv.loginserviceAudience) && erNiva4(credentials) -> JWTPrincipal(credentials.payload)
else -> null
}
}
}
basic("auth-basic") {
realm = "Access to the '/admin/' path"
validate { credentials ->
when {
validBasicAuthCredentials(authEnv, credentials) -> UserIdPrincipal(credentials.name)
else -> null
}
}
}
}
}
fun Application.setupLocalRoutesWithAuthentication(
varselSender: VarselSender,
varselSendtService: VarselSendtService,
replanleggingService: ReplanleggingService,
authEnv: AuthEnv
) {
install(Authentication) {
basic("auth-basic") {
realm = "Access to the '/admin/' path"
validate { credentials ->
when {
validBasicAuthCredentials(authEnv, credentials) -> UserIdPrincipal(credentials.name)
else -> null
}
}
}
}
routing {
registerBrukerApi(varselSendtService)
registerAdminApi(replanleggingService)
authenticate("auth-basic") {
registerJobTriggerApi(varselSender)
}
}
}
fun Application.setupRoutesWithAuthentication(
varselSender: VarselSender,
varselSendtService: VarselSendtService,
replanleggingService: ReplanleggingService,
authEnv: AuthEnv
) {
setupAuthentication(authEnv)
routing {
authenticate("loginservice") {
registerBrukerApi(varselSendtService)
}
authenticate("auth-basic") {
registerAdminApi(replanleggingService)
registerJobTriggerApi(varselSender)
}
}
}
| 2
|
Kotlin
|
2
| 0
|
8578a9c60ecc52653055defb2ee1944d8a1bf6e8
| 2,976
|
esyfovarsel
|
MIT License
|
modules/framework/src/main/java/soy/gabimoreno/framework/ContextExtensions.kt
|
soygabimoreno
| 477,796,937
| false
|
{"Kotlin": 364408, "Swift": 648, "Shell": 441}
|
package soy.gabimoreno.framework
import android.content.Context
import android.widget.Toast
import androidx.annotation.StringRes
fun Context.toast(
@StringRes resId: Int,
duration: Int = Toast.LENGTH_SHORT,
) {
Toast.makeText(
this,
resId,
duration
).show()
}
fun Context.toast(
message: CharSequence,
duration: Int = Toast.LENGTH_SHORT,
) {
Toast.makeText(
this,
message,
duration
).show()
}
| 6
|
Kotlin
|
10
| 13
|
5d5ff8117cda10f7567ac0caf152501c1d439baa
| 476
|
Base
|
Apache License 2.0
|
features/third_party/androidx/permissions/src/main/java/com/ruslan/hlushan/third_party/androidx/permissions/PermissionResult.kt
|
game-x50
| 361,364,864
| false
| null |
@file:Suppress("PackageNaming")
package com.ruslan.hlushan.third_party.androidx.permissions
sealed class PermissionResult {
abstract val requestCode: Int
abstract val permissions: SeparatedPermissions
class ShowRationale(
override val requestCode: Int,
override val permissions: SeparatedPermissions
) : PermissionResult()
class Response(
override val requestCode: Int,
override val permissions: SeparatedPermissions
) : PermissionResult()
}
| 21
|
Kotlin
|
0
| 0
|
3f50c768c05a85f5994f6c6ac4ffd57248eb4ada
| 518
|
android_client_app
|
Apache License 2.0
|
Application/src/main/java/android/prosotec/proyectocierzo/ProfileActivity.kt
|
UNIZAR-30226-PROYS
| 174,677,837
| true
|
{"Kotlin": 119605, "Java": 80731}
|
package android.prosotec.proyectocierzo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import kotlinx.android.synthetic.main.activity_profile.*
import com.example.android.mediasession.R
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
class ProfileActivity : AppCompatActivity() {
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
}
| 0
|
Kotlin
|
0
| 0
|
0b9587cc3e947b466c52ced5c0b6b11768aefda1
| 896
|
Android-1
|
Apache License 1.1
|
game/src/main/java/org/mhacks/app/game/data/model/QuestionResponse.kt
|
mhacks
| 22,456,318
| false
| null |
package org.mhacks.app.game.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.squareup.moshi.Json
import org.mhacks.app.core.data.Converters
import org.mhacks.app.game.data.QuestionTypeConverter
@TypeConverters(QuestionTypeConverter::class)
data class QuestionResponse(
@Json(name = "status") var status: Boolean,
@Json(name = "questions") var questions: List<Question>
)
@TypeConverters(Converters::class)
@Entity(tableName = "questions")
data class Question(
@PrimaryKey
@Json(name = "name") var name: String,
@Json(name = "text") var text: String,
@Json(name = "options") var options: List<String>,
@field:Json(name = "task_format") var taskFormat: String
)
| 1
|
Kotlin
|
12
| 21
|
12309b463e51acc3f41c463df647f410e16a6261
| 788
|
mhacks-android
|
MIT License
|
module/json/src/main/kotlin/io/github/siyual_park/json/patch/JsonPatchFactory.kt
|
siyul-park
| 403,557,925
| false
|
{"Kotlin": 711198, "TypeScript": 44640, "JavaScript": 1125, "Dockerfile": 292, "Shell": 195}
|
package io.github.siyual_park.json.patch
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component
@Component
class JsonPatchFactory(
private val objectMapper: ObjectMapper
) {
fun <T : Any> create(content: String): JsonPatch<T> {
return JsonPatch(objectMapper.readTree(content), objectMapper)
}
fun <T : Any> create(parser: JsonParser): JsonPatch<T> {
return JsonPatch(objectMapper.readTree(parser), objectMapper)
}
fun <T : Any> create(node: JsonNode): JsonPatch<T> {
return JsonPatch(node, objectMapper)
}
}
| 11
|
Kotlin
|
0
| 18
|
08c02ea8bf0c6c57157182f714624c4163ba49e2
| 700
|
spring-webflux-multi-module-boilerplate
|
MIT License
|
internetchecker/src/main/java/io/github/vnicius/internetchecker/PingHelper.kt
|
Vnicius
| 262,470,139
| false
| null |
package io.github.vnicius.internetchecker
import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.lang.ref.WeakReference
/**
* Created by @vnicius on 23/05/20.
* vinicius.matheus252@gmail.com
*/
class PingHelper(context: Context) {
private val contextReference = WeakReference(context.applicationContext)
private val queue: RequestQueue? by lazy {
contextReference.get()?.let { context ->
Volley.newRequestQueue(context)
}
}
fun ping(onSuccess: () -> Unit = {}, onError: () -> Unit = {}) {
val request = StringRequest(Request.Method.GET, PING_HOST, Response.Listener { _ ->
onSuccess()
}, Response.ErrorListener {
onError()
})
queue?.add(request)
}
companion object {
const val PING_HOST = "https://www.google.com"
}
}
| 0
|
Kotlin
|
0
| 1
|
ed7f17275bb22878f554a9bba349690e8f3e128b
| 1,031
|
internet-checker
|
MIT License
|
credentials/credentials-e2ee/src/androidTest/java/androidx/credentials/e2ee/IdentityKeyTest.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2023 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.credentials.e2ee
import android.util.Base64
import com.google.common.io.BaseEncoding
import com.google.common.truth.Truth.assertThat
import java.util.Random
import org.junit.Test
class IdentityKeyTest {
var sRandom: Random = Random()
private fun randBytes(numBytes: Int): ByteArray {
val bytes = ByteArray(numBytes)
sRandom.nextBytes(bytes)
return bytes
}
private fun hexEncode(bytes: ByteArray): String {
return BaseEncoding.base16().lowerCase().encode(bytes)
}
@Test
fun identityKeyWithFixedInputs_mustProduceExpectedOutput() {
val prf = ByteArray(32)
val salt = ByteArray(32)
// with an all-zero PRF and salt, this is the expected key
val expectedPrivKeyHex = "df7204546f1bee78b85324a7898ca119b387e01386d1aef037781d4a8a036aee"
val expectedPubKeyHex = "ba33d523fd7bf0d06ce9298c3440be1bea3748c6270ae3e07ae8ea19abb8ed23"
val identityKey = IdentityKey.createFromPrf(prf, salt, IdentityKey.IDENTITYKEY_TYPE_ED25519)
assertThat(identityKey.private).isNotNull()
assertThat(identityKey.public).isNotNull()
assertThat(hexEncode(identityKey.private)).isEqualTo(expectedPrivKeyHex)
assertThat(hexEncode(identityKey.public)).isEqualTo(expectedPubKeyHex)
}
@Test
fun identityKeyWithoutSalt_mustBeIdenticalToEmptySalt() {
for (i in 1..10) {
val prf = randBytes(32)
val identityKey =
IdentityKey.createFromPrf(prf, /* salt= */null,
IdentityKey.IDENTITYKEY_TYPE_ED25519)
val identityKey2 =
IdentityKey.createFromPrf(prf, ByteArray(32),
IdentityKey.IDENTITYKEY_TYPE_ED25519)
assertThat(identityKey).isEqualTo(identityKey2)
}
}
@Test
fun identityKey_canBeGeneratedUsingWebAuthnPrfOutput() {
/*
Ideally, we would test the full webauthn interaction (set the PRF extension to true, call
navigator.credentials.create, read the PRF output). The problem is that this would tie
androidX to the implementation of a password manager.
Instead, we manually copy the prfOutput value from //com/google/android/gms/fido/authenticator/embedded/AuthenticationRequestHandlerTest.java,
like a test vector. Even if the two values get out of sync, what we care about is the Base64
format, as the PRF output is fully random-looking by definition.
*/
val prfOutput = Base64.decode("f2HM0TolWHyYJ/+LQDW8N2vRdE0+risMV/tIKXQdj7tVKdGChdJuMyz1" +
"/iX7x4y3GvHLlmja1A8qCsKsekW22Q==",
Base64.DEFAULT
)
val salt = ByteArray(32)
val expectedPrivKeyHex = "bccdec572ae1be6b3c3f3473781965a1935d2614c928f5430b79188950658ad6"
val expectedPubKeyHex = "23fa91da0af9edefae9c53c584f933f3d02f934aebddb70511adac91f255afda"
val identityKey =
IdentityKey.createFromPrf(prfOutput, salt, IdentityKey.IDENTITYKEY_TYPE_ED25519)
assertThat(prfOutput).isNotNull()
assertThat(identityKey.private).isNotNull()
assertThat(identityKey.public).isNotNull()
assertThat(hexEncode(identityKey.private)).isEqualTo(expectedPrivKeyHex)
assertThat(hexEncode(identityKey.public)).isEqualTo(expectedPubKeyHex)
}
}
| 29
|
Kotlin
|
945
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 3,969
|
androidx
|
Apache License 2.0
|
src/main/kotlin/daniel/mybank/repository/ClientRepository.kt
|
DanFonseca
| 602,188,054
| false
| null |
package daniel.mybank.repository
import daniel.mybank.model.Client
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
@Repository
interface ClientRepository : CrudRepository<Client, String> {
fun findByCpf (cpf: String): Client?
}
| 0
|
Kotlin
|
0
| 0
|
b327cd4e8d7735b269708580d02bf865904109b8
| 292
|
mybank
|
MIT License
|
src/main/day16/State.kt
|
ollehagner
| 572,141,655
| false
| null |
package day16
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
data class State(val openers: List<ValveOpener>, val valves: List<Valve>) {
fun potentialMax(timeLimit: Int, distances: Map<Pair<String, String>, Int>): Int {
var remainingTime = (timeLimit * openers.size) - openers.sumOf { it.elapsedTime }
return releasedPressure(timeLimit) + valves
.filter { it.closed() }
.sortedByDescending { it.flowRate }
.map { it to (openers.minOfOrNull { opener -> distances[opener.position to it.id]!! } ?: throw IllegalStateException(
"Invalid distance map"
)) }
.takeWhile { (_, distance) ->
remainingTime -= distance
remainingTime > 0
}
.sumOf { (valve, distance) ->
valve.open(openers.first().elapsedTime + distance).releasedPressure(timeLimit)
}
}
fun openedValves(): Set<String> {
return this.valves.filter { it.opened }.map { it.id }.toSet()
}
fun openerAtValve(id: String): ValveOpener {
return openers.firstOrNull { it.position == id } ?: throw IllegalArgumentException("No opener at valve $id")
}
fun valve(id: String): Valve {
return valves.firstOrNull { it.id == id } ?: throw IllegalArgumentException("No valve at valve $id")
}
fun score(): Int {
return currentRelease() / openers.sumOf { it.elapsedTime }
}
fun releasedPressure(timeLimit: Int): Int {
return valves
.filter { it.opened }
.sumOf { it.releasedPressure(timeLimit) }
}
fun currentRelease(): Int {
return valves.filter { it.opened }
.sumOf { it.flowRate }
}
fun openValves(actions: List<OpenValveAction>): State {
return actions.toSet()
.fold(this) { acc, action ->
acc.openValve(action)
}
}
private fun openValve(action: OpenValveAction): State {
val opener = openerAtValve(action.from)
val newOpener = opener.openValve(action.to, action.time + 1)
val openedValve = valves.first { it.id == action.to }.open(newOpener.elapsedTime)
val newValves = valves
.filter { it.id != openedValve.id }
.fold(mutableListOf(openedValve)) { acc, valve ->
acc.add(valve)
acc
}
return copy(
openers = openers.filter { it != opener } + newOpener,
valves = newValves
)
}
}
| 0
|
Kotlin
|
0
| 0
|
b935fcfb465152f08307399eb85ee8a8a335f1a3
| 2,581
|
aoc2022
|
Apache License 2.0
|
src/test/kotlin/com/hoho/upbitapihelper/service/ApiManagerServiceTest.kt
|
hoho4190
| 518,368,050
| false
|
{"Kotlin": 113377, "Java": 2565}
|
package com.hoho.upbitapihelper.service
import com.hoho.upbitapihelper.util.EnumConverterFactory
import com.hoho.upbitapihelper.util.FileUtil
import com.hoho.upbitapihelper.util.TestUtil
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import okhttp3.MediaType
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.*
import retrofit2.Retrofit
import retrofit2.create
@DisplayName("Unit Test - Api Manager Service")
internal class ApiManagerServiceTest {
private val mockDataPath = "mock-data/api-manager"
private lateinit var amService: ApiManagerService
private lateinit var mockWebServer: MockWebServer
@BeforeEach
@OptIn(ExperimentalSerializationApi::class)
fun beforeEach() {
mockWebServer = MockWebServer()
mockWebServer.start()
val mockUrl = mockWebServer.url("/")
amService = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory(MediaType.parse("application/json")!!))
.addConverterFactory(EnumConverterFactory())
.baseUrl(mockUrl)
.build()
.create()
}
@AfterEach
fun afterEach() {
mockWebServer.shutdown()
}
@Test
@DisplayName("공지사항 조회 - Success")
fun getNoticesSuccessTest() {
// Given
val mockBody = FileUtil.readResource("$mockDataPath/getNotices-success.json")
mockWebServer.enqueue(MockResponse().setBody(mockBody))
val page = 1
val perPage = 3
// When
val call = amService.getNotices(page, perPage)
val response = call.execute()
// Then
println(TestUtil.convertResToPrettyStr(response))
Assertions.assertTrue(response.isSuccessful)
}
@Test
@DisplayName("업비트 소식 조회 - Success")
fun getNewsSuccessTest() {
// Given
val mockBody = FileUtil.readResource("$mockDataPath/getNews-success.json")
mockWebServer.enqueue(MockResponse().setBody(mockBody))
val page = 1
val perPage = 3
// When
val call = amService.getNews(page, perPage)
val response = call.execute()
// Then
println(TestUtil.convertResToPrettyStr(response))
Assertions.assertTrue(response.isSuccessful)
}
}
| 0
|
Kotlin
|
0
| 3
|
9f38818e8c82e7c64a4e11119187ce2b21cdb021
| 2,442
|
upbit-api-helper
|
Apache License 2.0
|
kapitel_11/KameraDemo3/app/src/main/java/com/thomaskuenneth/androidbuch/kamerademo3/KameraDemo3Activity.kt
|
tkuenneth
| 239,271,728
| false
|
{"Text": 1, "Ignore List": 178, "Markdown": 2, "Gradle": 261, "Java Properties": 174, "Shell": 87, "Batchfile": 87, "Proguard": 87, "Kotlin": 304, "XML": 1519, "Maven POM": 1, "Java": 2, "INI": 1, "HTML": 2, "SVG": 1}
|
package com.thomaskuenneth.androidbuch.kamerademo3
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.hardware.camera2.*
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.media.ImageReader
import android.media.MediaScannerConnection
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.util.Size
import android.view.SurfaceHolder
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.ByteBuffer
private val TAG = KameraDemo3Activity::class.simpleName
class KameraDemo3Activity : AppCompatActivity() {
private val requestCamera = 123
private var camera: CameraDevice? = null
private var activeSession: CameraCaptureSession? = null
private lateinit var manager: CameraManager
private lateinit var cameraId: String
private lateinit var imageReader: ImageReader
private lateinit var builderPreview: CaptureRequest.Builder
private val captureSessionCallback = object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
try {
session.setRepeatingRequest(builderPreview.build(), null, null)
activeSession = session
} catch (e: CameraAccessException) {
Log.e(TAG, "onConfigured()", e)
}
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.e(TAG, "onConfigureFailed()")
}
}
private val surfaceHolderCallback: SurfaceHolder.Callback = object : SurfaceHolder.Callback {
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.d(TAG, "surfaceDestroyed()")
}
override fun surfaceCreated(holder: SurfaceHolder) {
Log.d(TAG, "surfaceCreated()")
try {
openCamera()
} catch (e: Exception) {
// SecurityException, CameraAccessException
Log.e(TAG, "openCamera()", e)
}
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int, width: Int,
height: Int
) {
Log.d(TAG, "surfaceChanged()")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
manager = getSystemService(CameraManager::class.java)
setContentView(R.layout.activity_main)
camera = null
}
override fun onPause() {
super.onPause()
surfaceview.visibility = View.GONE
activeSession?.close()
activeSession = null
camera?.close()
camera = null
surfaceview.holder.removeCallback(surfaceHolderCallback)
}
override fun onResume() {
super.onResume()
if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.CAMERA),
requestCamera
)
} else {
configureHolder()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == requestCamera &&
grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED
) {
configureHolder()
}
}
private fun configureHolder() {
surfaceview.holder.addCallback(surfaceHolderCallback)
val sizes = findCameraFacingBack()
if (sizes.isEmpty()) {
Log.d(TAG, "keine passende Kamera gefunden")
finish()
}
val metrics = resources.displayMetrics
for (size in sizes) {
if (size.width > metrics.widthPixels
|| size.height > metrics.heightPixels
) {
continue
}
surfaceview.setOnClickListener { takePicture() }
surfaceview.holder.setFixedSize(size.width, size.height)
surfaceview.visibility = View.VISIBLE
imageReader = ImageReader.newInstance(
size.width, size.height,
ImageFormat.JPEG, 2
)
imageReader.setOnImageAvailableListener(
{
Log.d(TAG, "setOnImageAvailableListener()")
val image = imageReader.acquireLatestImage()
val planes = image.planes
val buffer = planes[0].buffer
saveJPG(buffer)
image.close()
}, null
)
return
}
Log.d(TAG, "Zu groß")
finish()
}
// vorhandene Kameras ermitteln und auswählen
private fun findCameraFacingBack(): Array<Size> {
cameraId = ""
try {
val ids = manager.cameraIdList
for (id in ids) {
val cc = manager.getCameraCharacteristics(id)
Log.d(TAG, "$id: $cc")
val lensFacing = cc.get(CameraCharacteristics.LENS_FACING)
if (lensFacing != null &&
lensFacing ==
CameraCharacteristics.LENS_FACING_BACK
) {
cameraId = id
cc.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP
)?.run {
return getOutputSizes(SurfaceHolder::class.java)
}
}
}
} catch (e: CameraAccessException) {
Log.e(TAG, "findCameraFacingBack()", e)
} catch (e: NullPointerException) {
Log.e(TAG, "findCameraFacingBack()", e)
}
return emptyArray()
}
@Throws(SecurityException::class)
private fun openCamera() {
manager.openCamera(
cameraId,
object : CameraDevice.StateCallback() {
override fun onOpened(_camera: CameraDevice) {
Log.d(TAG, "onOpened()")
camera = _camera
createPreviewCaptureSession()
}
override fun onDisconnected(camera: CameraDevice) {
Log.d(TAG, "onDisconnected()")
}
override fun onError(
camera: CameraDevice,
error: Int
) {
Log.d(TAG, "onError()")
}
}, null
)
}
private fun createPreviewCaptureSession() {
val outputs = mutableListOf<OutputConfiguration>()
outputs.add(OutputConfiguration(surfaceview.holder.surface))
outputs.add(OutputConfiguration(imageReader.surface))
val sessionConfiguration = SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
outputs, mainExecutor, captureSessionCallback
)
try {
camera?.createCaptureRequest(
CameraDevice.TEMPLATE_PREVIEW
)?.let {
builderPreview = it
it.addTarget(surfaceview.holder.surface)
camera?.createCaptureSession(sessionConfiguration)
}
} catch (e: Exception) {
Log.e(TAG, "createPreviewCaptureSession()", e)
}
}
private fun takePicture() {
try {
val builder = camera?.createCaptureRequest(
CameraDevice.TEMPLATE_STILL_CAPTURE
)
builder?.addTarget(imageReader.surface)
builder?.build()?.let {
activeSession?.capture(it, null, null)
}
} catch (e: CameraAccessException) {
Log.e(TAG, "takePicture()", e)
}
}
private fun saveJPG(data: ByteBuffer) {
getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.let {
if (it.mkdirs()) {
Log.d(TAG, "dirs created")
}
val f = File(it, "${TAG}_${System.currentTimeMillis()}.jpg")
try {
FileOutputStream(f).use { fos ->
BufferedOutputStream(fos).use { bos ->
while (data.hasRemaining()) {
bos.write(data.get().toInt())
}
Toast.makeText(
this, R.string.click,
Toast.LENGTH_SHORT
).show()
addToMediaProvider(f)
}
}
} catch (e: IOException) {
Log.e(TAG, "saveJPG()", e)
}
}
}
private fun addToMediaProvider(f: File) {
MediaScannerConnection.scanFile(
this,
arrayOf(f.toString()),
arrayOf("image/jpeg")
) { _, uri ->
val i = Intent(
Intent.ACTION_VIEW,
uri
)
startActivity(i)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
977f93b8ff9bdd50d45a1a51d009b1eba75b7eb0
| 9,459
|
begleitmaterialien-zu-android-11
|
Apache License 2.0
|
app/src/main/java/io/github/wulkanowy/data/repositories/MessageRepository.kt
|
wulkanowy
| 87,721,285
| false
| null |
package io.github.wulkanowy.data.repositories
import android.content.Context
import com.squareup.moshi.Moshi
import dagger.hilt.android.qualifiers.ApplicationContext
import io.github.wulkanowy.R
import io.github.wulkanowy.data.Resource
import io.github.wulkanowy.data.db.SharedPrefProvider
import io.github.wulkanowy.data.db.dao.MessageAttachmentDao
import io.github.wulkanowy.data.db.dao.MessagesDao
import io.github.wulkanowy.data.db.entities.Message
import io.github.wulkanowy.data.db.entities.MessageWithAttachment
import io.github.wulkanowy.data.db.entities.Recipient
import io.github.wulkanowy.data.db.entities.Semester
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.data.enums.MessageFolder
import io.github.wulkanowy.data.enums.MessageFolder.RECEIVED
import io.github.wulkanowy.data.mappers.mapFromEntities
import io.github.wulkanowy.data.mappers.mapToEntities
import io.github.wulkanowy.data.pojos.MessageDraft
import io.github.wulkanowy.data.pojos.MessageDraftJsonAdapter
import io.github.wulkanowy.sdk.Sdk
import io.github.wulkanowy.sdk.pojo.Folder
import io.github.wulkanowy.sdk.pojo.SentMessage
import io.github.wulkanowy.utils.AutoRefreshHelper
import io.github.wulkanowy.utils.getRefreshKey
import io.github.wulkanowy.utils.init
import io.github.wulkanowy.utils.networkBoundResource
import io.github.wulkanowy.utils.uniqueSubtract
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.sync.Mutex
import timber.log.Timber
import java.time.LocalDateTime.now
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageRepository @Inject constructor(
private val messagesDb: MessagesDao,
private val messageAttachmentDao: MessageAttachmentDao,
private val sdk: Sdk,
@ApplicationContext private val context: Context,
private val refreshHelper: AutoRefreshHelper,
private val sharedPrefProvider: SharedPrefProvider,
private val moshi: Moshi,
) {
private val saveFetchResultMutex = Mutex()
private val cacheKey = "message"
@Suppress("UNUSED_PARAMETER")
fun getMessages(
student: Student, semester: Semester,
folder: MessageFolder, forceRefresh: Boolean, notify: Boolean = false
): Flow<Resource<List<Message>>> = networkBoundResource(
mutex = saveFetchResultMutex,
shouldFetch = {
it.isEmpty() || forceRefresh || refreshHelper.isShouldBeRefreshed(
getRefreshKey(cacheKey, student, folder)
)
},
query = { messagesDb.loadAll(student.id.toInt(), folder.id) },
fetch = {
sdk.init(student).getMessages(Folder.valueOf(folder.name), now().minusMonths(3), now())
.mapToEntities(student)
},
saveFetchResult = { old, new ->
messagesDb.deleteAll(old uniqueSubtract new)
messagesDb.insertAll((new uniqueSubtract old).onEach {
it.isNotified = !notify
})
messagesDb.updateAll(getMessagesWithReadByChange(old, new, !notify))
refreshHelper.updateLastRefreshTimestamp(getRefreshKey(cacheKey, student, folder))
}
)
private fun getMessagesWithReadByChange(
old: List<Message>, new: List<Message>,
setNotified: Boolean
): List<Message> {
val oldMeta = old.map { Triple(it, it.readBy, it.unreadBy) }
val newMeta = new.map { Triple(it, it.readBy, it.unreadBy) }
val updatedItems = newMeta uniqueSubtract oldMeta
return updatedItems.map {
val oldItem = old.find { item -> item.messageId == it.first.messageId }
it.first.apply {
id = oldItem?.id ?: 0
isNotified = oldItem?.isNotified ?: setNotified
content = oldItem?.content.orEmpty()
}
}
}
fun getMessage(
student: Student, message: Message, markAsRead: Boolean = false
): Flow<Resource<MessageWithAttachment?>> = networkBoundResource(
shouldFetch = {
checkNotNull(it, { "This message no longer exist!" })
Timber.d("Message content in db empty: ${it.message.content.isEmpty()}")
it.message.unread || it.message.content.isEmpty()
},
query = { messagesDb.loadMessageWithAttachment(student.id.toInt(), message.messageId) },
fetch = {
sdk.init(student).getMessageDetails(
messageId = it!!.message.messageId,
folderId = message.folderId,
read = markAsRead,
id = message.realId
).let { details ->
details.content to details.attachments.mapToEntities()
}
},
saveFetchResult = { old, (downloadedMessage, attachments) ->
checkNotNull(old, { "Fetched message no longer exist!" })
messagesDb.updateAll(listOf(old.message.apply {
id = old.message.id
unread = !markAsRead
content = content.ifBlank { downloadedMessage }
}))
messageAttachmentDao.insertAttachments(attachments)
Timber.d("Message ${message.messageId} with blank content: ${old.message.content.isBlank()}, marked as read")
}
)
fun getMessagesFromDatabase(student: Student): Flow<List<Message>> {
return messagesDb.loadAll(student.id.toInt(), RECEIVED.id)
}
suspend fun updateMessages(messages: List<Message>) {
return messagesDb.updateAll(messages)
}
suspend fun sendMessage(
student: Student, subject: String, content: String,
recipients: List<Recipient>
): SentMessage = sdk.init(student).sendMessage(
subject = subject,
content = content,
recipients = recipients.mapFromEntities()
)
suspend fun deleteMessage(student: Student, message: Message) {
val isDeleted = sdk.init(student).deleteMessages(
messages = listOf(message.messageId), message.folderId
)
if (message.folderId != MessageFolder.TRASHED.id && isDeleted) {
val deletedMessage = message.copy(folderId = MessageFolder.TRASHED.id).apply {
id = message.id
content = message.content
}
messagesDb.updateAll(listOf(deletedMessage))
} else messagesDb.deleteAll(listOf(message))
}
var draftMessage: MessageDraft?
get() = sharedPrefProvider.getString(context.getString(R.string.pref_key_message_send_draft))
?.let { MessageDraftJsonAdapter(moshi).fromJson(it) }
set(value) = sharedPrefProvider.putString(
context.getString(R.string.pref_key_message_send_draft),
value?.let { MessageDraftJsonAdapter(moshi).toJson(it) }
)
}
| 76
|
Kotlin
|
25
| 148
|
6007de017f01a676662534737afe5c684eb7711e
| 6,774
|
wulkanowy
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsppudautomationapi/controller/ReferenceControllerTest.kt
|
ministryofjustice
| 709,230,604
| false
|
{"Kotlin": 99495, "Dockerfile": 1375, "Shell": 77}
|
package uk.gov.justice.digital.hmpps.hmppsppudautomationapi.controller
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.then
import org.springframework.http.HttpStatus
import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.ppud.PpudClient
import uk.gov.justice.digital.hmpps.hmppsppudautomationapi.testdata.randomString
@ExtendWith(MockitoExtension::class)
internal class ReferenceControllerTest {
@Mock
lateinit var ppudClient: PpudClient
private lateinit var controller: ReferenceController
@BeforeEach
fun beforeEach() {
controller = ReferenceController(ppudClient)
}
@Test
fun `when establishments is called then ppud client is invoked and results returned`() {
runBlocking {
val values = listOf(randomString(), randomString(), randomString())
given(ppudClient.retrieveLookupValues()).willReturn(values)
val result = controller.establishments()
then(ppudClient).should().retrieveLookupValues()
assertEquals(HttpStatus.OK.value(), result.statusCode.value())
assertEquals(values, result.body?.values)
}
}
}
| 1
|
Kotlin
|
0
| 1
|
67f863a4c0716366c1756e90cdccd46b2b7e3eec
| 1,389
|
hmpps-ppud-automation-api
|
MIT License
|
app/src/main/java/com/stocksexchange/android/data/stores/wallets/WalletsServerDataStore.kt
|
nscoincommunity
| 277,168,471
| true
|
{"Kotlin": 2814235}
|
package com.stocksexchange.android.data.stores.wallets
import com.stocksexchange.api.StexRestApi
import com.stocksexchange.api.model.rest.TransactionAddressData
import com.stocksexchange.api.model.rest.Wallet
import com.stocksexchange.api.model.rest.parameters.WalletParameters
import com.stocksexchange.core.model.Result
import com.stocksexchange.core.utils.helpers.performBackgroundOperation
class WalletsServerDataStore(
private val stexRestApi: StexRestApi
) : WalletsDataStore {
override suspend fun save(wallet: Wallet) {
throw UnsupportedOperationException()
}
override suspend fun save(wallets: List<Wallet>) {
throw UnsupportedOperationException()
}
override suspend fun create(currencyId: Int, protocolId: Int): Result<Wallet> {
return performBackgroundOperation {
stexRestApi.createWallet(currencyId, protocolId)
}
}
override suspend fun createDepositAddressData(walletId: Long, protocolId: Int): Result<TransactionAddressData> {
return performBackgroundOperation {
stexRestApi.createDepositAddress(walletId, protocolId)
}
}
override suspend fun deleteAll() {
throw UnsupportedOperationException()
}
override suspend fun search(params: WalletParameters): Result<List<Wallet>> {
throw UnsupportedOperationException()
}
override suspend fun get(walletId: Long): Result<Wallet> {
return performBackgroundOperation {
stexRestApi.getWallet(walletId)
}
}
override suspend fun getAll(params: WalletParameters): Result<List<Wallet>> {
return performBackgroundOperation {
stexRestApi.getWallets(params)
}
}
}
| 0
| null |
0
| 0
|
52766afab4f96506a2d9ed34bf3564b6de7af8c3
| 1,742
|
Android-app
|
MIT License
|
app/src/main/java/com/stocksexchange/android/data/stores/wallets/WalletsServerDataStore.kt
|
nscoincommunity
| 277,168,471
| true
|
{"Kotlin": 2814235}
|
package com.stocksexchange.android.data.stores.wallets
import com.stocksexchange.api.StexRestApi
import com.stocksexchange.api.model.rest.TransactionAddressData
import com.stocksexchange.api.model.rest.Wallet
import com.stocksexchange.api.model.rest.parameters.WalletParameters
import com.stocksexchange.core.model.Result
import com.stocksexchange.core.utils.helpers.performBackgroundOperation
class WalletsServerDataStore(
private val stexRestApi: StexRestApi
) : WalletsDataStore {
override suspend fun save(wallet: Wallet) {
throw UnsupportedOperationException()
}
override suspend fun save(wallets: List<Wallet>) {
throw UnsupportedOperationException()
}
override suspend fun create(currencyId: Int, protocolId: Int): Result<Wallet> {
return performBackgroundOperation {
stexRestApi.createWallet(currencyId, protocolId)
}
}
override suspend fun createDepositAddressData(walletId: Long, protocolId: Int): Result<TransactionAddressData> {
return performBackgroundOperation {
stexRestApi.createDepositAddress(walletId, protocolId)
}
}
override suspend fun deleteAll() {
throw UnsupportedOperationException()
}
override suspend fun search(params: WalletParameters): Result<List<Wallet>> {
throw UnsupportedOperationException()
}
override suspend fun get(walletId: Long): Result<Wallet> {
return performBackgroundOperation {
stexRestApi.getWallet(walletId)
}
}
override suspend fun getAll(params: WalletParameters): Result<List<Wallet>> {
return performBackgroundOperation {
stexRestApi.getWallets(params)
}
}
}
| 0
| null |
0
| 0
|
52766afab4f96506a2d9ed34bf3564b6de7af8c3
| 1,742
|
Android-app
|
MIT License
|
app/app/src/main/java/com/proct/activities/inreal/utils/diffutils/order/DiffUtilsOrder.kt
|
inRealAR
| 361,197,397
| false
| null |
package com.proct.activities.inreal.utils.diffutils.order
import androidx.recyclerview.widget.DiffUtil
import com.proct.activities.inreal.data.model.OrderItem
class DiffUtilsOrder(private val oldList: List<OrderItem>, private val newList: List<OrderItem>) :
DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList[oldItemPosition] == newList[newItemPosition]
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
oldList[oldItemPosition] == newList[newItemPosition] && oldItemPosition == newItemPosition
}
| 0
|
Kotlin
|
1
| 1
|
4f50e60dce104747c133954f38e1471ff25713b6
| 737
|
inReal
|
MIT License
|
demo/demo/src/jsMain/kotlin/zakadabar/demo/frontend/pages/ship/Table.kt
|
kondorj
| 355,137,640
| true
|
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
|
/*
* Copyright © 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.demo.frontend.pages.ship
import zakadabar.demo.data.PortDto
import zakadabar.demo.data.SeaDto
import zakadabar.demo.data.ship.ShipDto
import zakadabar.demo.data.speed.SpeedDto
import zakadabar.demo.resources.Strings
import zakadabar.stack.data.builtin.account.AccountPublicDto
import zakadabar.stack.frontend.builtin.table.ZkTable
class Table : ZkTable<ShipDto>() {
// These preloads are a bit too many, it might be better to create a
// DTO for this table and build the result properly on server side.
private val seas by preload { SeaDto.allAsMap() }
private val ports by preload { PortDto.allAsMap() }
private val speeds by preload { SpeedDto.allAsMap() }
private val accounts by preload { AccountPublicDto.allAsMap() }
override fun onConfigure() {
title = Strings.ships
crud = Ships
add = true
search = true
+ ShipDto::id
+ ShipDto::name
+ ShipDto::hasPirateFlag
+ custom {
label = Strings.speed
render = { + speeds[it.speed]?.description }
}
+ custom {
label = Strings.captain
render = { + accounts[it.captain]?.fullName }
}
+ custom {
label = Strings.port
render = {
val port = ports[it.port]
val sea = seas[port?.sea]
+ "${port?.name ?: "Davy Jones Locker"} (${sea?.name ?: "At World's End"})"
}
}
+ actions()
}
}
| 0
| null |
0
| 0
|
2379c0fb031f04a230e753a9afad6bd260f6a0b2
| 1,642
|
zakadabar-stack
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.