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
profile/src/main/java/org/openedx/profile/presentation/profile/ProfileViewModel.kt
openedx
613,282,821
false
{"Kotlin": 2073675, "Groovy": 5883, "JavaScript": 1129}
package org.openedx.profile.presentation.profile import androidx.fragment.app.FragmentManager import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import org.openedx.core.BaseViewModel import org.openedx.core.R import org.openedx.core.UIMessage import org.openedx.core.extension.isInternetError import org.openedx.core.system.ResourceManager import org.openedx.profile.domain.interactor.ProfileInteractor import org.openedx.profile.presentation.ProfileAnalytics import org.openedx.profile.presentation.ProfileAnalyticsEvent import org.openedx.profile.presentation.ProfileAnalyticsKey import org.openedx.profile.presentation.ProfileRouter import org.openedx.profile.system.notifier.AccountUpdated import org.openedx.profile.system.notifier.ProfileNotifier class ProfileViewModel( private val interactor: ProfileInteractor, private val resourceManager: ResourceManager, private val notifier: ProfileNotifier, private val analytics: ProfileAnalytics, val profileRouter: ProfileRouter ) : BaseViewModel() { private val _uiState: MutableStateFlow<ProfileUIState> = MutableStateFlow(ProfileUIState.Loading) internal val uiState: StateFlow<ProfileUIState> = _uiState.asStateFlow() private val _uiMessage = MutableLiveData<UIMessage>() val uiMessage: LiveData<UIMessage> get() = _uiMessage private val _isUpdating = MutableLiveData<Boolean>() val isUpdating: LiveData<Boolean> get() = _isUpdating init { getAccount() } override fun onCreate(owner: LifecycleOwner) { super.onCreate(owner) viewModelScope.launch { notifier.notifier.collect { if (it is AccountUpdated) { getAccount() } } } } private fun getAccount() { _uiState.value = ProfileUIState.Loading viewModelScope.launch { try { val cachedAccount = interactor.getCachedAccount() if (cachedAccount == null) { _uiState.value = ProfileUIState.Loading } else { _uiState.value = ProfileUIState.Data( account = cachedAccount ) } val account = interactor.getAccount() _uiState.value = ProfileUIState.Data( account = account ) } catch (e: Exception) { if (e.isInternetError()) { _uiMessage.value = UIMessage.SnackBarMessage(resourceManager.getString(R.string.core_error_no_connection)) } else { _uiMessage.value = UIMessage.SnackBarMessage(resourceManager.getString(R.string.core_error_unknown_error)) } } finally { _isUpdating.value = false } } } fun updateAccount() { _isUpdating.value = true getAccount() } fun profileEditClicked(fragmentManager: FragmentManager) { (uiState.value as? ProfileUIState.Data)?.let { data -> profileRouter.navigateToEditProfile( fragmentManager, data.account ) } logProfileEvent(ProfileAnalyticsEvent.EDIT_CLICKED) } private fun logProfileEvent( event: ProfileAnalyticsEvent, params: Map<String, Any?> = emptyMap(), ) { analytics.logEvent( event = event.eventName, params = buildMap { put(ProfileAnalyticsKey.NAME.key, event.biValue) put(ProfileAnalyticsKey.CATEGORY.key, ProfileAnalyticsKey.PROFILE.key) putAll(params) } ) } }
85
Kotlin
23
18
4d36310011d20ce0fe896ae4e4d3ca2148f322b6
4,055
openedx-app-android
Apache License 2.0
app/src/main/java/com/robyn/dayplus2/display/DisplayActivity.kt
yifeidesu
92,456,032
false
{"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 17, "Proguard": 1, "XML": 36, "Text": 1, "Java": 2, "Kotlin": 38}
package com.robyn.dayplus2.display import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentStatePagerAdapter import android.support.v4.content.FileProvider import android.support.v4.view.ViewPager import android.support.v7.app.ActionBar import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.widget.ImageView import com.robyn.dayplus2.R import com.robyn.dayplus2.data.MyEvent import com.robyn.dayplus2.data.source.local.EventDatabase import com.robyn.dayplus2.data.source.local.EventsLocalDataSource import com.robyn.dayplus2.myUtils.formatDateStr import com.robyn.dayplus2.myUtils.getImageFile import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.runBlocking class DisplayActivity : AppCompatActivity(), DisplayFragment.DisplayCallback { private lateinit var mEvent: MyEvent // Current event events_item to display lateinit var mPresenter: DisplayPresenter var mActionBar: ActionBar? = null lateinit var mDataSource: EventsLocalDataSource override fun setToolbarContent(event: MyEvent) { customToolbar(event) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.display_ac) mDataSource = getDataSource() // // Setup toolbar title and subtitle. cannot included in set fg content // val initialId = intent.getStringExtra(EXTRA_EVENT_ID_DISPLAY) // mEvent = runBlocking { async { mDataSource.fetchEvent(initialId) }.await() } // customToolbar(mEvent) // Setup PagerAdapter val events = runBlocking { async { mDataSource.fetchAllEvents() }.await() } val eventsCount = events.size val fragmentManager = supportFragmentManager val pager = findViewById<ViewPager>(R.id.fg_container_display_ac_pager) pager.adapter = object : FragmentStatePagerAdapter(fragmentManager) { // Returns the fg that passing to the framework. override fun getItem(position: Int): Fragment { // val uuid = runBlocking { // async { mDataSource.fetchAllEvents()[position].uuid }.await() // } val uuid = events[position].uuid val fragment = DisplayFragment.newInstance(uuid) DisplayPresenter(uuid, mDataSource, fragment) return fragment } override fun getCount(): Int { return eventsCount } } val id = intent.getStringExtra(EXTRA_EVENT_ID_DISPLAY) val currentPosition = intent.getIntExtra(EXTRA_EVENT_POSITION_DISPLAY, 0) val currentEvent = events[currentPosition] setSupportActionBar(findViewById(R.id.toolbar_display_ac)) supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) customToolbar(currentEvent) } pager.currentItem = currentPosition pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { customToolbar(events[position]) } }) // todo move to fg //val background = findViewById<ImageView>(R.id.background_pic_display_ac) //mEvent = this..fetchEvent(id) // if (mEvent.getImageFile(applicationContext) != null) { // val file = mEvent.getImageFile(applicationContext) // file?.let { // val uri = FileProvider.getUriForFile( // applicationContext, // "com.robyn.dayplus2.fileprovider", // it // ) // background.setImageURI(uri) // } // } // // // todo move to fg // mEvent.getImageFile(applicationContext)?.apply { // val file = this // val uri = FileProvider.getUriForFile(applicationContext, AUTHORITY, file) // background.setImageURI(uri) // } } private fun getDataSource():EventsLocalDataSource { return EventsLocalDataSource .getInstance(EventDatabase.getInMemoryDatabase(applicationContext).eventsDao()) } private fun customToolbar(event: MyEvent) { supportActionBar?.let { it.title = event.title.toString() it.subtitle = event.formatDateStr() } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_display, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { // R.id.edit -> { // startActivity( // AddEditActivity.newIntent( // applicationContext, // intent.getStringExtra(EXTRA_EVENT_ID_DISPLAY) // ) // ) // // return true // } // // todo move to fg // R.id.remove -> { // val builder = AlertDialog.Builder(this) // builder.setMessage("Sure to remove this mEvent?") // .setPositiveButton("Yes") { dialog, id -> // //dataSource.removeEvent(mEvent.mUuid) // [email protected]() // val intent = Intent( // applicationContext, // EventsActivity::class.java // ) // startActivity(intent) // } // .setNegativeButton("No") { dialog, id -> } // builder.create().show() // return true // } else -> return super.onOptionsItemSelected(item) } } companion object { private const val AUTHORITY = "com.robyn.dayplus2.fileprovider" const val EXTRA_EVENT_ID_DISPLAY = "com.robyn.dayplus2.event_id" const val EXTRA_EVENT_POSITION_DISPLAY = "EXTRA_EVENT_POSITION_DISPLAY" fun newIntent(context: Context, id: String): Intent { val intent = Intent(context, DisplayActivity::class.java) intent.putExtra(EXTRA_EVENT_ID_DISPLAY, id) return intent } } }
1
null
1
1
788a1ef3cdf88b9e6e65f513148cda58bb43fef7
6,901
DayPlus-Countdown
Apache License 2.0
peacock-core/src/main/kotlin/com/peacock/core/domain/account/AccountRepository.kt
peacock-123
828,176,906
false
{"Kotlin": 12393, "Dockerfile": 189}
package com.peacock.core.domain.account import com.peacock.core.domain.account.vo.AccountId import com.peacock.core.domain.vo.Email import org.springframework.data.repository.CrudRepository interface AccountRepository : CrudRepository<Account, AccountId> { fun findByEmail(email: Email): Account? }
0
Kotlin
0
0
5523334b76aa3b4bcbe9faf790e71191e26b26fe
305
peacock-server
MIT License
mongo/src/test/java/com/rarible/core/mongo/AbstractIntegrationTest.kt
rarible
357,923,214
false
null
package com.rarible.core.mongo import com.rarible.core.test.ext.MongoCleanup import com.rarible.core.test.ext.MongoTest import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.data.mongodb.core.ReactiveMongoOperations import org.springframework.test.context.ContextConfiguration @MongoTest @MongoCleanup @SpringBootTest(classes = [TestConfiguration::class]) @ContextConfiguration(classes = [MockContext::class]) abstract class AbstractIntegrationTest { @Autowired protected lateinit var mongo: ReactiveMongoOperations }
0
null
3
9
fb72de3228c224daf7e8ec2e09becc4dee602733
623
service-core
MIT License
common-model/src/main/java/com/moadgara/common_model/usecase/UseCase.kt
YKakdas
692,527,114
false
{"Kotlin": 320913}
package com.moadgara.common_model.usecase import com.moadgara.common_model.network.NetworkResult import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext abstract class UseCase<in P, R>(private val coroutineDispatcher: CoroutineDispatcher) { /** Executes the use case asynchronously and returns a [NetworkResult]. * * @return a [NetworkResult]. * * @param param the input parameters to run the use case with */ suspend operator fun invoke(param: P): NetworkResult<R> { return try { // Moving all use case's executions to the injected dispatcher // In production code, this is usually the Default dispatcher (background thread) // In tests, this becomes a TestCoroutineDispatcher withContext(coroutineDispatcher) { execute(param) } } catch (e: Exception) { NetworkResult.Failure(e.message) } } /** * Override this to set the code to be executed. */ @Throws(RuntimeException::class) protected abstract fun execute(param: P): NetworkResult<R> }
6
Kotlin
1
0
fa509863863ffc8a315bd238afe2f3d0f0ec61c8
1,143
NexusNook
Apache License 2.0
src/offer/Questions08.kt
andrewloski
154,839,594
true
{"Kotlin": 79493, "Java": 31720}
package offer //给定一颗二叉树及其中一个节点,找出其中序遍历序列的下一个节点 class BinaryTreeNodeWithFather<T>(var mValues: T, var mFather: BinaryTreeNodeWithFather<T>? = null, var mLeft: BinaryTreeNodeWithFather<T>? = null, var mRight: BinaryTreeNodeWithFather<T>? = null) fun main(args: Array<String>) { val a = BinaryTreeNodeWithFather<Char>('a') val b = BinaryTreeNodeWithFather<Char>('b', a) val c = BinaryTreeNodeWithFather<Char>('c', a) val d = BinaryTreeNodeWithFather<Char>('d', b) val e = BinaryTreeNodeWithFather<Char>('e', b) val f = BinaryTreeNodeWithFather<Char>('f', c) val g = BinaryTreeNodeWithFather<Char>('g', c) val h = BinaryTreeNodeWithFather<Char>('h', e) val i = BinaryTreeNodeWithFather<Char>('i', e) a.mLeft = b a.mRight = c b.mLeft = d b.mRight = e c.mLeft = f c.mRight = g e.mLeft = h e.mRight = i val str = "空" println("a:${getNext(a) ?: str}") println("b:${getNext(b) ?: str}") println("c:${getNext(c) ?: str}") println("d:${getNext(d) ?: str}") println("e:${getNext(e) ?: str}") println("f:${getNext(f) ?: str}") println("g:${getNext(g) ?: str}") println("h:${getNext(h) ?: str}") println("i:${getNext(i) ?: str}") } fun <T> getNext(node: BinaryTreeNodeWithFather<T>): T? { if (node.mRight == null) { if (node.mFather != null) { if (node.mFather!!.mLeft === node) { return node.mFather?.mValues } else { var nNode = node while (nNode.mFather!!.mFather != null) { if (nNode.mFather!!.mFather!!.mLeft === nNode.mFather) { return nNode.mFather!!.mFather!!.mValues } nNode = nNode.mFather!! } return null } } else { return null } } else { var right = node.mRight while (right!!.mLeft != null) { right = right.mLeft } return right.mValues } }
0
Kotlin
0
0
878265e3fcc76c66b55f3f39bba11dee540b3691
1,772
Algorithm
Apache License 2.0
app/src/main/java/com/google/norinori6791/cycledo/ui/dust/DustFragment.kt
norinori777
208,719,519
false
null
package com.google.norinori6791.cycledo.ui.dust import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.norinori6791.cycledo.R class DustFragment : Fragment() { private lateinit var dustViewModel: DustViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { dustViewModel = ViewModelProviders.of(this).get(DustViewModel::class.java) val root = inflater.inflate(R.layout.fragment_send, container, false) val textView: TextView = root.findViewById(R.id.text_send) dustViewModel.text.observe(this, Observer { textView.text = it }) return root } }
6
Kotlin
0
0
64d33c5d84b39b4065b4034e45b33bace2eb3b5a
953
CycleDo
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/BowlingPins.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.BowlingPins: ImageVector get() { if (_bowlingPins != null) { return _bowlingPins!! } _bowlingPins = Builder(name = "BowlingPins", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 8.5f) arcToRelative(19.105f, 19.105f, 0.0f, false, true, 0.548f, -2.382f) arcTo(9.61f, 9.61f, 0.0f, false, false, 10.0f, 4.0f) arcTo(3.827f, 3.827f, 0.0f, false, false, 6.0f, 0.0f) arcTo(3.827f, 3.827f, 0.0f, false, false, 2.0f, 4.0f) arcToRelative(9.61f, 9.61f, 0.0f, false, false, 0.452f, 2.119f) arcTo(19.136f, 19.136f, 0.0f, false, true, 3.0f, 8.5f) arcToRelative(6.542f, 6.542f, 0.0f, false, true, -1.175f, 2.92f) arcTo(10.433f, 10.433f, 0.0f, false, false, 0.0f, 16.773f) arcToRelative(12.344f, 12.344f, 0.0f, false, false, 2.083f, 6.6f) lineTo(2.531f, 24.0f) lineTo(9.469f, 24.0f) lineToRelative(0.448f, -0.624f) arcTo(12.344f, 12.344f, 0.0f, false, false, 12.0f, 16.773f) arcToRelative(10.433f, 10.433f, 0.0f, false, false, -1.825f, -5.353f) arcTo(6.555f, 6.555f, 0.0f, false, true, 9.0f, 8.5f) close() moveTo(6.0f, 3.0f) curveToRelative(0.71f, 0.0f, 1.0f, 0.29f, 1.0f, 0.922f) curveToRelative(-0.023f, 0.195f, -0.213f, 0.9f, -0.352f, 1.417f) arcTo(22.624f, 22.624f, 0.0f, false, false, 6.036f, 8.0f) lineTo(5.964f, 8.0f) arcToRelative(22.624f, 22.624f, 0.0f, false, false, -0.615f, -2.661f) curveTo(5.21f, 4.824f, 5.02f, 4.117f, 5.0f, 4.0f) curveTo(5.0f, 3.29f, 5.29f, 3.0f, 6.0f, 3.0f) close() moveTo(7.856f, 21.0f) lineTo(4.144f, 21.0f) arcTo(9.183f, 9.183f, 0.0f, false, true, 3.0f, 16.773f) arcToRelative(7.864f, 7.864f, 0.0f, false, true, 1.423f, -3.854f) arcTo(18.836f, 18.836f, 0.0f, false, false, 5.434f, 11.0f) lineTo(6.566f, 11.0f) arcToRelative(18.836f, 18.836f, 0.0f, false, false, 1.011f, 1.919f) arcTo(7.864f, 7.864f, 0.0f, false, true, 9.0f, 16.773f) arcTo(9.184f, 9.184f, 0.0f, false, true, 7.856f, 21.0f) close() moveTo(22.175f, 11.42f) arcTo(6.555f, 6.555f, 0.0f, false, true, 21.0f, 8.5f) arcToRelative(19.105f, 19.105f, 0.0f, false, true, 0.548f, -2.382f) arcTo(9.61f, 9.61f, 0.0f, false, false, 22.0f, 4.0f) arcToRelative(3.827f, 3.827f, 0.0f, false, false, -4.0f, -4.0f) arcToRelative(3.827f, 3.827f, 0.0f, false, false, -4.0f, 4.0f) arcToRelative(9.61f, 9.61f, 0.0f, false, false, 0.452f, 2.119f) arcTo(19.136f, 19.136f, 0.0f, false, true, 15.0f, 8.5f) arcToRelative(6.542f, 6.542f, 0.0f, false, true, -1.175f, 2.92f) arcTo(10.433f, 10.433f, 0.0f, false, false, 12.0f, 16.773f) arcToRelative(12.344f, 12.344f, 0.0f, false, false, 2.083f, 6.6f) lineToRelative(0.448f, 0.624f) horizontalLineToRelative(6.938f) lineToRelative(0.448f, -0.624f) arcTo(12.344f, 12.344f, 0.0f, false, false, 24.0f, 16.773f) arcTo(10.433f, 10.433f, 0.0f, false, false, 22.175f, 11.42f) close() moveTo(18.0f, 3.0f) curveToRelative(0.71f, 0.0f, 1.0f, 0.29f, 1.0f, 0.922f) curveToRelative(-0.023f, 0.195f, -0.213f, 0.9f, -0.352f, 1.417f) arcTo(22.624f, 22.624f, 0.0f, false, false, 18.036f, 8.0f) horizontalLineToRelative(-0.072f) arcToRelative(22.624f, 22.624f, 0.0f, false, false, -0.615f, -2.661f) curveTo(17.21f, 4.824f, 17.02f, 4.117f, 17.0f, 4.0f) curveTo(17.0f, 3.29f, 17.29f, 3.0f, 18.0f, 3.0f) close() moveTo(19.856f, 21.0f) lineTo(16.144f, 21.0f) arcTo(9.183f, 9.183f, 0.0f, false, true, 15.0f, 16.773f) arcToRelative(7.864f, 7.864f, 0.0f, false, true, 1.423f, -3.854f) arcTo(18.836f, 18.836f, 0.0f, false, false, 17.434f, 11.0f) horizontalLineToRelative(1.132f) arcToRelative(18.836f, 18.836f, 0.0f, false, false, 1.011f, 1.919f) arcTo(7.864f, 7.864f, 0.0f, false, true, 21.0f, 16.773f) arcTo(9.184f, 9.184f, 0.0f, false, true, 19.856f, 21.0f) close() } } .build() return _bowlingPins!! } private var _bowlingPins: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,759
icons
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppselectronicmonitoringcreateanorderapi/models/AdditionalDocument.kt
ministryofjustice
852,871,729
false
{"Kotlin": 75871, "Dockerfile": 1173}
package uk.gov.justice.digital.hmpps.hmppselectronicmonitoringcreateanorderapi.models import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.Table import java.util.* @Entity @Table(name = "ADDITIONAL_DOCUMENTIONS") data class AdditionalDocument( @Id @Column(name = "ID", nullable = false, unique = true) val id: UUID = UUID.randomUUID(), @Column(name = "ORDER_ID", nullable = false, unique = true) val orderId: UUID, @Column(name = "FILE_NAME", nullable = true) var fileName: String? = null, @ManyToOne(optional = true) @JoinColumn(name = "ORDER_ID", updatable = false, insertable = false) private val orderForm: OrderForm? = null, )
1
Kotlin
0
0
1a1e301379437d0d9a312a62d24d1c9e07016d63
805
hmpps-electronic-monitoring-create-an-order-api
MIT License
app/src/main/java/com.terracode.blueharvest/listeners/accessibilityListeners/UnitToggleListener.kt
Capstone-Terracoders
718,832,727
false
{"Kotlin": 201501}
package com.terracode.blueharvest.listeners.accessibilityListeners import android.widget.CompoundButton import com.terracode.blueharvest.AccessibilitySettingsActivity import com.terracode.blueharvest.utils.PreferenceManager import com.terracode.blueharvest.utils.UnitConverter /** * Listener for handling changes in unit toggle switch in the accessibility settings screen. * This listener is triggered when the user toggles the switch for units (e.g., metric/imperial). * * @author <NAME> 3/2/2024 * * @param activity The parent AccessibilitySettingsActivity instance. */ class UnitToggleListener(private val activity: AccessibilitySettingsActivity) : CompoundButton.OnCheckedChangeListener { /** * Called when the checked state of a compound button has changed. * * @param buttonView The compound button view whose state has changed. * @param isChecked The new checked state of buttonView. */ override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { // Set SharedPreferences for this activity PreferenceManager.init(activity) // Update the value of unit toggle switch in SharedPreferences PreferenceManager.setSelectedUnit(isChecked) //Convert all data to correct unit here var rakeHeight = PreferenceManager.getRakeHeight() var maxHeightDisplayed = PreferenceManager.getMaxHeightDisplayedInput() var minRakeHeight = PreferenceManager.getMinRakeHeightInput() var optimalHeightRange = PreferenceManager.getOptimalHeightRangeInput() if (isChecked){ rakeHeight = UnitConverter.convertHeightToMetric(rakeHeight)!! maxHeightDisplayed = UnitConverter.convertHeightToMetric(maxHeightDisplayed)!! minRakeHeight = UnitConverter.convertHeightToMetric(minRakeHeight)!! optimalHeightRange = UnitConverter.convertHeightToMetric(optimalHeightRange)!! } else { rakeHeight = UnitConverter.convertHeightToImperial(rakeHeight)!! maxHeightDisplayed = UnitConverter.convertHeightToImperial(maxHeightDisplayed)!! minRakeHeight = UnitConverter.convertHeightToImperial(minRakeHeight)!! optimalHeightRange = UnitConverter.convertHeightToImperial(optimalHeightRange)!! } PreferenceManager.setCurrentHeight(rakeHeight) PreferenceManager.setMaxHeightDisplayedInput(maxHeightDisplayed) PreferenceManager.setMinRakeHeightInput(minRakeHeight) PreferenceManager.setOptimalHeightRangeInput(optimalHeightRange) } }
69
Kotlin
0
0
a7c6739cd4ff084a233a27213c462cdee8615c06
2,585
Mobile-Application
MIT License
modules/android/ui/compose/src/main/kotlin/alakazam/android/ui/compose/Colours.kt
jonapoul
375,762,483
false
null
package alakazam.android.ui.compose import androidx.compose.material.Colors import androidx.compose.runtime.Stable import androidx.compose.ui.graphics.Color @Stable public val Colors.OnSurfaceSecondary: Color get() = if (isLight) Color(0x99000000) else Color(0x99FFFFFF) @Stable public val Colors.OnSurfaceGreen: Color get() = if (isLight) Color(0xFF00B000) else Color(0xFF55FF55) @Stable public val Colors.OnSurfaceYellow: Color get() = if (isLight) Color(0xFFB0B000) else Color(0xFFFFFF55) @Stable public val Colors.OnSurfaceOrange: Color get() = if (isLight) Color(0xFFB06300) else Color(0xFFFF9955) @Stable public val Colors.OnSurfaceRed: Color get() = if (isLight) Color(0xFFB00000) else Color(0xFFFF5555) @Stable public val Colors.OnSurfaceBlue: Color get() = if (isLight) Color(0xFF0063B0) else Color(0xFF5599FF) @Stable public val Colors.SnackbarBackground: Color get() = if (isLight) Color(0xFF575757) else Color(0xFF474747) @Stable public val Colors.OnSnackbarGreen: Color get() = Color(0xFF55FF55) @Stable public val Colors.OnSnackbarBlue: Color get() = Color(0xFF5599FF) @Stable public val Colors.OnSnackbarYellow: Color get() = Color(0xFFFFFF55) @Stable public val Colors.OnSnackbarRed: Color get() = Color(0xFFFF5555) @Stable public val Colors.DialogBackground: Color get() = if (isLight) surface else Color(0xFF343434)
0
null
0
1
20c3c3255f9ac32db71aa04ea6357f0535e98f85
1,347
alakazam
Apache License 2.0
src/test/kotlin/msw/server/core/common/classes.kt
RaphaelTarita
316,530,927
false
null
package msw.server.core.common import com.google.common.net.InetAddresses import java.net.InetAddress import java.time.OffsetDateTime import java.util.UUID import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import msw.server.core.model.OPLevel import msw.server.core.model.adapters.DateSerializer import msw.server.core.model.adapters.IPSerializer import msw.server.core.model.adapters.LevelSerializer import msw.server.core.model.adapters.UUIDSerializer interface ModelMarker @Serializable data class Model01( val s: String = "Hello, World!", val i: Int = 42, val b: Boolean = false ) : ModelMarker @Serializable data class Model02( @Serializable(with = DateSerializer::class) val dateTime: OffsetDateTime = OffsetDateTime.now() .withNano(0), // com.example.core.model.adapters.DateSerializer.kt @Serializable(with = IPSerializer::class) val ip: InetAddress = InetAddresses.forString("127.0.0.1"), // com.example.core.model.adapters.IPSerializer.kt @Serializable(with = LevelSerializer::class) val level: OPLevel = OPLevel.MODERATOR, // com.example.core.model.adapters.LevelSerializer.kt @Serializable(with = UUIDSerializer::class) val uuid: UUID = UUID.randomUUID() // com.example.core.model.adapters.UUIDSerializer.kt ) : ModelMarker @Serializable data class Model03( val s: String = "Hello, World!", val i: Int = 42, val nested1: Model03X01 = Model03X01(), val l: Long = 999999999999999999L, val nested2: Model03X02 = Model03X02() ) : ModelMarker @Serializable data class Model03X01( val stringField: String = "stringField", val doubleField: Double = 3.1415, val byteField: Byte = 2 ) : ModelMarker @Serializable data class Model03X02( @Serializable(with = DateSerializer::class) val dateTime: OffsetDateTime = OffsetDateTime.now().withNano(0).minusDays(1), val int: Int = 100 ) : ModelMarker @Serializable data class Model04( val list: List<Int> = listOf(1, 1, 2, 3, 5, 8, 13, 21, 34), val map: Map<String, Int> = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5), val set: Set<String> = setOf("firstElem", "secondElem", "thirdElem", "fourthElem", "fifthElem"), val string: String = "Hello!" ) : ModelMarker @Serializable data class Model05( val path1: Model05X01 = Model05X01(), val path2: Model05X02 = Model05X02(), val path3: Model05X03 = Model05X03() ) : ModelMarker @Serializable data class Model05X01( val path1: Model05X01X01 = Model05X01X01(), val path2: Model05X01X02 = Model05X01X02(), val endpoint1: String = "Model05 -> path 1 -> endpoint 1" ) : ModelMarker @Serializable data class Model05X02( val path1: Model05X02X01 = Model05X02X01(), val path2: Model05X02X02 = Model05X02X02() ) : ModelMarker @Serializable data class Model05X03( val path1: Model05X03X01 = Model05X03X01(), val path2: Model05X03X02 = Model05X03X02(), val path3: Model05X03X03 = Model05X03X03(), val path4: Model05X03X04 = Model05X03X04(), val endpoint1: String = "Model05 -> path 3 -> endpoint 1", val endpoint2: String = "Model05 -> path 3 -> endpoint 2" ) : ModelMarker @Serializable data class Model05X01X01( val endpoint1: String = "Model05 -> path 1 -> path 1 -> endpoint 1" ) : ModelMarker @Serializable data class Model05X01X02( val endpoint1: String = "Model05 -> path 1 -> path 2 -> endpoint 1", val endpoint2: String = "Model05 -> path 1 -> path 2 -> endpoint 2" ) : ModelMarker @Serializable data class Model05X02X01( val endpoint1: String = "Model05 -> path 2 -> path 1 -> endpoint 1", val endpoint2: String = "Model05 -> path 2 -> path 1 -> endpoint 2", val endpoint3: String = "Model05 -> path 2 -> path 1 -> endpoint 3" ) : ModelMarker @Serializable data class Model05X02X02( val path1: Model05X02X02X01 = Model05X02X02X01(), val path2: Model05X02X02X02 = Model05X02X02X02(), val endpoint1: String = "Model05 -> path 2 -> path 2 -> endpoint 1" ) : ModelMarker @Serializable data class Model05X03X01( val endpoint1: String = "Model05 -> path 3 -> path 1 -> endpoint 1" ) : ModelMarker @Serializable data class Model05X03X02( val endpoint1: String = "Model05 -> path 3 -> path 2 -> endpoint 1", ) : ModelMarker @Serializable data class Model05X03X03( val endpoint1: String = "Model05 -> path 3 -> path 3 -> endpoint 1", val endpoint2: String = "Model05 -> path 3 -> path 3 -> endpoint 2" ) : ModelMarker @Serializable data class Model05X03X04( val endpoint1: String = "Model05 -> path 3 -> path 4 -> endpoint 1" ) : ModelMarker @Serializable data class Model05X02X02X01( val endpoint1: String = "Model05 -> path 2 -> path 2 -> path 1 -> endpoint 1", val endpoint2: String = "Model05 -> path 2 -> path 2 -> path 1 -> endpoint 2" ) : ModelMarker @Serializable data class Model05X02X02X02( val endpoint1: String = "Model05 -> path 2 -> path 2 -> path 2 -> endpoint 1" ) : ModelMarker @Serializable data class Model06( val byte: Byte = 1, val short: Short = 2, val int: Int = 3, val long: Long = 4L, val float: Float = 3.14f, val double: Double = 3.1415, val boolean: Boolean = true, val char: Char = 'x', val string: String = "Hello, World!" ) : ModelMarker @Serializable data class PropertiesEscapeModel( @SerialName("e=e:e e\\e#e!e") val test: Int = 42 ) : ModelMarker
0
null
0
6
adf27aa75901ee7c35bbda724ee36dc43727e0a7
5,424
msw-server
MIT License
http-client/src/main/java/no/nav/familie/http/interceptor/MdcValuesPropagatingClientInterceptor.kt
navikt
202,538,908
false
null
package no.nav.familie.http.interceptor import no.nav.familie.log.IdUtils import no.nav.familie.log.NavHttpHeaders import no.nav.familie.log.mdc.MDCConstants import org.slf4j.MDC import org.springframework.http.HttpRequest import org.springframework.http.client.ClientHttpRequestExecution import org.springframework.http.client.ClientHttpRequestInterceptor import org.springframework.http.client.ClientHttpResponse import org.springframework.stereotype.Component @Component class MdcValuesPropagatingClientInterceptor : ClientHttpRequestInterceptor { override fun intercept(request: HttpRequest, body: ByteArray, execution: ClientHttpRequestExecution): ClientHttpResponse { val callId = MDC.get(MDCConstants.MDC_CALL_ID) ?: IdUtils.generateId() request.headers.add(NavHttpHeaders.NAV_CALL_ID.asString(), callId) return execution.execute(request, body) } }
19
Kotlin
1
2
957e0346ada3cabbc536ec5371b830e1fd69ea74
893
familie-felles
MIT License
app/src/main/kotlin/me/leon/ctf/Ook.kt
Leon406
381,644,086
false
null
package me.leon.ctf private val engine = OokEngine() fun String.ookEncrypt(): String = throw NotImplementedError() fun String.ookDecrypt() = engine.interpret(this.replace("\r\n|\n".toRegex(), " "))
1
Kotlin
80
339
5f7627974e58bd6a00679fd8ce69d8355815eaa2
201
ToolsFx
ISC License
platform/testGuiFramework/src/com/intellij/testGuiFramework/framework/SystemProperties.kt
hieuprogrammer
284,920,751
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.framework /** * An annotation to provide custom system properties for a running instance of IDEA. * It assumed to have a next usage: * @code { * @SystemProperties(arrayOf("key1=value1", "key2=value2")) * SomeGuiTestClass * } */ @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) @kotlin.annotation.Target(AnnotationTarget.CLASS, AnnotationTarget.FILE) annotation class SystemProperties(val keyValueArray: Array<String>)
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
617
intellij-community
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/annotations/prohibitPositionedArgument/tooManyArgs.fir.kt
BradOselo
367,097,840
true
null
// FILE: A.java public @interface A { int a(); double b(); boolean x(); } // FILE: b.kt @A(false, 1.0, false, <!TOO_MANY_ARGUMENTS!>1<!>, <!TOO_MANY_ARGUMENTS!>2<!>) fun foo1() {}
0
null
0
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
193
kotlin
Apache License 2.0
mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/TestImapConnection.kt
thunderbird
1,326,671
false
null
package com.mail.ann.mail.store.imap import java.io.OutputStream import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock internal open class TestImapConnection(val timeout: Long, override val connectionGeneration: Int = 1) : ImapConnection { override val logId: String = "testConnection" override var isConnected: Boolean = false protected set override val outputStream: OutputStream get() = TODO("Not yet implemented") override val isUidPlusCapable: Boolean = true override var isIdleCapable: Boolean = true protected set val defaultSocketReadTimeout = 30 * 1000 var currentSocketReadTimeout = defaultSocketReadTimeout protected set @Volatile private var tag: Int = 0 private val receivedCommands = LinkedBlockingDeque<String>() private val responses = LinkedBlockingDeque<Response>() private val readResponseLock = ReentrantLock() private val readResponseLockCondition = readResponseLock.newCondition() override fun open() { isConnected = true } override fun close() { isConnected = false } override fun hasCapability(capability: String): Boolean { throw UnsupportedOperationException("not implemented") } override fun executeSimpleCommand(command: String): List<ImapResponse> { throw UnsupportedOperationException("not implemented") } override fun executeCommandWithIdSet( commandPrefix: String, commandSuffix: String, ids: Set<Long> ): List<ImapResponse> { throw UnsupportedOperationException("not implemented") } override fun sendCommand(command: String, sensitive: Boolean): String { val tag = ++tag println(">>> $tag $command") receivedCommands.add(command) return tag.toString() } override fun sendContinuation(continuation: String) { println(">>> $continuation") receivedCommands.add(continuation) } override fun readResponse(): ImapResponse { readResponseLock.withLock { readResponseLockCondition.signal() } val imapResponse = when (val response = responses.take()) { is Response.Continuation -> ImapResponseHelper.createImapResponse("+ ${response.text}") is Response.Tagged -> ImapResponseHelper.createImapResponse("$tag ${response.response}") is Response.Untagged -> ImapResponseHelper.createImapResponse("* ${response.response}") is Response.Action -> response.action() } println("<<< $imapResponse") return imapResponse } override fun readResponse(callback: ImapResponseCallback?): ImapResponse { throw UnsupportedOperationException("not implemented") } override fun setSocketDefaultReadTimeout() { currentSocketReadTimeout = defaultSocketReadTimeout } override fun setSocketReadTimeout(timeout: Int) { currentSocketReadTimeout = timeout } fun waitForCommand(command: String) { do { val receivedCommand = receivedCommands.poll(timeout, TimeUnit.SECONDS) ?: throw AssertionError("Timeout") } while (receivedCommand != command) } fun waitForBlockingRead() { readResponseLock.withLock { readResponseLockCondition.await(timeout, TimeUnit.SECONDS) } } fun throwOnRead(block: () -> Nothing) { responses.add(Response.Action(block)) } fun enqueueTaggedServerResponse(response: String) { responses.add(Response.Tagged(response)) } fun enqueueUntaggedServerResponse(response: String) { responses.add(Response.Untagged(response)) } fun enqueueContinuationServerResponse(text: String = "") { responses.add(Response.Continuation(text)) } fun setIdleNotSupported() { isIdleCapable = false } } private sealed class Response { class Tagged(val response: String) : Response() class Untagged(val response: String) : Response() class Continuation(val text: String) : Response() class Action(val action: () -> ImapResponse) : Response() }
846
null
2467
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
4,260
thunderbird-android
Apache License 2.0
app/src/main/java/com/alpriest/energystats/ui/flow/home/SolarPowerFlow.kt
alpriest
606,081,400
false
{"Kotlin": 852801}
package com.alpriest.energystats.ui.flow.home import androidx.compose.foundation.Canvas import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Slider import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.PaintingStyle import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.alpriest.energystats.ui.flow.LineOrientation import com.alpriest.energystats.ui.flow.PowerFlowLinePosition import com.alpriest.energystats.ui.flow.PowerFlowView import com.alpriest.energystats.ui.flow.battery.iconBackgroundColor import com.alpriest.energystats.ui.flow.battery.isDarkMode import com.alpriest.energystats.ui.theme.AppTheme import com.alpriest.energystats.ui.theme.EnergyStatsTheme import com.alpriest.energystats.ui.theme.Sunny import com.alpriest.energystats.ui.theme.preview import kotlinx.coroutines.flow.MutableStateFlow @Composable fun SolarPowerFlow(amount: Double, modifier: Modifier, iconHeight: Dp, themeStream: MutableStateFlow<AppTheme>) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier ) { val glowing: Boolean val sunColor: Color var glowColor: Color = Color.Transparent val orange = Color(0xFFF2A53D) val theme by themeStream.collectAsState() if (amount >= 0.001f && amount < theme.solarRangeDefinitions.threshold1) { glowing = false sunColor = Sunny } else if (amount >= theme.solarRangeDefinitions.threshold1 && amount < theme.solarRangeDefinitions.threshold2) { glowing = true glowColor = Sunny.copy(alpha = 0.4f) sunColor = Sunny } else if (amount >= theme.solarRangeDefinitions.threshold2 && amount < theme.solarRangeDefinitions.threshold3) { glowing = true glowColor = Sunny.copy(alpha = 0.9f) sunColor = orange } else if (amount >= theme.solarRangeDefinitions.threshold3 && amount < 500f) { glowing = true glowColor = orange sunColor = Color.Red } else { glowing = false sunColor = iconBackgroundColor(isDarkMode(themeStream)) glowColor = Color.Transparent } Box( modifier = Modifier .requiredSize(width = iconHeight, height = iconHeight) ) { val paint = remember { Paint().apply { style = PaintingStyle.Stroke strokeWidth = 10f } } val frameworkPaint = remember { paint.asFrameworkPaint() } val transparent = glowColor .copy(alpha = 0f) .toArgb() frameworkPaint.color = transparent frameworkPaint.setShadowLayer( 15f, 0f, 0f, glowColor .toArgb() ) val center = with(LocalDensity.current) { Offset(x = iconHeight.toPx() / 2f, y = (iconHeight.toPx() / 2f)) } Canvas( modifier = Modifier .requiredSize(width = iconHeight, height = iconHeight) .fillMaxSize() ) { if (glowing) { this.drawIntoCanvas { it.drawCircle( center = center, radius = 28f, paint = paint ) for (degrees in 0 until 360 step 45) { val offset = center.minus(Offset(x = 51f, y = 5f)) rotate(degrees = degrees.toFloat()) { it.drawRoundRect( left = offset.x, top = offset.y, right = offset.x + 14f, bottom = offset.y + 8f, paint = paint, radiusX = 8f, radiusY = 8f ) } } } } drawCircle( color = sunColor, center = center, radius = 28f, ) for (degrees in 0 until 360 step 45) { rotate(degrees = degrees.toFloat()) { drawRoundRect( color = sunColor, size = Size(width = 14f, height = 8f), topLeft = center.minus(Offset(x = 51f, y = 5f)), cornerRadius = CornerRadius(x = 8f, y = 8f) ) } } } } Spacer(modifier = Modifier.height(4.dp)) PowerFlowView( amount = amount, themeStream = themeStream, position = PowerFlowLinePosition.NONE, orientation = LineOrientation.VERTICAL ) } } @Preview(showBackground = true, widthDp = 500) @Composable fun SolarPowerFlowViewPreview() { val amount = remember { mutableFloatStateOf(0.0f) } EnergyStatsTheme { Column { SolarPowerFlow( amount = amount.value.toDouble(), modifier = Modifier .width(100.dp) .height(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview().copy(showFinancialSummary = false)) ) Slider( value = amount.value, onValueChange = { amount.value = it }, valueRange = 0.1f..5.0f ) Row( modifier = Modifier .height(300.dp) .wrapContentWidth() ) { SolarPowerFlow( amount = 0.0, modifier = Modifier.width(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview()) ) SolarPowerFlow( amount = 0.5, modifier = Modifier.width(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview()) ) SolarPowerFlow( amount = 1.5, modifier = Modifier.width(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview()) ) SolarPowerFlow( amount = 2.5, modifier = Modifier.width(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview()) ) SolarPowerFlow( amount = 3.5, modifier = Modifier.width(100.dp), iconHeight = 40.dp, themeStream = MutableStateFlow(AppTheme.preview()) ) } } } }
8
Kotlin
3
3
e730e5ec4efc4cd32e0aca8d2fbdb548174ffbb7
8,578
EnergyStats-Android
MIT License
app/src/main/java/com/example/unrepeatability/MainActivity.kt
Samiaza
763,386,216
false
{"Kotlin": 14955}
package com.example.unrepeatability import android.content.Intent import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import java.util.Timer import kotlin.concurrent.timerTask class MainActivity : AppCompatActivity() { private lateinit var startJingle: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { val sharedPreferences = getSharedPreferences("shared_preferences", MODE_PRIVATE) if (!sharedPreferences.contains("highscore_count")) { with(sharedPreferences.edit()) { putInt("highscore_count", 0) apply() } } super.onCreate(savedInstanceState) startJingle = MediaPlayer.create(this, R.raw.game_start) setContentView(R.layout.activity_main) startJingle.start() Timer().schedule(timerTask { startActivity(Intent(this@MainActivity, MenuActivity::class.java)) startJingle.release() finish() }, 2500) } }
0
Kotlin
0
0
1e9cf7f12adebae3f2046647f0eb3a096e388fdf
1,051
Repeat-The-Sequence
MIT License
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/enumEntryJavaEnumReceiver.before.Main.kt
JetBrains
2,489,216
false
null
// "Create enum constant 'A'" "false" // ERROR: Unresolved reference: A internal fun foo(): J.<caret>A = throw Throwable("")
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
124
intellij-community
Apache License 2.0
extension/core/src/main/kotlin/io/holunda/camunda/bpm/data/adapter/basic/ReadWriteAdapterVariableMap.kt
holunda-io
213,882,987
false
null
package io.holunda.camunda.bpm.data.adapter.basic import org.camunda.bpm.engine.variable.VariableMap import java.util.* /** * Read-write adapter for variable map. * * @param [T] type of value. * @param variableMap variable map to access. * @param variableName variable to access. * @param clazz class of variable value. */ class ReadWriteAdapterVariableMap<T : Any?>(private val variableMap: VariableMap, variableName: String, clazz: Class<T>) : AbstractBasicReadWriteAdapter<T>(variableName, clazz) { override fun getOptional(): Optional<T> { @Suppress("UNCHECKED_CAST") return Optional.ofNullable(getOrNull(variableMap[variableName])) as Optional<T> } override fun set(value: T, isTransient: Boolean) { variableMap.putValueTyped(variableName, getTypedValue(value, isTransient)) } override fun getLocalOptional(): Optional<T> { throw UnsupportedOperationException("Can't get a local variable on a variable map") } override fun setLocal(value: T, isTransient: Boolean) { throw UnsupportedOperationException("Can't set a local variable on a variable map") } override fun remove() { variableMap.remove(variableName) } override fun removeLocal() { throw UnsupportedOperationException("Can't set a local variable on a variable map") } }
20
null
6
31
9c3657be2ab4b5c92047aa145557ea66e4d690c5
1,310
camunda-bpm-data
Apache License 2.0
app/src/main/java/com/example/weatherapp/MainActivity.kt
AntonioArquelau
768,745,537
false
{"Kotlin": 28859}
package com.example.weatherapp import android.Manifest import android.content.pm.PackageManager import android.location.LocationManager import android.os.Bundle import android.provider.Settings.Global.getString import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.weatherapp.model.data.WeatherResponse import com.example.weatherapp.ui.theme.MenuTitleText import com.example.weatherapp.ui.theme.MenuValueText import com.example.weatherapp.ui.theme.SubTitleBold import com.example.weatherapp.ui.theme.TempStyle import com.example.weatherapp.ui.theme.TitleBold import com.example.weatherapp.ui.theme.WeatherAppTheme import com.example.weatherapp.utils.DataStatus import com.example.weatherapp.utils.LoadingUtils import com.example.weatherapp.viewmodel.WeatherViewModel import java.text.DecimalFormat import java.text.NumberFormat class MainActivity : ComponentActivity() { companion object { private const val TAG = "MainActivity" } private val viewModel: WeatherViewModel by lazy { WeatherViewModel() } val appId by lazy { getString(R.string.appid) } private lateinit var locationManager: LocationManager private val locationPermissionCode = 2 val formatter: NumberFormat = DecimalFormat("#0.00") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WeatherAppTheme { ShowUI(viewModel){onClickReload()} } } getLocation() } private fun onClickReload(){ if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), locationPermissionCode ) return } val location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) viewModel.getWeatherBasedOnLocation( location?.latitude.toString(), location?.longitude.toString(), appId ) } private fun getLocation() { locationManager = getSystemService(LOCATION_SERVICE) as LocationManager if ((ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), locationPermissionCode ) } else{ val location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) viewModel.getWeatherBasedOnLocation( location?.latitude.toString(), location?.longitude.toString(), appId ) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == locationPermissionCode) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show() if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { return } val location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) viewModel.getWeatherBasedOnLocation(location?.latitude.toString(), location?.longitude.toString(), appId) } else { Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show() } } } } @Composable fun ShowUI(viewModel: WeatherViewModel, onClickReload: () -> Unit){ val dataStatus : DataStatus<WeatherResponse> by viewModel.infoStatus.observeAsState(DataStatus.Loading()) when(dataStatus){ is DataStatus.Success ->{ LoadingUtils.LoadingUI(false) CreateUI(viewModel) } is DataStatus.Error -> { LoadingUtils.LoadingUI(false) ShowErrorScreen { onClickReload } } else -> { LoadingUtils.LoadingUI(true) } } } @Composable fun CreateUI(viewModel: WeatherViewModel) { val mainSummary: String by viewModel.mainSummary.observeAsState("") val city: String by viewModel.city.observeAsState("") val temp: String by viewModel.temp.observeAsState("") val maxTemp: String by viewModel.maxTemp.observeAsState("") val minTemp: String by viewModel.minTemp.observeAsState("") val humidity: String by viewModel.humidity.observeAsState("") val wind: String by viewModel.wind.observeAsState("") val colorId = when(mainSummary){ "Cloud", "Clouds" ->{ R.color.lightBlue } "Rain" ->{ R.color.lightBlue } else -> { R.color.lightOrange } } val iconId = when(mainSummary){ "Cloud", "Clouds" ->{ R.drawable.cloud } "Rain" ->{ R.drawable.rain } else -> { R.drawable.sun } } ConstraintLayout( modifier = Modifier .fillMaxSize() .background(colorResource(id = colorId)) ) { val (row, main, cityRef, tempRef, tempIcon) = createRefs() Text( text = mainSummary, style = TitleBold, modifier = Modifier .padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.main_summary_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.default_dimen) ) .constrainAs(main) { top.linkTo(parent.top) start.linkTo(parent.start) end.linkTo(parent.end) } ) Text( text = city, style = SubTitleBold, modifier = Modifier.constrainAs(cityRef) { top.linkTo(main.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } ) Text( text = "$temp º", style = TempStyle, modifier = Modifier .padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.temp_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.default_dimen), ) .constrainAs(tempRef) { top.linkTo(cityRef.bottom) start.linkTo(parent.start) end.linkTo(parent.end) } ) Image( painter = painterResource(id = iconId), contentDescription = null, modifier = Modifier .padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.main_image_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.default_dimen) ) .height(dimensionResource(id = R.dimen.main_image_size)) .width(dimensionResource(id = R.dimen.main_image_size)) .constrainAs(tempIcon) { top.linkTo(tempRef.bottom) start.linkTo(parent.start) end.linkTo(parent.end) }) Row( modifier = Modifier .fillMaxWidth() .background(colorResource(id = R.color.lightGray)) .padding( dimensionResource(id = R.dimen.bottom_row_padding_start), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.bottom_row_padding_end), dimensionResource(id = R.dimen.default_dimen) ) .constrainAs(row) { bottom.linkTo(parent.bottom) start.linkTo(parent.start) end.linkTo(parent.end) }, horizontalArrangement = Arrangement.SpaceBetween, ) { CreateBottomMenuElements(stringResource(R.string.max), R.drawable.max_temp, "$maxTemp º") CreateBottomMenuElements(stringResource(R.string.min), R.drawable.min_temp, "$minTemp º") CreateBottomMenuElements(stringResource(R.string.wind), R.drawable.wind, "$wind m/s") CreateBottomMenuElements(stringResource(R.string.humidity), R.drawable.humidity, "$humidity %") } } } @Composable fun ShowErrorScreen (onClickReload: () -> Unit){ Box( modifier = Modifier .fillMaxSize() ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .align(Alignment.Center) ) { Image( modifier = Modifier .width(dimensionResource(id = R.dimen.error_image_icon_size)) .height(dimensionResource(id = R.dimen.error_image_icon_size)), painter = painterResource(id = R.drawable.error), contentDescription = null ) Text( modifier = Modifier .padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.error_text_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.error_text_padding_bottom) ), style = MenuValueText, text = stringResource(R.string.error_message) ) } Button( onClick = { onClickReload.invoke() }, modifier = Modifier .fillMaxWidth() .padding( dimensionResource(id = R.dimen.bottom_reload_padding_start), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.bottom_reload_padding_end), dimensionResource(id = R.dimen.bottom_reload_padding_bottom) ) .align(Alignment.BottomCenter) ) { Text(stringResource(R.string.reload)) } } } @Composable fun CreateBottomMenuElements(title: String, icon: Int, value: String) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .width(dimensionResource(id = R.dimen.column_bottom_info_width)) .height(dimensionResource(id = R.dimen.column_bottom_info_height)) ) { Text( modifier = Modifier.padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.label_text_bottom_item_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.label_text_bottom_item_padding_bottom) ), style = MenuTitleText, text = title ) Icon( modifier = Modifier .width(dimensionResource(id = R.dimen.label_icon_bottom_item_size)) .height(dimensionResource(id = R.dimen.label_icon_bottom_item_size)), tint = colorResource(id = R.color.lightBlack), painter = painterResource(id = icon), contentDescription = null ) Text( modifier = Modifier.padding( dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.label_text_bottom_item_padding_top), dimensionResource(id = R.dimen.default_dimen), dimensionResource(id = R.dimen.label_text_bottom_item_padding_bottom) ), style = MenuValueText, text = value ) } }
0
Kotlin
0
0
93e0b2dce58ccf5f3fac4b4074f73f56f407db3a
14,448
WeatherApp
MIT License
shared/src/wasmJsMain/kotlin/com/example/cache/DatabaseDriverFactory.kt
Hieu-Luu
761,312,099
false
{"Kotlin": 21698, "Swift": 594, "HTML": 304}
package com.example.cache actual class DatabaseDriverFactory { }
0
Kotlin
0
0
80b9335218ec4cbc3d35f6f6ae36b1caee16a94a
65
kmp-example
Apache License 2.0
app/src/main/java/com/hackware/mormont/notebook/SettingsActivity.kt
LinDevHard
177,015,303
false
null
package com.hackware.mormont.notebook import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceActivity import android.preference.PreferenceManager import androidx.appcompat.app.AppCompatActivity import android.content.Intent import android.preference.Preference import android.util.Log /* * See [Android Design: Settings](http://developer.android.com/design/patterns/settings.html) * for design guidelines and the [Settings API Guide](http://developer.android.com/guide/topics/ui/settings.html) * for more information on developing a Settings UI. */ class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_custom) initSettingFragment() setupActionBar() } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { supportActionBar?.show() supportActionBar?.setDisplayHomeAsUpEnabled(true) } private fun sendFB() { val email: Intent = Intent(android.content.Intent.ACTION_SEND) email.setType("plain/text") email.putExtra(android.content.Intent.EXTRA_EMAIL, R.string.dev_email) startActivity(Intent.createChooser(email,"Send email")) } private fun initSettingFragment(){ supportFragmentManager .beginTransaction() .add(R.id.fragment_main, SettingsFragment()) .commit() } }
0
Kotlin
0
2
c994ab73ba036097c73bc4f5ca7b2cad544d36e0
1,559
notes_android
MIT License
kotlin-main/src/main/kotlin/io/objectbox/example/Main.kt
objectbox
79,907,973
false
{"Java": 163500, "Kotlin": 72467, "Shell": 79}
/* * Copyright 2022-2024 ObjectBox Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.objectbox.example import io.objectbox.BoxStore import io.objectbox.kotlin.boxFor import io.objectbox.sync.Sync /** * Note: use the run button in IntelliJ IDEA or Android Studio, * or to run with Gradle from a terminal: * * ``` * ./gradlew kotlin-main:run --args="This is my note text." * ``` */ object Main { @JvmStatic fun main(args: Array<String>) { println("Using ObjectBox ${BoxStore.getVersion()} (${BoxStore.getVersionNative()})") println("ObjectBox Sync is " + if (Sync.isAvailable()) "available" else "unavailable") val store = MyObjectBox.builder().name("objectbox-notes-db").build() val box = store.boxFor(Note::class) val text = if (args.size > 0) args.joinToString(" ") else "No text given" box.put(Note(text)) println("${box.count()} notes in ObjectBox database:") for (note in box.all) { println(note) } store.close() } }
2
Java
93
396
8fb98b9adb6f277fec99979296f4ac05e3cbe24f
1,586
objectbox-examples
Apache License 2.0
app/src/main/java/com/itflat/popugweather/PopugiaFragment.kt
iTflatApps
408,177,465
false
{"Kotlin": 34121}
/* * Copyright 2021 iTFlat Apps * * 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.itflat.popugweather import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import kotlinx.android.synthetic.main.fragment_tab.view.* import okhttp3.* import org.json.JSONArray import org.json.JSONObject import java.io.IOException import kotlin.math.roundToInt class PopugiaFragment(private val activity: Activity, private val mContext: Context) : Fragment() { private var adapter:RecyclerViewAdapter?=null private var list= mutableListOf<WeatherModel>() private var fullList= mutableListOf<String>() private var mView:View? = null @SuppressLint("InflateParams") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mView = inflater.inflate(R.layout.fragment_tab, null) mView!!.swipe_refresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.progress_1), ContextCompat.getColor(mContext,R.color.progress_2), ContextCompat.getColor(mContext,R.color.background_accent)) mView!!.city_list.layoutManager = GridLayoutManager(mContext,1) if (adapter == null){ adapter = RecyclerViewAdapter(mContext, Intent(mContext, WeatherActivity::class.java), activity, mutableListOf(), mutableListOf()) } mView!!.city_list.adapter=adapter mView!!.swipe_refresh.isRefreshing = true getWeather("2450022/", "Абрашинск") getWeather("551801/", "Санкт-Попуг") getWeather("796597/","Кешаград") getWeather("2122265/", "Пугск") getWeather("2436704/", "Тамагочинск") getWeather("906057/", "Погрызинск") getWeather("2158433/", "Аркадон") getWeather("721943/", "Гиацинтск") getWeather("638242/", "Черембшовск на Семене") mView!!.swipe_refresh.setOnRefreshListener { // Initialize a new Runnable mView!!.city_list.suppressLayout(true) list.clear() fullList.clear() getWeather("2450022/", "Абрашинск") getWeather("551801/", "Санкт-Попуг") getWeather("796597/","Кешаград") getWeather("2122265/", "Пугск") getWeather("2436704/", "Тамагочинск") getWeather("906057/", "Погрызинск") getWeather("2158433/", "Аркадон") getWeather("721943/", "Гиацинтск") getWeather("638242/", "Черембшовск на Семене") // Execute the task after specified time } return mView!! } private fun getWeather(cityCode:String, cityName:String) { val url = "https://www.metaweather.com/api/location/$cityCode" val okHttpClient = OkHttpClient() val request = Request.Builder() .url(url) .build() okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) {} override fun onResponse(call: Call, response: Response) { if (response.code == 200) { val fullInfo= JSONObject(response.body!!.string()) val info= ((fullInfo.get("consolidated_weather") as JSONArray)[0] as JSONObject) val weather=WeatherModel(cityName, info.get("weather_state_name").toString(), info.get("the_temp").toString().toDouble().roundToInt().toString()) when(weather.cityWeather){ "Snow" -> weather.cityWeather="Снег" "Sleet" -> weather.cityWeather= "Дождь со снегом" "Hail" -> weather.cityWeather= "Град" "Thunderstorm" -> weather.cityWeather= "Гроза" "Heavy Rain" -> weather.cityWeather= "Сильный дождь" "Light Rain" -> weather.cityWeather= "Лёгкий дождь" "Showers" -> weather.cityWeather= "Ливни" "Heavy Cloud" -> weather.cityWeather= "Пасмурно" "Light Cloud" -> weather.cityWeather= "Облачно" "Clear" -> weather.cityWeather= "Солнечно" } activity.runOnUiThread { list.add(weather) fullList.add(fullInfo.toString()) if (list.size == 9){ if (adapter?.weatherList?.isEmpty() == true){ mView!!.swipe_refresh.isRefreshing = false adapter?.weatherList=list adapter?.fullWeatherList=fullList for (i in list.indices){ adapter?.notifyItemInserted(i) } } else{ mView!!.swipe_refresh.isRefreshing = false adapter?.weatherList=list adapter?.fullWeatherList=fullList for (i in list.indices){ adapter?.notifyItemChanged(i) } } mView!!.city_list.suppressLayout(false) } } } } }) } }
0
Kotlin
0
1
967f6d74b2e28752dedd35b8d41321d3e675b1bb
6,257
PopugWeather
Apache License 2.0
layout-inspector/src/com/android/tools/idea/layoutinspector/SkiaParser.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.layoutinspector import com.android.annotations.concurrency.Slow import com.android.repository.Revision import com.android.repository.api.LocalPackage import com.android.repository.api.RepoManager import com.android.repository.api.RepoPackage import com.android.sdklib.repository.AndroidSdkHandler import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.layoutinspector.model.InspectorView import com.android.tools.idea.layoutinspector.proto.SkiaParser import com.android.tools.idea.layoutinspector.proto.SkiaParserServiceGrpc import com.android.tools.idea.protobuf.ByteString import com.android.tools.idea.sdk.AndroidSdks import com.android.tools.idea.sdk.StudioDownloader import com.android.tools.idea.sdk.StudioSettingsController import com.android.tools.idea.sdk.progress.StudioLoggerProgressIndicator import com.android.tools.idea.sdk.wizard.SdkQuickfixUtils import com.google.common.annotations.VisibleForTesting import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.openapi.util.SystemInfo.isWindows import com.intellij.util.net.NetUtils import io.grpc.ManagedChannel import io.grpc.Status import io.grpc.StatusRuntimeException import io.grpc.netty.NettyChannelBuilder import java.awt.Image import java.awt.Point import java.awt.color.ColorSpace import java.awt.image.BufferedImage import java.awt.image.DataBuffer import java.awt.image.DataBufferInt import java.awt.image.DirectColorModel import java.awt.image.Raster import java.awt.image.SinglePixelPackedSampleModel import java.io.File import java.nio.ByteOrder import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import javax.xml.bind.JAXBContext import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement import kotlin.math.max import kotlin.math.min private const val PARSER_PACKAGE_NAME = "skiaparser" private const val INITIAL_DELAY_MILLI_SECONDS = 10L private const val MAX_DELAY_MILLI_SECONDS = 1000L private const val MAX_TIMES_TO_RETRY = 10 class InvalidPictureException : Exception() class UnsupportedPictureVersionException(val version: Int) : Exception() interface SkiaParserService { @Throws(InvalidPictureException::class) fun getViewTree(data: ByteArray, isInterrupted: () -> Boolean = { false }): InspectorView? fun shutdownAll() } // The minimum version of a skia parser component required by this version of studio. // It's the parser's responsibility to be compatible with all supported studio versions. private val minimumRevisions = mapOf( "skiaparser;1" to Revision(1) ) object SkiaParser : SkiaParserService { private val unmarshaller = JAXBContext.newInstance(VersionMap::class.java).createUnmarshaller() private val devbuildServerInfo = ServerInfo(null, -1, -1) private var supportedVersionMap: Map<Int?, ServerInfo>? = null private var latestPackagePath: String? = null private val mapLock = Any() private const val VERSION_MAP_FILE_NAME = "version-map.xml" private val progressIndicator = StudioLoggerProgressIndicator(SkiaParser::class.java) @Slow @Throws(InvalidPictureException::class) override fun getViewTree(data: ByteArray, isInterrupted: () -> Boolean): InspectorView? { val server = runServer(data) ?: throw UnsupportedPictureVersionException(getSkpVersion(data)) val response = server.getViewTree(data) return response?.root?.let { try { buildTree(it, isInterrupted) } catch (interruptedException: InterruptedException) { null } } } @Slow override fun shutdownAll() { supportedVersionMap?.values?.forEach { it.shutdown() } devbuildServerInfo.shutdown() } private fun buildTree(node: SkiaParser.InspectorView, isInterrupted: () -> Boolean): InspectorView? { if (isInterrupted()) { throw InterruptedException() } val width = node.width val height = node.height var image: Image? = null if (!node.image.isEmpty) { val intArray = IntArray(width * height) node.image.asReadOnlyByteBuffer().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(intArray) val buffer = DataBufferInt(intArray, width * height) val model = SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, intArrayOf(0xff0000, 0xff00, 0xff, 0xff000000.toInt())) val raster = Raster.createWritableRaster(model, buffer, Point(0, 0)) val colorModel = DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), 32, 0xff0000, 0xff00, 0xff, 0xff000000.toInt(), false, DataBuffer.TYPE_INT) @Suppress("UndesirableClassUsage") image = BufferedImage(colorModel, raster, false, null) } val res = InspectorView(node.id, node.type, node.x, node.y, width, height, image) node.childrenList.mapNotNull { buildTree(it, isInterrupted) }.forEach { res.addChild(it) } return res } /** * Run a server that can parse the given [data], or null if no appropriate server version is available. */ @Slow private fun runServer(data: ByteArray): ServerInfo? { val server = findServerInfoForSkpVersion(getSkpVersion(data)) ?: return null server.runServer() return server } @VisibleForTesting fun getSkpVersion(data: ByteArray): Int { // SKPs start with "skiapict" in ascii if (data.slice(0..7) != "skiapict".toByteArray(Charsets.US_ASCII).asList() || data.size < 12) { throw InvalidPictureException() } var skpVersion = 0 var mult = 1 // assume little endian for now for (i in 0..3) { skpVersion += data[i + 8] * mult mult = mult shl 8 } return skpVersion } /** * Get the [ServerInfo] for a server that can render SKPs of the given [skpVersion], or null if no valid server is found. */ @VisibleForTesting fun findServerInfoForSkpVersion(skpVersion: Int): ServerInfo? { if (StudioFlags.DYNAMIC_LAYOUT_INSPECTOR_USE_DEVBUILD_SKIA_SERVER.get()) { return devbuildServerInfo } if (supportedVersionMap == null) { readVersionMapping() } var serverInfo = findVersionInMap(skpVersion) // If we didn't find it in the map, maybe we have an old map. Download the latest and look again. if (serverInfo == null) { val latest = getLatestParserPackage(AndroidSdks.getInstance().tryToChooseSdkHandler()) if (latest?.path?.equals(latestPackagePath) != true) { readVersionMapping() serverInfo = findVersionInMap(skpVersion) } if (serverInfo == null && downloadLatestVersion()) { serverInfo = findVersionInMap(skpVersion) } } return serverInfo } private fun findVersionInMap(skpVersion: Int): ServerInfo? { return synchronized(mapLock) { supportedVersionMap?.let { it.values.find { serverInfo -> serverInfo.skpVersionRange.contains(skpVersion) } } } } @Slow private fun downloadLatestVersion(): Boolean { val sdkHandler = AndroidSdks.getInstance().tryToChooseSdkHandler() val sdkManager = sdkHandler.getSdkManager(progressIndicator) // TODO: async and progress sdkManager.loadSynchronously(RepoManager.DEFAULT_EXPIRATION_PERIOD_MS, progressIndicator, StudioDownloader(), StudioSettingsController.getInstance()) val latestRemote = sdkHandler.getLatestRemotePackageForPrefix( PARSER_PACKAGE_NAME, null, true, progressIndicator) ?: return false val maybeNewPackage = latestRemote.path val updatablePackage = sdkManager.packages.consolidatedPkgs[maybeNewPackage] ?: return false if (updatablePackage.hasLocal() && !updatablePackage.isUpdate) { // latest already installed return false } val installResult = CompletableFuture<Boolean>() ApplicationManager.getApplication().invokeAndWait { // TODO: probably don't show dialog ever? SdkQuickfixUtils.createDialogForPackages(null, listOf(updatablePackage), listOf(), false)?.show() val newPackage = sdkManager.packages.consolidatedPkgs[maybeNewPackage] if (newPackage == null || !newPackage.hasLocal() || newPackage.isUpdate) { // update cancelled? installResult.complete(false) } readVersionMapping() installResult.complete(true) } return installResult.get() && supportedVersionMap != null } private fun readVersionMapping() { val sdkHandler = AndroidSdks.getInstance().tryToChooseSdkHandler() val latestPackage = getLatestParserPackage(sdkHandler) if (latestPackage != null) { val mappingFile = File(latestPackage.location, VERSION_MAP_FILE_NAME) try { val mapInputStream = sdkHandler.fileOp.newFileInputStream(mappingFile) val map = unmarshaller.unmarshal(mapInputStream) as VersionMap synchronized(mapLock) { val newMap = mutableMapOf<Int?, ServerInfo>() for (spec in map.servers) { val existing = supportedVersionMap?.get(spec.version) if (existing?.skpVersionRange?.start == spec.skpStart && existing.skpVersionRange.last == spec.skpEnd) { newMap[spec.version] = existing } else { newMap[spec.version] = ServerInfo(spec.version, spec.skpStart, spec.skpEnd) } } supportedVersionMap = newMap latestPackagePath = latestPackage.path } } catch (e: Exception) { Logger.getInstance(SkiaParser::class.java).warn("Failed to parse mapping file", e) } } } private fun getLatestParserPackage(sdkHandler: AndroidSdkHandler): LocalPackage? { return sdkHandler.getLatestLocalPackageForPrefix(PARSER_PACKAGE_NAME, { true }, true, progressIndicator) } } /** * Metadata for a skia parser server version. May or may not correspond to a server on disk, but has the capability to download it if not. * If [serverVersion] is null, corresponds to the locally-built1 server (in a dev build). */ @VisibleForTesting class ServerInfo(val serverVersion: Int?, skpStart: Int, skpEnd: Int?) { private val serverName = "skia-grpc-server" + if (isWindows) ".exe" else "" val skpVersionRange: IntRange = IntRange(skpStart, skpEnd ?: Int.MAX_VALUE) var client: SkiaParserServiceGrpc.SkiaParserServiceBlockingStub? = null var channel: ManagedChannel? = null var handler: OSProcessHandler? = null private val progressIndicator = StudioLoggerProgressIndicator(ServerInfo::class.java) private val packagePath = "${PARSER_PACKAGE_NAME}${RepoPackage.PATH_SEPARATOR}$serverVersion" private val serverPath: File? = findPath() private fun findPath(): File? { return if (serverVersion == null) { // devbuild File(PathManager.getHomePath(), "../../bazel-bin/tools/base/dynamic-layout-inspector/${serverName}") } else { val sdkHandler = AndroidSdks.getInstance().tryToChooseSdkHandler() var serverPackage = sdkHandler.getLocalPackage(packagePath, progressIndicator) ?: return null // If the path isn't in the map at all, it's newer than this version of studio. if (minimumRevisions.getOrDefault(serverPackage.path, Revision(0)) > serverPackage.version) { // Current version is too old, try to update val updatablePackage = sdkHandler.getSdkManager(progressIndicator).packages.consolidatedPkgs[packagePath] ?: return null if (updatablePackage.isUpdate) { SdkQuickfixUtils.createDialogForPackages(null, listOf(updatablePackage), listOf(), false)?.show() } serverPackage = sdkHandler.getLocalPackage(packagePath, progressIndicator) ?: return null // we didn't update successfully if (minimumRevisions.getOrDefault(serverPackage.path, Revision(0)) > serverPackage.version) { return null } } File(serverPackage.location, serverName) } } /** * Start the server if it isn't already running. * * If the server is killed by another process we detect it with process.isAlive. * Note that this will be a sub process of Android Studio and will terminate when * Android Studio process is terminated. */ @Slow fun runServer() { if (client != null && channel?.isShutdown != true && channel?.isTerminated != true && handler?.process?.isAlive == true) { // already started return } if (serverPath?.exists() != true && !tryDownload()) { throw Exception("Unable to find server version $serverVersion") } val realPath = serverPath ?: throw Exception("Unable to find server version $serverVersion") // TODO: actually find and (re-)launch the server, and reconnect here if necessary. val localPort = NetUtils.findAvailableSocketPort() if (localPort < 0) { throw Exception("Unable to find available socket port") } channel = NettyChannelBuilder .forAddress("localhost", localPort) .usePlaintext() .maxInboundMessageSize(512 * 1024 * 1024 - 1) .build() client = SkiaParserServiceGrpc.newBlockingStub(channel) handler = OSProcessHandler.Silent(GeneralCommandLine(realPath.absolutePath, localPort.toString())) handler!!.addProcessListener(object : ProcessAdapter() { override fun processTerminated(event: ProcessEvent) { // TODO(b/151639359) // We get a 137 when we terminate the server. Silence this error. if (event.exitCode != 0 && event.exitCode != 137) { Logger.getInstance(SkiaParser::class.java).error("SkiaServer terminated exitCode: ${event.exitCode} text: ${event.text}") } else { Logger.getInstance(SkiaParser::class.java).info("SkiaServer terminated successfully") } } override fun processWillTerminate(event: ProcessEvent, willBeDestroyed: Boolean) { Logger.getInstance(SkiaParser::class.java).debug("SkiaServer willTerminate") } override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { Logger.getInstance(SkiaParser::class.java).info("SkiaServer Message: ${event.text}") } }) handler?.startNotify() } @Slow fun shutdown() { channel?.shutdownNow() channel?.awaitTermination(1, TimeUnit.SECONDS) channel = null client = null handler?.destroyProcess() handler = null } @Slow private fun tryDownload(): Boolean { if (serverVersion == null) { // devbuild, can't download return false } val sdkHandler = AndroidSdks.getInstance().tryToChooseSdkHandler() val sdkManager = sdkHandler.getSdkManager(progressIndicator) // TODO: async and progress sdkManager.loadSynchronously(RepoManager.DEFAULT_EXPIRATION_PERIOD_MS, progressIndicator, StudioDownloader(), StudioSettingsController.getInstance()) val updatablePackage = sdkManager.packages.consolidatedPkgs[packagePath] ?: return false if (updatablePackage.hasLocal() && !updatablePackage.isUpdate) { // latest already installed return false } SdkQuickfixUtils.createDialogForPackages(null, listOf(updatablePackage), listOf(), false)?.show() ?: return false // TODO: needed? sdkManager.reloadLocalIfNeeded(progressIndicator) val newPackage = sdkManager.packages.consolidatedPkgs[packagePath] ?: return false return newPackage.hasLocal() && !newPackage.isUpdate } @Slow fun getViewTree(data: ByteArray): SkiaParser.GetViewTreeResponse? { ping() return getViewTreeImpl(data) } // TODO: add ping functionality to the server? @Slow fun ping() { getViewTreeImpl(ByteArray(1)) } private fun getViewTreeImpl(data: ByteArray): SkiaParser.GetViewTreeResponse? { val request = SkiaParser.GetViewTreeRequest.newBuilder().setSkp(ByteString.copyFrom(data)).build() return getViewTreeWithRetry(request) } private fun getViewTreeWithRetry(request: SkiaParser.GetViewTreeRequest): SkiaParser.GetViewTreeResponse? { var tries = 0 var delay = INITIAL_DELAY_MILLI_SECONDS var lastException: StatusRuntimeException? = null while (tries < MAX_TIMES_TO_RETRY) { try { return client?.getViewTree(request) } catch (ex: StatusRuntimeException) { if (ex.status.code != Status.Code.UNAVAILABLE) { throw ex } Thread.sleep(delay) tries++ delay = min(2 * delay, MAX_DELAY_MILLI_SECONDS) lastException = ex } } throw lastException!! } } @XmlRootElement(name="versionMapping") private class VersionMap { @XmlElement(name = "server") val servers: MutableList<ServerVersionSpec> = mutableListOf() } private class ServerVersionSpec { @XmlAttribute(name = "version", required = true) val version: Int = 0 @XmlAttribute(name = "skpStart", required = true) val skpStart: Int = 0 @XmlAttribute(name = "skpEnd", required = false) val skpEnd: Int? = null }
0
null
187
751
16d17317f2c44ec46e8cd2180faf9c349d381a06
17,938
android
Apache License 2.0
src/test/java/assignmentTests/optionalTests/KotlinCoroutineLocalCrawlTest.kt
americanstone
417,626,723
false
null
package assignmentTests.optionalTests import admin.CrawlTest import edu.vanderbilt.imagecrawler.crawlers.CrawlerType import org.junit.Ignore import org.junit.Test /** * OPTIONAL test for this assignment. */ @Ignore class KotlinCoroutineLocalCrawlTest { @Test fun optionalTest() { CrawlTest.localCrawlTest(CrawlerType.KOTLIN_COROUTINES) } }
1
null
1
1
2ac7bf09376a9fa6104963c67ece65e7f2b9912e
364
image-crawler
MIT License
model/src/androidMain/kotlin/tech/skot/model/Encoding.kt
skot-framework
235,318,194
false
null
package tech.skot.model import android.util.Base64 import java.security.MessageDigest import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec actual fun decodeBase64(str: String): String { return String(Base64.decode(str, Base64.URL_SAFE)) } actual fun encodeBase64(str: String) = Base64.encodeToString(str.toByteArray(), Base64.NO_WRAP or Base64.URL_SAFE) actual fun hashSHA256(str: String) = hashString("SHA-256", str) private fun hashString(type: String, input: String): String { val HEX_CHARS = "0123456789ABCDEF" val bytes = MessageDigest .getInstance(type) .digest(input.toByteArray()) val result = StringBuilder(bytes.size * 2) bytes.forEach { val i = it.toInt() result.append(HEX_CHARS[i shr 4 and 0x0f]) result.append(HEX_CHARS[i and 0x0f]) } return result.toString() } actual fun aes128encrypt(textToEncrypt: String, secret: String, initializationVector: String): String { val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") val keySpec = SecretKeySpec(secret.toByteArray().copyOf(32), "AES") val ivSpec = IvParameterSpec(initializationVector.toByteArray()) cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec) return Base64.encodeToString(cipher.doFinal(textToEncrypt.toByteArray()), Base64.NO_WRAP) }
1
Kotlin
4
5
44ddb5bd14313e81ff3abff97d7e6b1242e9f3c5
1,370
skot
Apache License 2.0
kotlin-native/backend.native/tests/samples/globalState/src/globalStateMain/kotlin/Global.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package sample.globalstate import kotlin.native.concurrent.* import kotlinx.cinterop.* import platform.posix.* inline fun Int.ensureUnixCallResult(op: String, predicate: (Int) -> Boolean = { x -> x == 0} ): Int { if (!predicate(this)) { throw Error("$op: ${strerror(posix_errno())!!.toKString()}") } return this } data class SharedDataMember(val double: Double) data class SharedData(val string: String, val int: Int, val member: SharedDataMember) // Here we access the same shared Kotlin object from multiple threads. val globalObject: SharedData? get() = sharedData.kotlinObject?.asStableRef<SharedData>()?.get() fun dumpShared(prefix: String) { println(""" $prefix: ${pthread_self()} x=${sharedData.x} f=${sharedData.f} s=${sharedData.string!!.toKString()} """.trimIndent()) } fun main() { // Arena owning all native allocs. val arena = Arena() // Assign global data. sharedData.x = 239 sharedData.f = 0.5f sharedData.string = "Hello Kotlin!".cstr.getPointer(arena) // Here we create shared object reference, val stableRef = StableRef.create(SharedData("Shared", 239, SharedDataMember(2.71))) sharedData.kotlinObject = stableRef.asCPointer() dumpShared("thread1") println("shared is $globalObject") // Start a new thread, that sees the variable. // memScoped is needed to pass thread's local address to pthread_create(). memScoped { val thread = alloc<pthread_tVar>() pthread_create(thread.ptr, null, staticCFunction { argC -> initRuntimeIfNeeded() dumpShared("thread2") val arg = argC!!.asStableRef<SharedDataMember>() println("thread arg is ${arg.get()} shared is $globalObject") arg.dispose() // Workaround for compiler issue. null as COpaquePointer? }, StableRef.create(SharedDataMember(3.14)).asCPointer() ).ensureUnixCallResult("pthread_create") pthread_join(thread.value, null).ensureUnixCallResult("pthread_join") } // At this moment we do not need data stored in shared data, so clean up the data // and free memory. sharedData.string = null stableRef.dispose() arena.clear() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,413
kotlin
Apache License 2.0
sample-library/src/main/java/com/xfinity/blueprint_sample_library/mvp/view/StaticScreenView.kt
Comcast
103,149,221
false
{"Gradle": 10, "XML": 68, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Kotlin": 132, "Proguard": 6, "Java": 3}
/* * * * Copyright 2018 Comcast Cable Communications Management, LLC * * 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.xfinity.blueprint.bootstrap.component.model import com.xfinity.blueprint.model.ComponentModel data class SimpleTextModel(val text: CharSequence) : ComponentModel
14
Kotlin
15
21
47835a4e0138d4dd267677b0b264c9778884e7c9
818
blueprint
Apache License 2.0
mbmobilesdk/src/main/java/com/daimler/mbmobilesdk/preferences/mbmobilesdk/SharedMBMobileSDKPreferences.kt
Daimler
199,815,262
false
null
package com.daimler.mbmobilesdk.preferences.mbmobilesdk import android.content.Context import android.content.SharedPreferences import com.daimler.mbcommonkit.extensions.getMultiAppSharedPreferences import com.daimler.mbcommonkit.utils.preferencesForSharedUserId import com.daimler.mbmobilesdk.preferences.PreferencesInitializable internal class SharedMBMobileSDKPreferences( context: Context, sharedUserId: String ) : BaseMBMobileSDKPreferences(), PreferencesInitializable { override val prefs: SharedPreferences = context.getMultiAppSharedPreferences(MULTI_APP_PREFERENCES_NAME, sharedUserId) init { initialize(context, sharedUserId, MULTI_APP_PREFERENCES_NAME) } override fun arePreferencesInitialized(preferences: SharedPreferences): Boolean = !preferences.getString(KEY_DEVICE_ID, null).isNullOrBlank() override fun needsInitialization(): Boolean = deviceId.get().isBlank() override fun copyFromPreferences(preferences: SharedPreferences) { // copy device id val tmpDeviceId = preferences.getString(KEY_DEVICE_ID, "").orEmpty() deviceId.set(tmpDeviceId) } override fun onNoInitializedPreferencesFound() { deviceId.set(generateDeviceId()) } private companion object { private const val MULTI_APP_PREFERENCES_NAME = "mb.mobile.sdk.settings.shared" } } private fun PreferencesInitializable.initialize(context: Context, sharedUserId: String, settingsName: String) { if (needsInitialization()) { val prefs = preferencesForSharedUserId(context, settingsName, sharedUserId) prefs.firstOrNull { arePreferencesInitialized(it) } ?.let { copyFromPreferences(it) } ?: onNoInitializedPreferencesFound() } }
1
Kotlin
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
1,802
MBSDK-Mobile-Android
MIT License
lib_base/src/main/java/com/hzsoft/lib/base/widget/NetErrorView.kt
zhouhuandev
346,678,456
false
null
package com.lib.base.widget import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.RelativeLayout import androidx.annotation.ColorRes import com.lib.base.R class NetErrorView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) { private var mOnClickListener: View.OnClickListener? = null private val mRlNetWorkError: RelativeLayout init { View.inflate(context, R.layout.view_net_error, this) findViewById<View>(R.id.btn_net_refresh).setOnClickListener { v -> if (mOnClickListener != null) { mOnClickListener!!.onClick(v) } } mRlNetWorkError = findViewById(R.id.rl_net_error_root) } fun setRefreshBtnClickListener(listener: View.OnClickListener) { mOnClickListener = listener } fun setNetErrorBackground(@ColorRes colorResId: Int) { mRlNetWorkError.setBackgroundColor(resources.getColor(colorResId)) } }
0
null
53
88
c74e9e5e1059805e4373981633e17616a2328948
1,004
BaseDemo
Apache License 2.0
src/test/kotlin/handlers/events/TimestampGeneratorTest.kt
th2-net
313,911,661
false
{"Kotlin": 448754, "Dockerfile": 330, "Shell": 190}
/* * Copyright 2022-2024 Exactpro (Exactpro Systems Limited) * * 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 handlers.events import com.exactpro.cradle.BookId import com.exactpro.cradle.TimeRelation import com.exactpro.cradle.testevents.StoredTestEvent import com.exactpro.cradle.testevents.StoredTestEventId import com.exactpro.th2.rptdataprovider.* import com.exactpro.th2.rptdataprovider.entities.filters.FilterPredicate import com.exactpro.th2.rptdataprovider.entities.internal.ProviderEventId import com.exactpro.th2.rptdataprovider.entities.requests.SseEventSearchRequest import com.exactpro.th2.rptdataprovider.handlers.events.SearchInterval import com.exactpro.th2.rptdataprovider.handlers.events.TimeIntervalGenerator import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.time.Instant import java.time.temporal.ChronoUnit @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TimestampGeneratorTest { private val startTimestamp = Instant.parse("2022-04-21T12:00:00Z") private val endTimestamp = Instant.parse("2022-04-21T23:00:00Z") private val bookId = BookId("testBook") private val scope = "testScope" private val eventId = StoredTestEventId(bookId, scope, startTimestamp, "id") private val providerEventIdSingle = ProviderEventId(null, eventId) private fun getSearchRequest( startTimestamp: Instant?, endTimestamp: Instant?, searchDirection: TimeRelation = TimeRelation.AFTER, resumeId: ProviderEventId? = null ): SseEventSearchRequest { val parameters = mutableMapOf<String, List<String>>() if (startTimestamp != null) { parameters["startTimestamp"] = listOf(startTimestamp.toEpochMilli().toString()) } if (endTimestamp != null) { parameters["endTimestamp"] = listOf(endTimestamp.toEpochMilli().toString()) } if (resumeId != null) { parameters["resumeFromId"] = listOf(resumeId.toString()) } parameters["bookId"] = listOf(bookId.toString()) parameters["scope"] = listOf(scope) return SseEventSearchRequest(parameters, FilterPredicate(emptyList())) .copy(searchDirection = searchDirection) .also { it.checkRequest() } } private fun mockEvent(startTimestamp: Instant, resumeId: ProviderEventId): StoredTestEvent { val event: StoredTestEvent = mockk() every { event.startTimestamp } answers { startTimestamp } every { event.id } answers { resumeId.eventId } return event } @Test fun testTimestampInOneDay() { val request = getSearchRequest(startTimestamp, endTimestamp) val generator = TimeIntervalGenerator(request, null, null) val result = generator.toList() Assertions.assertEquals( listOf( SearchInterval( startInterval = startTimestamp, endInterval = endTimestamp, startRequest = startTimestamp, endRequest = endTimestamp, providerResumeId = null ) ), result ) } @Test fun testTimestampInOneDayReverse() { val request = getSearchRequest(endTimestamp, startTimestamp, TimeRelation.BEFORE) val generator = TimeIntervalGenerator(request, null, null) val result = generator.toList() Assertions.assertEquals( listOf( SearchInterval( startInterval = startTimestamp, endInterval = endTimestamp, startRequest = endTimestamp, endRequest = startTimestamp, providerResumeId = null ) ), result ) } @Test fun testTimestampInDifferentDays() { val startPlusOneDay = startTimestamp.plus(1, ChronoUnit.DAYS) val request = getSearchRequest(startTimestamp, startPlusOneDay) val generator = TimeIntervalGenerator(request, null, null) val result = generator.toList() val startNextDay = getDayStart(startPlusOneDay) Assertions.assertEquals( listOf( SearchInterval( startInterval = startTimestamp, endInterval = startNextDay.minusNanos(1).toInstant(), startRequest = startTimestamp, endRequest = startPlusOneDay, providerResumeId = null ), SearchInterval( startInterval = startNextDay.toInstant(), endInterval = startPlusOneDay, startRequest = startTimestamp, endRequest = startPlusOneDay, providerResumeId = null ) ), result ) } @Test fun testTimestampInDifferentDaysReverse() { val startMinusOneDay = startTimestamp.minus(1, ChronoUnit.DAYS) val request = getSearchRequest(startTimestamp, startMinusOneDay, TimeRelation.BEFORE) val generator = TimeIntervalGenerator(request, null, null) val result = generator.toList() val startNextDay = getDayStart(startTimestamp) Assertions.assertEquals( listOf( SearchInterval( startInterval = startNextDay.toInstant(), endInterval = startTimestamp, startRequest = startTimestamp, endRequest = startMinusOneDay, providerResumeId = null ), SearchInterval( startInterval = startMinusOneDay, endInterval = startNextDay.minusNanos(1).toInstant(), startRequest = startTimestamp, endRequest = startMinusOneDay, providerResumeId = null ) ), result ) } @Test fun testResumeIdSingleInOneDay() { val request = getSearchRequest(startTimestamp, endTimestamp, resumeId = providerEventIdSingle) val eventStart = startTimestamp.plusSeconds(10) val event = mockEvent(eventStart, providerEventIdSingle) val generator = TimeIntervalGenerator(request, providerEventIdSingle, event) val result = generator.toList() Assertions.assertEquals( listOf( SearchInterval( startInterval = eventStart, endInterval = endTimestamp, startRequest = startTimestamp, endRequest = endTimestamp, providerResumeId = providerEventIdSingle ) ), result ) } @Test fun testResumeIdSingleInTwoDays() { val startPlusOneDay = startTimestamp.plus(1, ChronoUnit.DAYS) val request = getSearchRequest(null, startPlusOneDay, resumeId = providerEventIdSingle) val eventStart = startTimestamp.plusSeconds(10) val event = mockEvent(eventStart, providerEventIdSingle) val generator = TimeIntervalGenerator(request, providerEventIdSingle, event) val result = generator.toList() val startNextDay = getDayStart(startPlusOneDay) Assertions.assertEquals( listOf( SearchInterval( startInterval = eventStart, endInterval = startNextDay.minusNanos(1).toInstant(), startRequest = eventStart, endRequest = startPlusOneDay, providerResumeId = providerEventIdSingle ), SearchInterval( startInterval = startNextDay.toInstant(), endInterval = startPlusOneDay, startRequest = eventStart, endRequest = startPlusOneDay, providerResumeId = null ) ), result ) } }
3
Kotlin
2
4
e9e34e7edafcab204ba783a18ddf420337709db5
8,419
th2-rpt-data-provider
Apache License 2.0
org.librarysimplified.audiobook.tests/src/test/java/org/librarysimplified/audiobook/tests/LicenseStatusParserTest.kt
ThePalaceProject
379,956,255
false
{"Kotlin": 695923, "Java": 2392}
package org.librarysimplified.audiobook.tests import org.librarysimplified.audiobook.lcp.license_status.LicenseStatusParserProviderType import org.librarysimplified.audiobook.lcp.license_status.LicenseStatusParsers class LicenseStatusParserTest : LicenseStatusParserContract() { override fun parsers(): LicenseStatusParserProviderType { return LicenseStatusParsers } }
1
Kotlin
1
1
e876ad5481897b14c37c0969997dcce0807fac33
379
android-audiobook
Apache License 2.0
core-mvp-binding/src/main/java/ru/surfstudio/android/core/mvp/binding/rx/loadable/data/EmptyErrorException.kt
eltray
200,101,552
true
{"Kotlin": 1787549, "Java": 826942, "FreeMarker": 54338, "Groovy": 8823, "C++": 1542, "CMake": 285}
package ru.surfstudio.android.core.mvp.binding.rx.loadable.data import java.lang.Exception /** * Пустая ошибка. * Используется, если запрос вернул положительный результат, и предыдущий errorState необходимо очистить. */ class EmptyErrorException : Exception()
0
Kotlin
0
0
69d435621d90954102af7424b4b309213d9bc95d
264
SurfAndroidStandard
Apache License 2.0
kotest-extensions-testcontainers-kafka/src/main/kotlin/io/kotest/extensions/testcontainers/kafka/KafkaContainerExtension.kt
kotest
361,198,041
false
null
package io.kotest.extensions.testcontainers.kafka import io.kotest.core.extensions.MountableExtension import io.kotest.core.listeners.AfterProjectListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.apache.kafka.clients.CommonClientConfigs import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.serialization.BytesDeserializer import org.apache.kafka.common.serialization.BytesSerializer import org.apache.kafka.common.utils.Bytes import org.testcontainers.containers.KafkaContainer import org.testcontainers.utility.DockerImageName import java.util.Properties class KafkaContainerExtension( private val container: KafkaContainer, ) : AfterProjectListener, MountableExtension<KafkaContainer, KafkaContainer> { constructor() : this(KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"))) override suspend fun afterProject() { if (container.isRunning) withContext(Dispatchers.IO) { container.stop() } } override fun mount(configure: KafkaContainer.() -> Unit): KafkaContainer { container.configure() container.start() return container } } fun KafkaContainer.producer(): KafkaProducer<Bytes, Bytes> { val props = Properties() props[CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = BytesSerializer::class.java props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = BytesSerializer::class.java return KafkaProducer<Bytes, Bytes>(props) } fun KafkaContainer.consumer(consumerGroupId: String? = null): KafkaConsumer<Bytes, Bytes> { val props = Properties() props[CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers props[ConsumerConfig.GROUP_ID_CONFIG] = consumerGroupId ?: ("kotest_consumer_" + System.currentTimeMillis()) props[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = "earliest" props[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = BytesDeserializer::class.java props[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = BytesDeserializer::class.java return KafkaConsumer<Bytes, Bytes>(props) }
1
Kotlin
3
14
333d48d9d210520c8279e000bbbfb447344f5ee1
2,315
kotest-extensions-testcontainers
Apache License 2.0
app/src/main/java/com/example/cameramotiondetector/ExtendedImageView.kt
AmirrezaNasiri
731,762,698
false
{"Kotlin": 15386, "CMake": 1926, "C++": 262}
package com.example.cameramotiondetector import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView class ExtendedImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : AppCompatImageView(context, attrs) { public var boxes = arrayOf<Array<Int>>() override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) boxes.forEach { val paint = Paint() paint.color = Color.RED paint.alpha = 50 paint.strokeWidth = 3f canvas!!.drawRect(it[0].toFloat(), it[1].toFloat(), it[2].toFloat(), it[3].toFloat(), paint) } } }
0
Kotlin
0
2
9bab5fdfe614823cfe3f7d3aa52ccc427a3423ec
790
camera-motion-detector
Apache License 2.0
system-extension/src/main/java/com/highcapable/betterandroid/system/extension/component/BroadcastFactory.kt
BetterAndroid
708,020,230
false
{"Kotlin": 369902, "Java": 6779}
/* * Better Android - Create more useful tool extensions for Android. * Copyright (C) 2019-2023 HighCapable * https://github.com/BetterAndroid/BetterAndroid * * Apache License Version 2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is created by fankes on 2023/10/27. */ @file:Suppress("unused", "InlinedApi", "UnspecifiedRegisterReceiverFlag") @file:JvmName("BroadcastUtils") package com.highcapable.betterandroid.system.extension.component import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import com.highcapable.betterandroid.system.extension.tool.SystemVersion /** * Register a broadcast receiver. * * Usage: * * ```kotlin * val filter = IntentFilter().apply { * addAction("com.example.app.action.KNOCK") * } * registerReceiver(filter) { context, intent -> * val greetings = intent.getStringExtra("greetings") * context.toast(greetings) * } * ``` * @receiver the current context. * @param filter the [IntentFilter]. * @param flags the flags, default is [Context.RECEIVER_EXPORTED]. * @param onReceive callback the receiver event function body. */ fun Context.registerReceiver(filter: IntentFilter, flags: Int? = null, onReceive: (context: Context, intent: Intent) -> Unit) { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (context == null || intent == null) return onReceive(context, intent) } } val receiverFlags = flags ?: Context.RECEIVER_EXPORTED if (SystemVersion.isHighAndEqualsTo(SystemVersion.T)) registerReceiver(receiver, filter, receiverFlags) else registerReceiver(receiver, filter) } /** * Send a broadcast. * * Usage: * * ```kotlin * // Send a broadcast to "com.example.app". * sendBroadcast("com.example.app", "com.example.app.action.KNOCK") { * putExtra("greetings", "Hey you!") * } * // If you don't want to specific a package name. * sendBroadcast(action = arrayOf("com.example.app.action.KNOCK")) { * putExtra("greetings", "Hey there!") * } * ``` * @receiver the current context. * @param packageName the receiverd app's package name, default is empty. * @param action the actions you want to send, default is empty. * @param initiate the [Intent] builder body. */ fun Context.sendBroadcast(packageName: String = "", vararg action: String, initiate: Intent.() -> Unit = {}) = sendBroadcast(Intent().apply { if (packageName.isNotBlank()) setPackage(packageName) action.forEach { setAction(it) } }.apply(initiate))
0
Kotlin
0
22
ad00888146552a96ba0d72ab5ee1fdc3786513bf
3,176
BetterAndroid
Apache License 2.0
app/src/main/java/org/stepik/android/domain/onboarding/analytic/OnboardingClosedAnalyticEvent.kt
StepicOrg
42,045,161
false
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
package org.stepik.android.domain.onboarding.analytic import org.stepik.android.domain.base.analytic.AnalyticEvent class OnboardingClosedAnalyticEvent( screen: Int ) : AnalyticEvent { companion object { private const val PARAM_SCREEN = "screen" } override val name: String = "Onboarding closed" override val params: Map<String, Any> = mapOf(PARAM_SCREEN to screen) }
13
Kotlin
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
414
stepik-android
Apache License 2.0
local/local/src/main/java/com/nimbusframework/nimbuslocal/deployment/services/StageService.kt
thomasjallerton
163,180,980
false
{"YAML": 3, "Ignore List": 2, "XML": 4, "Maven POM": 9, "Dockerfile": 1, "Text": 1, "Markdown": 35, "Kotlin": 570, "Java": 167, "JSON": 2, "JavaScript": 4, "SVG": 4, "CSS": 1}
package com.nimbusframework.nimbuslocal.deployment.services class StageService( val deployingStage: String, private val deployingDefaultStage: Boolean, private val allowedOrigin: Map<String, String>, private val allowedHeaders: Map<String, List<String>> ) { fun <T> isResourceDeployedInStage(annotations: Array<T>, getStages: (T) -> Array<String>): Boolean { for (annotation in annotations) { val stages = getStages(annotation) if (stages.contains(deployingStage) || (stages.isEmpty() && deployingDefaultStage)) { return true } } return false } fun <T> annotationForStage(annotations: Array<T>, getStages: (T) -> Array<String>): T? { for (annotation in annotations) { val stages = getStages(annotation) if (stages.contains(deployingStage) || (stages.isEmpty() && deployingDefaultStage)) { return annotation } } return null } fun getDefaultAllowedOrigin(): String { return allowedOrigin[deployingStage] ?: "" } fun getDefaultAllowedHeaders(): Array<String> { return allowedHeaders[deployingStage]?.toTypedArray() ?: arrayOf() } }
6
Kotlin
5
39
5c3325caaf3fe9de9ffad130fd1e773c6f680e89
1,267
nimbus-framework
MIT License
app/src/main/java/com/niyaj/popos/features/customer/presentation/settings/export_customer/ExportCustomerScreen.kt
skniyajali
579,613,644
false
null
package com.niyaj.popos.features.customer.presentation.settings.export_customer import android.Manifest import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Upload import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.niyaj.popos.R import com.niyaj.popos.features.common.ui.theme.SpaceSmall import com.niyaj.popos.features.common.util.ImportExport import com.niyaj.popos.features.common.util.ImportExport.writeData import com.niyaj.popos.features.common.util.UiEvent import com.niyaj.popos.features.components.ExportedFooter import com.niyaj.popos.features.components.ImportExportHeader import com.niyaj.popos.features.components.ItemNotAvailable import com.niyaj.popos.features.components.LoadingIndicator import com.niyaj.popos.features.components.util.BottomSheetWithCloseDialog import com.niyaj.popos.features.customer.presentation.components.ImportExportCustomerBody import com.niyaj.popos.features.customer.presentation.settings.CustomerSettingsEvent import com.niyaj.popos.features.customer.presentation.settings.CustomerSettingsViewModel import com.niyaj.popos.utils.Constants import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.result.ResultBackNavigator import com.ramcosta.composedestinations.spec.DestinationStyle import kotlinx.coroutines.launch @OptIn(ExperimentalPermissionsApi::class) @Destination(style = DestinationStyle.BottomSheet::class) @Composable fun ExportCustomerScreen( navController : NavController, viewModel : CustomerSettingsViewModel = hiltViewModel(), resultBackNavigator: ResultBackNavigator<String> ) { val scope = rememberCoroutineScope() val lazyListState = rememberLazyListState() val context = LocalContext.current LaunchedEffect(key1 = true, key2 = Unit) { scope.launch { viewModel.onEvent(CustomerSettingsEvent.GetAllCustomer) } } val hasStoragePermission = rememberMultiplePermissionsState( permissions = listOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, ) ) val isChoose = viewModel.onChoose val customerState = viewModel.customers.collectAsStateWithLifecycle().value val selectedCustomers = viewModel.selectedCustomers.toList() val exportedData = viewModel.importExportedCustomers.collectAsStateWithLifecycle().value var expanded by remember { mutableStateOf(false) } val askForPermissions = { if (!hasStoragePermission.allPermissionsGranted) { hasStoragePermission.launchMultiplePermissionRequest() } } val exportLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult() ) { it.data?.data?.let { scope.launch { val result = writeData(context, it, exportedData) if(result){ resultBackNavigator.navigateBack("${exportedData.size} Customers has been exported") } else { resultBackNavigator.navigateBack("Unable to export customers") } } } } LaunchedEffect(key1 = true) { viewModel.eventFlow.collect { event -> when (event) { is UiEvent.OnSuccess -> { resultBackNavigator.navigateBack(event.successMessage) } is UiEvent.OnError -> { resultBackNavigator.navigateBack(event.errorMessage) } is UiEvent.IsLoading -> {} } } } BottomSheetWithCloseDialog( modifier = Modifier.fillMaxWidth(), text = stringResource(id = R.string.export_customers), icon = Icons.Default.Upload, onClosePressed = { navController.navigateUp() } ) { Crossfade( targetState = customerState, label = "Export Contact Crossfade" ) { customerState -> when { customerState.isLoading -> LoadingIndicator() customerState.customers.isNotEmpty() -> { val showFileSelector = if (isChoose) selectedCustomers.isNotEmpty() else true Column( modifier = Modifier .fillMaxWidth() .padding(SpaceSmall) ) { ImportExportHeader( text = "Export " + if (isChoose) "${selectedCustomers.size} Selected Customer" else " All Customer", isChosen = isChoose, onClickChoose = { viewModel.onEvent(CustomerSettingsEvent.OnChooseCustomer) }, onClickAll = { viewModel.onChoose = false viewModel.onEvent(CustomerSettingsEvent.DeselectCustomers) }, ) AnimatedVisibility( visible = isChoose, enter = fadeIn(), exit = fadeOut(), modifier = Modifier .fillMaxWidth() .then(if (expanded) Modifier.weight(1.1F) else Modifier), ) { ImportExportCustomerBody( lazyListState = lazyListState, customers = customerState.customers, selectedCustomers = selectedCustomers, expanded = expanded, onExpandChanged = { expanded = !expanded }, onSelectCustomer = { viewModel.onEvent(CustomerSettingsEvent.SelectCustomer(it)) }, onClickSelectAll = { viewModel.onEvent(CustomerSettingsEvent.SelectAllCustomer(Constants.ImportExportType.EXPORT)) } ) } ExportedFooter( text = "Export Customers", showFileSelector = showFileSelector, onExportClick = { scope.launch { askForPermissions() val result = ImportExport.createFile( context = context, fileName = EXPORTED_CUSTOMER_FILE_NAME ) exportLauncher.launch(result) viewModel.onEvent(CustomerSettingsEvent.GetExportedCustomer) } } ) } } else -> ItemNotAvailable(text = customerState.error ?: "Customers not available") } } } } const val EXPORTED_CUSTOMER_FILE_NAME = "customers"
4
Kotlin
0
1
6e00bd5451336314b99f6ae1f1f43eea0f2079ad
8,786
POS-Application
MIT License
src/jvmMain/kotlin/baaahs/util/JvmLogger.kt
baaahs
174,897,412
false
{"Kotlin": 3453370, "C": 1529197, "C++": 661364, "GLSL": 404582, "HTML": 55183, "JavaScript": 53132, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.util import org.slf4j.LoggerFactory class JvmLogger(id: String) : NativeLogger { private val logger = LoggerFactory.getLogger(id) override fun debug(exception: Throwable?, message: () -> String) { if (logger.isDebugEnabled) logger.debug(message(), exception) } override fun info(exception: Throwable?, message: () -> String) { if (logger.isInfoEnabled) logger.info(message(), exception) } override fun warn(exception: Throwable?, message: () -> String) { if (logger.isWarnEnabled) logger.warn(message(), exception) } override fun error(exception: Throwable?, message: () -> String) { if (logger.isErrorEnabled) logger.error(message(), exception) } override fun isEnabled(level: LogLevel): Boolean { return when (level) { LogLevel.DEBUG -> logger.isDebugEnabled LogLevel.INFO -> logger.isInfoEnabled LogLevel.WARN -> logger.isWarnEnabled LogLevel.ERROR -> logger.isErrorEnabled } } override fun <T> group(message: String, block: () -> T): T { info { ">> $message" } return try { block() } finally { info { "<< $message" } } } } actual fun getLogger(id: String): NativeLogger = JvmLogger(id)
108
Kotlin
12
40
384a415dc129f7123a48697a79a5a27140e003ea
1,317
sparklemotion
MIT License
libadwaita-bindings/src/nativeMain/kotlin/bindings.adw/PasswordEntryRow.kt
vbsteven
582,302,322
false
null
package bindings.adw import bindings.gobject.asTypedPointer import internal.BuiltinTypeInfo import kotlinx.cinterop.CPointer import native.adwaita.ADW_TYPE_PASSWORD_ENTRY_ROW import native.adwaita.AdwPasswordEntryRow import native.adwaita.adw_password_entry_row_new class PasswordEntryRow : EntryRow { val adwPasswordEntryRow get() = adwEntryRowPointer.asTypedPointer<AdwPasswordEntryRow>() constructor(pointer: CPointer<*>) : super(pointer) constructor() : this(adw_password_entry_row_new()!!) companion object { val Type = BuiltinTypeInfo(ADW_TYPE_PASSWORD_ENTRY_ROW, ::PasswordEntryRow) } }
0
Kotlin
0
24
af5f6c9d32498b6e791a92503dfb45ebfd1af6c3
625
gtk-kotlin-native
MIT License
backpack-compose/src/main/kotlin/net/skyscanner/backpack/compose/card/BpkCard.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018-2021 Skyscanner Ltd * * 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 net.skyscanner.backpack.compose.card import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import net.skyscanner.backpack.compose.theme.BpkTheme import net.skyscanner.backpack.compose.tokens.BpkBorderRadius import net.skyscanner.backpack.compose.tokens.BpkElevation import net.skyscanner.backpack.compose.tokens.BpkSpacing enum class BpkCardCorner { Small, Large, } enum class BpkCardPadding { None, Small, } @OptIn(ExperimentalMaterialApi::class) @Composable fun BpkCard( onClick: () -> Unit, modifier: Modifier = Modifier, corner: BpkCardCorner = BpkCardCorner.Small, padding: BpkCardPadding = BpkCardPadding.Small, contentAlignment: Alignment = Alignment.TopStart, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, content: @Composable BoxScope.() -> Unit, ) { val focused by interactionSource.collectIsFocusedAsState() val pressed by interactionSource.collectIsPressedAsState() val elevated = focused || pressed val elevation by animateDpAsState( when { elevated -> BpkElevation.Xl else -> BpkElevation.Base } ) val backgroundColor by animateColorAsState( when { elevated -> BpkTheme.colors.backgroundElevation02 else -> BpkTheme.colors.backgroundElevation01 } ) Card( modifier = modifier, shape = BpkCardShape(corner), backgroundColor = backgroundColor, contentColor = BpkTheme.colors.textPrimary, elevation = elevation, onClick = onClick, onClickLabel = onClickLabel, interactionSource = interactionSource, enabled = enabled, role = role, content = { BpkCardContent(padding, contentAlignment, content) }, ) } @Composable fun BpkCard( modifier: Modifier = Modifier, corner: BpkCardCorner = BpkCardCorner.Small, padding: BpkCardPadding = BpkCardPadding.Small, contentAlignment: Alignment = Alignment.TopStart, content: @Composable BoxScope.() -> Unit, ) { Card( modifier = modifier, shape = BpkCardShape(corner), backgroundColor = BpkTheme.colors.backgroundElevation01, contentColor = BpkTheme.colors.textPrimary, elevation = BpkElevation.Base, content = { BpkCardContent(padding, contentAlignment, content) }, ) } @Composable private inline fun BpkCardContent( padding: BpkCardPadding, contentAlignment: Alignment, content: @Composable BoxScope.() -> Unit, ) { Box( modifier = Modifier.padding( all = when (padding) { BpkCardPadding.None -> 0.dp BpkCardPadding.Small -> BpkSpacing.Base }, ), contentAlignment = contentAlignment, content = content, ) } private fun BpkCardShape(corner: BpkCardCorner) = RoundedCornerShape( size = when (corner) { BpkCardCorner.Small -> BpkBorderRadius.Md BpkCardCorner.Large -> BpkBorderRadius.Lg } )
7
Kotlin
23
55
f2fd1e811d6e7ea642d3dd231b11966f345e821a
4,423
backpack-android
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/poll/FetchPollResponseEventsTask.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * 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.matrix.android.sdk.internal.session.room.relation.poll import androidx.annotation.VisibleForTesting import com.zhuinden.monarchy.Monarchy import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.RelationType import org.matrix.android.sdk.api.session.events.model.isPollResponse import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.internal.crypto.EventDecryptor import org.matrix.android.sdk.internal.database.mapper.toEntity import org.matrix.android.sdk.internal.database.model.EventEntity import org.matrix.android.sdk.internal.database.model.EventInsertType import org.matrix.android.sdk.internal.database.query.copyToRealmOrIgnore import org.matrix.android.sdk.internal.database.query.where import org.matrix.android.sdk.internal.di.SessionDatabase import org.matrix.android.sdk.internal.network.GlobalErrorReceiver import org.matrix.android.sdk.internal.network.executeRequest import org.matrix.android.sdk.internal.session.room.RoomAPI import org.matrix.android.sdk.internal.session.room.relation.RelationsResponse import org.matrix.android.sdk.internal.task.Task import org.matrix.android.sdk.internal.util.awaitTransaction import org.matrix.android.sdk.internal.util.time.Clock import javax.inject.Inject @VisibleForTesting const val FETCH_RELATED_EVENTS_LIMIT = 50 /** * Task to fetch all the vote events to ensure full aggregation for a given poll. */ internal interface FetchPollResponseEventsTask : Task<FetchPollResponseEventsTask.Params, Result<Unit>> { data class Params( val roomId: String, val startPollEventId: String, ) } internal class DefaultFetchPollResponseEventsTask @Inject constructor( private val roomAPI: RoomAPI, private val globalErrorReceiver: GlobalErrorReceiver, @SessionDatabase private val monarchy: Monarchy, private val clock: Clock, private val eventDecryptor: EventDecryptor, ) : FetchPollResponseEventsTask { override suspend fun execute(params: FetchPollResponseEventsTask.Params): Result<Unit> = runCatching { var nextBatch: String? = fetchAndProcessRelatedEventsFrom(params) while (nextBatch?.isNotEmpty() == true) { nextBatch = fetchAndProcessRelatedEventsFrom(params, from = nextBatch) } } private suspend fun fetchAndProcessRelatedEventsFrom(params: FetchPollResponseEventsTask.Params, from: String? = null): String? { val response = getRelatedEvents(params, from) val filteredEvents = response.chunks .map { decryptEventIfNeeded(it) } .filter { it.isPollResponse() } addMissingEventsInDB(params.roomId, filteredEvents) return response.nextBatch } private suspend fun getRelatedEvents(params: FetchPollResponseEventsTask.Params, from: String? = null): RelationsResponse { return executeRequest(globalErrorReceiver, canRetry = true) { roomAPI.getRelations( roomId = params.roomId, eventId = params.startPollEventId, relationType = RelationType.REFERENCE, from = from, limit = FETCH_RELATED_EVENTS_LIMIT, ) } } private suspend fun addMissingEventsInDB(roomId: String, events: List<Event>) { monarchy.awaitTransaction { realm -> val eventIdsToCheck = events.mapNotNull { it.eventId }.filter { it.isNotEmpty() } if (eventIdsToCheck.isNotEmpty()) { val existingIds = EventEntity.where(realm, eventIdsToCheck).findAll().toList().map { it.eventId } events.filterNot { it.eventId in existingIds } .map { it.toEntity(roomId = roomId, sendState = SendState.SYNCED, ageLocalTs = computeLocalTs(it)) } .forEach { it.copyToRealmOrIgnore(realm, EventInsertType.PAGINATION) } } } } private suspend fun decryptEventIfNeeded(event: Event): Event { if (event.isEncrypted()) { eventDecryptor.decryptEventAndSaveResult(event, timeline = "") } event.ageLocalTs = computeLocalTs(event) return event } private fun computeLocalTs(event: Event) = clock.epochMillis() - (event.unsignedData?.age ?: 0) }
91
Kotlin
4
9
a2c060c687b0aa69af681138c5788d6933d19860
5,006
tchap-android
Apache License 2.0
face_module/src/main/java/com/inz/z/face_module/view/widget/FaceView.kt
Memory-Z
141,771,340
false
{"Java": 1063423, "Kotlin": 584610}
package com.inz.z.face_module.view.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.util.TypedValue import android.view.View /** * author : chensen * data : 2018/3/19 * desc : */ class FaceView : View { lateinit var mPaint: Paint private var mCorlor = "#42ed45" private var mFaces: ArrayList<RectF>? = null constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } private fun init() { mPaint = Paint() mPaint.color = Color.parseColor(mCorlor) mPaint.style = Paint.Style.STROKE mPaint.strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, context.resources.displayMetrics) mPaint.isAntiAlias = true } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) mFaces?.let { for (face in it) { canvas.drawRect(face, mPaint) } } } fun setFaces(faces: ArrayList<RectF>) { this.mFaces = faces invalidate() } }
1
Java
1
1
feff01057cf308fcbf9f1ebf880b9a114badf970
1,409
Z_inz
Apache License 2.0
src/main/kotlin/com/workos/usermanagement/types/AuthenticationAdditionalOptions.kt
workos
419,780,611
false
{"Kotlin": 500568}
package com.workos.usermanagement.types import com.fasterxml.jackson.annotation.JsonProperty open class AuthenticationAdditionalOptions( /** * The token of an invitation. The invitation should be in the pending state. * * When a valid invitation token is specified, the user is able to sign up even * if it is disabled in the environment. Additionally, if the invitation was for * a specific organization, attaching the token to a user's authenticate call * automatically provisions their membership to the organization. */ @JsonProperty("invitation_token") open val invitationToken: String? = null, /** * The IP address of the request from the user who is attempting to authenticate. * * Refer to your web framework or server documentation for the correct way to * obtain the user’s actual IP address. If your application receives requests * from a reverse proxy, you may need to retrieve this from a special header * like `X-Forward-For`. */ @JsonProperty("ip_address") open val ipAddress: String? = null, /** * The user agent of the request from the user who is attempting to authenticate. * This should be the value of the `User-Agent` header. */ @JsonProperty("user_agent") open val userAgent: String? = null )
1
Kotlin
8
12
4387a813f3d17f499386e7b24660f7f8117cab95
1,289
workos-kotlin
MIT License
app/src/main/java/com/korol/myweather/ui/city/RvViewedCityAdapter.kt
AndreyKoroliov1981
456,469,102
false
{"Kotlin": 59456}
package com.korol.myweather.ui.city import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.korol.myweather.databinding.RcViewedCityItemBinding import com.korol.myweather.db.ViewedCity class RvViewedCityAdapter ( var citysList: ArrayList<ViewedCity>, private val onClickListener: RVViewedCityOnClickListener ) : RecyclerView.Adapter<RvViewedCityAdapter.ViewHolder>() { inner class ViewHolder(val binding: RcViewedCityItemBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewedCityAdapter.ViewHolder { val binding =RcViewedCityItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder) { with(citysList[position]) { binding.nameCity.text = this.nameCity binding.nameRegion.text = this.nameRegion binding.saveTime.text=this.currentTime } binding.basket.setOnClickListener { onClickListener.onClickedBasket(citysList[position]) } binding.containerItem.setOnClickListener { onClickListener.onClicked(citysList[position]) } } } override fun getItemCount(): Int { return citysList.size } }
0
Kotlin
0
0
a6074efac0ea6d9c945a2b9edcff5d3b6eec1e44
1,583
My-Weather
The Unlicense
src/main/kotlin/dev/deepslate/fallacy/Fallacy.kt
Mottle
841,231,519
false
{"Kotlin": 289220, "Java": 21036}
package dev.deepslate.fallacy import dev.deepslate.fallacy.common.FallacyTabs import dev.deepslate.fallacy.common.block.FallacyBlocks import dev.deepslate.fallacy.common.data.FallacyAttachments import dev.deepslate.fallacy.common.data.FallacyAttributes import dev.deepslate.fallacy.common.effect.FallacyEffects import dev.deepslate.fallacy.common.item.FallacyItems import dev.deepslate.fallacy.common.item.armor.FallacyArmorMaterials import dev.deepslate.fallacy.common.item.component.FallacyDataComponents import dev.deepslate.fallacy.common.loot.FallacyLootModifiers import dev.deepslate.fallacy.common.registrate.Registration import dev.deepslate.fallacy.race.FallacyRaces import dev.deepslate.fallacy.rule.RangedAttributeRule import dev.deepslate.fallacy.rule.item.VanillaExtendedFoodPropertiesRule import dev.deepslate.fallacy.rule.item.VanillaItemDeprecationRule import net.minecraft.resources.ResourceLocation import net.neoforged.bus.api.IEventBus import net.neoforged.bus.api.SubscribeEvent import net.neoforged.fml.common.Mod import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger @Mod(Fallacy.MOD_ID) class Fallacy(val modBus: IEventBus) { companion object { const val MOD_ID = "fallacy" val LOGGER: Logger = LogManager.getLogger(MOD_ID) fun id(name: String): ResourceLocation = ResourceLocation.fromNamespaceAndPath(MOD_ID, name) } init { modBus.addListener(::commonSetup) Registration.init() FallacyAttachments.register(modBus) FallacyLootModifiers.init(modBus) FallacyTabs.init(modBus) FallacyAttributes.init(modBus) FallacyEffects.init(modBus) FallacyRaces.init(modBus) FallacyDataComponents.init(modBus) FallacyArmorMaterials.init(modBus) FallacyItems FallacyBlocks playRule() } @SubscribeEvent fun commonSetup(event: FMLCommonSetupEvent) { } private fun playRule() { RangedAttributeRule.rule() VanillaExtendedFoodPropertiesRule.rule() VanillaItemDeprecationRule.rule() LOGGER.info("Rules load over.") } }
0
Kotlin
0
0
6858960a6c7021660159a04b8656215efe74cb6e
2,215
Fallacy
MIT License
src/main/kotlin/com/fpwag/admin/domain/entity/Dept.kt
FlowersPlants
286,647,008
false
null
package com.fpwag.admin.domain.entity import com.baomidou.mybatisplus.annotation.TableName import com.fpwag.admin.infrastructure.CommonConstant import com.fpwag.admin.infrastructure.mybatis.base.DataEntity /** * 部门信息 * * @author fpwag */ @TableName(value = "sys_dept") class Dept() : DataEntity() { companion object { private const val serialVersionUID = CommonConstant.SERIAL_VERSION } constructor(id: String?) : this() { this.id = id } var parentId: String? = null var name: String? = null var code: String? = null }
0
Kotlin
0
3
dae83eb311a3d23da5b1d65d3196d7ffdd5229ce
570
fp-admin
Apache License 2.0
serialization/serialization-annotation/src/main/kotlin/androidx/serialization/Field.kt
virendersran01
343,676,031
true
{"Java Properties": 20, "Shell": 44, "Markdown": 43, "Java": 4516, "HTML": 17, "Kotlin": 3557, "Python": 28, "Proguard": 37, "Batchfile": 6, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 1, "C++": 2}
/* * 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.serialization import kotlin.annotation.AnnotationRetention.BINARY import kotlin.annotation.AnnotationTarget.FIELD import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationTarget.PROPERTY import kotlin.annotation.AnnotationTarget.VALUE_PARAMETER /** * Marks a property of a message class as a serializable field. * * Applying this annotation to the properties of a class marks it as a message class. A message * classes may be serialized to a proto-encoded byte array or a [android.os.Parcel] or used as * the request or response type of an [Action] on a service interface. * * ```kotlin * data class MyMessage( * @Field(1) val textField: String, * @Field(2, protoEncoding = ProtoEncoding.ZIG_ZAG_VARINT) negativeField: Int * ) * ``` * * ## Field Types * * Fields may be of a nullable or non-null scalar type including [Boolean], [Double], [Float], * [Int] or [UInt], [Long] or [ULong], [String], and bytes as [ByteArray], [UByteArray], or * [java.nio.ByteBuffer]. Complex types for fields include nullable or non-null enum classes with * [EnumValue] annotations and other message classes in the same compilation unit. Message * classes with only a parcel representation and no proto representation may also include * nullable service interfaces from the same package, nullable instances of active objects * including [android.os.IInterface], [android.os.IBinder], and [android.os.ParcelFileDescriptor]. * * Fields can also be collections of supported non-null types either as arrays or collections. * Supported collection types include [Collection], [Iterable], [List], [Set], and * [java.util.SortedSet] as well as concrete implementations of [Collection] that have a default * constructor. * * Maps fields with non-null string or integral keys and non-null values of any supported type are * supported as well. Supported map types include [Map], [androidx.collection.SimpleArrayMap], * and the specialized `SparseArray` classes from [android.util] or [androidx.collection]. * Concrete implementations of [Map] are also supported provided they have a default constructor. * * ## Default Values * * When deserializing an encoded message, fields missing from the encoded representation are set * to a default value. This property allows the serializer to reduce the size of encoded messages * by eliding scalar fields and nullable fields set to their default values entirely. * * For nullable fields, the default value is always `null`. The default for service fields and * active objects is always `null`, as these fields are required to be nullable. * * For non-null fields, the default varies based on the type of the field: * * * Numeric fields default to zero * * Boolean fields default to false * * String and bytes fields default to an empty string, byte array or byte buffer * * Enum fields default to the enum value marked with [EnumValue.DEFAULT] * * Message fields default to an instance of the message class with all its fields set to * their default values recursively * * Array, collection, and map fields default to an empty container of the appropriate type * * If you need to know if a scalar type was present in an encoded message or simply set to the * default value, use the nullable version of the type. * * ## Message Classes * * Message classes be abstract and may extend other classes, including other message classes * within the same compilation unit. However messages themselves do not have a hierarchy, and * each concrete message class is flattened into one message in the resolved schema. * * Not every property of a message class needs to be serializable, but Serialization must be able * to instantiate a message class from the recognized fields parsed from an encoded message. This * means that a constructor of factory function must exist that only takes field parameters with * this annotation. Alternatively a builder class with this annotation on its setter methods may * be used for instantiation instead. * * This annotation can be used at multiple points for the same logical field, such as a parameter * to a factory function or a setter on a builder and an immutable property on the message class. * To avoid unexpected behavior, both copies of the annotation for a logical field must be * identical. * * @property id Integer ID of the field. * * Valid field IDs are positive integers between 1 and 268,435,456 (`0x0fff_ffff`) inclusive except * 19,000 through 19,999 inclusive, which are [reserved in proto][1]. Note that the upper limit is * one bit smaller than proto's upper limit to accommodate a 4 bits of field length in the parcel * encoding. * * Field IDs must be unique within a message, including any fields inherited from parent message * classes but may be reused between unrelated messages. * * To reserve field IDs for future use or to prevent unintentional reuse of removed field IDs, * apply the [Reserved] annotation to the message class. * * [1]: https://developers.google.com/protocol-buffers/docs/proto3#assigning-field-numbers * * @property protoEncoding The encoding for this field's proto representation. * * If this field is an array or supported collection type, this property sets the encoding of the * items in the collection. If the field is a supported map type, this property sets the encoding * of the values of the map. * * Only integral fields in the proto representation of a message have multiple encoding options. * Leave this set to [ProtoEncoding.DEFAULT] for non-integral fields. * * @property mapKeyProtoEncoding The proto encoding for this field's keys, if it's a map. * * This property is only applicable to fields of supported map types with integral keys. Leave * this set to [ProtoEncoding.DEFAULT] for non-map fields or map fields with string keys. */ @Retention(BINARY) @Target(FIELD, FUNCTION, PROPERTY, VALUE_PARAMETER) public annotation class Field( @get:JvmName("value") val id: Int, val protoEncoding: ProtoEncoding = ProtoEncoding.DEFAULT, val mapKeyProtoEncoding: ProtoEncoding = ProtoEncoding.DEFAULT )
0
null
0
1
e4ce477393fc1026f45fe67b73d8400f19e83975
6,806
androidx
Apache License 2.0
src/main/kotlin/io/mustelidae/riverotter/config/WebConfiguration.kt
stray-cat-developers
297,187,345
false
{"Kotlin": 173944, "Shell": 252}
package io.mustelidae.riverotter.config import io.mustelidae.riverotter.utils.Jackson import org.springframework.context.annotation.Configuration import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar import org.springframework.format.support.FormattingConversionService import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.StringHttpMessageConverter import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.servlet.config.annotation.CorsRegistry import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration import java.time.format.DateTimeFormatter @Configuration @ControllerAdvice class WebConfiguration : DelegatingWebMvcConfiguration() { override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) { val objectMapper = Jackson.getMapper() converters.add(StringHttpMessageConverter()) converters.add(MappingJackson2HttpMessageConverter(objectMapper)) super.configureMessageConverters(converters) } override fun mvcConversionService(): FormattingConversionService { val conversionService = super.mvcConversionService() val dateTimeRegistrar = DateTimeFormatterRegistrar() dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ISO_DATE) dateTimeRegistrar.setTimeFormatter(DateTimeFormatter.ISO_TIME) dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ISO_DATE_TIME) dateTimeRegistrar.registerFormatters(conversionService) return conversionService } override fun addCorsMappings(registry: CorsRegistry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowCredentials(false) .maxAge(3600) } }
1
Kotlin
2
3
09c1839947d0410b0e3d50c3520f783618cbf8f4
1,948
river-otter
MIT License
baselibrary/src/main/java/newtrekwang/com/baselibrary/presenter/view/BaseView.kt
Wangjiaxing123
119,262,875
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "XML": 76, "Kotlin": 80, "Java": 4}
package newtrekwang.com.baselibrary.presenter.view /** * Created by dell on 2018/1/30. */ interface BaseView { fun showLoading() fun hideLoading() fun onError(text:String) fun showToast(str: String) }
0
Kotlin
0
0
dad2cc48cd71c134a872bac151b7fe8a26a498b9
219
KotlinMall
Apache License 2.0
android/app/src/main/java/now/fortuitous/thanos/process/v2/ProcessManageScreen.kt
Tornaco
228,014,878
false
null
/* * (C) Copyright 2022 Thanox * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package github.tornaco.android.thanos.process.v2 import android.text.format.DateUtils import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.FilterAlt import androidx.compose.material.icons.filled.OpenInNew import androidx.compose.material.icons.filled.Search import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import com.elvishew.xlog.XLog import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshIndicator import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import dev.enro.core.compose.registerForNavigationResult import github.tornaco.android.thanos.R import github.tornaco.android.thanos.apps.AppDetailsActivity import github.tornaco.android.thanos.core.pm.AppInfo import github.tornaco.android.thanos.module.compose.common.widget.AppLabelText import github.tornaco.android.thanos.module.compose.common.widget.SmallSpacer import github.tornaco.android.thanos.module.compose.common.widget.clickableWithRipple import github.tornaco.android.thanos.module.compose.common.loader.AppSetFilterItem import github.tornaco.android.thanos.module.compose.common.requireActivity import github.tornaco.android.thanos.module.compose.common.theme.ColorDefaults import github.tornaco.android.thanos.module.compose.common.theme.TypographyDefaults.appBarTitleTextStyle import github.tornaco.android.thanos.module.compose.common.widget.* import kotlinx.coroutines.flow.distinctUntilChanged @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class) @Composable fun ProcessManageScreen( onBackPressed: () -> Unit, toLegacyUi: () -> Unit ) { val viewModel = hiltViewModel<ProcessManageViewModel>(LocalContext.current.requireActivity()) val lifecycle = LocalLifecycleOwner.current.lifecycle viewModel.bindLifecycle(lifecycle) val state by viewModel.state.collectAsState() val navHandle = registerForNavigationResult<Boolean> { shouldUpdate -> if (shouldUpdate) { viewModel.refresh(0) } } XLog.d("viewModel= $viewModel by owner: ${LocalViewModelStoreOwner.current}") LaunchedEffect(viewModel) { viewModel.init() } val listState = rememberLazyListState() val searchBarState = rememberSearchBarState() LaunchedEffect(searchBarState) { snapshotFlow { searchBarState.keyword } .distinctUntilChanged() .collect { viewModel.keywordChanged(it) } } BackHandler(searchBarState.showSearchBar) { searchBarState.closeSearchBar() } ThanoxSmallAppBarScaffold( title = { Text( stringResource(id = R.string.feature_title_process_manage), style = appBarTitleTextStyle() ) }, actions = { Row( modifier = Modifier, verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = { toLegacyUi() }) { Icon( imageVector = Icons.Filled.OpenInNew, contentDescription = "Back to legacy ui" ) } IconButton(onClick = { searchBarState.showSearchBar() }) { Icon( imageVector = Icons.Filled.Search, contentDescription = "Search" ) } } }, searchBarState = searchBarState, floatingActionButton = { ExtendableFloatingActionButton( extended = false, text = { Text(text = stringResource(id = R.string.feature_title_one_key_boost)) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_rocket_line), contentDescription = "Boost" ) }) { viewModel.clearBgTasks() } }, onBackPressed = onBackPressed ) { contentPadding -> SwipeRefresh( state = rememberSwipeRefreshState(state.isLoading), onRefresh = { viewModel.refresh() }, // Shift the indicator to match the list content padding indicatorPadding = contentPadding, // We want the indicator to draw within the padding clipIndicatorToPadding = false, // Tweak the indicator to scale up/down indicator = { state, refreshTriggerDistance -> SwipeRefreshIndicator( state = state, refreshTriggerDistance = refreshTriggerDistance, scale = true, arrowEnabled = false, contentColor = MaterialTheme.colorScheme.primary ) } ) { val context = LocalContext.current RunningAppList( modifier = Modifier.padding(contentPadding), lazyListState = listState, state = state, onRunningItemClick = { navHandle.open(RunningAppStateDetails(it)) }, onNotRunningItemClick = { AppDetailsActivity.start(context, it) }, onFilterItemSelected = { viewModel.onFilterItemSelected(it) }) } } } @Composable private fun AppFilterDropDown(state: ProcessManageState, onFilterItemSelected: (AppSetFilterItem) -> Unit) { FilterDropDown( icon = Icons.Filled.FilterAlt, selectedItem = state.selectedAppSetFilterItem, allItems = state.appFilterItems, onItemSelected = onFilterItemSelected ) } @OptIn(ExperimentalFoundationApi::class) @Composable fun RunningAppList( modifier: Modifier, lazyListState: LazyListState = rememberLazyListState(), state: ProcessManageState, onRunningItemClick: (RunningAppState) -> Unit, onNotRunningItemClick: (AppInfo) -> Unit, onFilterItemSelected: (AppSetFilterItem) -> Unit ) { LazyColumn( state = lazyListState, modifier = modifier .background(color = MaterialTheme.colorScheme.surface) .fillMaxSize() ) { item { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 8.dp) ) { AppFilterDropDown(state, onFilterItemSelected) Spacer(modifier = Modifier.size(16.dp)) } } if (state.runningAppStates.isNotEmpty()) { stickyHeader { RunningGroupHeader(state.runningAppStates.size) } items(state.runningAppStates) { RunningAppItem( it, state.cpuUsageRatioStates[it.appInfo], state.netSpeedStates[it.appInfo], onRunningItemClick ) } } if (state.runningAppStatesBg.isNotEmpty()) { stickyHeader { CachedGroupHeader(state.runningAppStatesBg.size) } items(state.runningAppStatesBg) { RunningAppItem( it, state.cpuUsageRatioStates[it.appInfo], state.netSpeedStates[it.appInfo], onRunningItemClick ) } } if (state.appsNotRunning.isNotEmpty()) { stickyHeader { NotRunningGroupHeader(state.appsNotRunning.size) } items(state.appsNotRunning) { NotRunningAppItem(it, onNotRunningItemClick) } } } } @Composable fun CachedGroupHeader(itemCount: Int) { Surface(tonalElevation = 2.dp) { Box( modifier = Modifier .fillMaxWidth() .background(ColorDefaults.backgroundSurfaceColor()) .padding(horizontal = 20.dp, vertical = 8.dp), contentAlignment = Alignment.CenterStart ) { val text = stringResource(id = R.string.running_process_background) Text( text = "$text - $itemCount", style = MaterialTheme.typography.titleMedium ) } } } @Composable fun RunningGroupHeader(itemCount: Int) { Surface(tonalElevation = 2.dp) { Box( modifier = Modifier .fillMaxWidth() .background(ColorDefaults.backgroundSurfaceColor()) .padding(horizontal = 20.dp, vertical = 8.dp), contentAlignment = Alignment.CenterStart ) { val text = stringResource(id = R.string.running_process_running) Text( text = "$text - $itemCount", style = MaterialTheme.typography.titleMedium ) } } } @Composable fun NotRunningGroupHeader(itemCount: Int) { Surface(tonalElevation = 2.dp) { Box( modifier = Modifier .fillMaxWidth() .background(ColorDefaults.backgroundSurfaceColor()) .padding(horizontal = 20.dp, vertical = 8.dp), contentAlignment = Alignment.CenterStart ) { val text = stringResource(id = R.string.running_process_not_running) Text( text = "$text - $itemCount", style = MaterialTheme.typography.titleMedium ) } } } @Composable fun RunningAppItem( appState: RunningAppState, cpuRatio: String?, netSpeed: NetSpeedState?, onItemClick: (RunningAppState) -> Unit ) { Box( modifier = Modifier .clickableWithRipple { onItemClick(appState) } ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 4.dp) .heightIn(min = 72.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start ) { AppIcon(modifier = Modifier.size(38.dp), appState.appInfo) Spacer(modifier = Modifier.size(12.dp)) Column(verticalArrangement = Arrangement.Center) { AppLabelText( Modifier.sizeIn(maxWidth = 240.dp), appState.appInfo.appLabel ) if (appState.serviceCount == 0) { PText(appState) } else { PSText(appState) } AppRunningTime(appState) } } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.End ) { MemSizeBadge(appState) cpuRatio?.let { SmallSpacer() MD3Badge("CPU $it%") } SmallSpacer() AnimatedVisibility(visible = netSpeed != null) { netSpeed?.let { NetSpeedBadge(it) } } } } } } @Composable private fun AppRunningTime(appState: RunningAppState) { if (appState.runningTimeMillis != null) { val runningTimeStr = DateUtils.formatElapsedTime(null, appState.runningTimeMillis / 1000L) Text( text = "${ stringResource( id = R.string.service_running_time ) } $runningTimeStr", style = MaterialTheme.typography.labelMedium ) } } @OptIn(ExperimentalMaterialApi::class) @Composable fun NotRunningAppItem(appInfo: AppInfo, onItemClick: (AppInfo) -> Unit) { Box( modifier = Modifier .clickableWithRipple { onItemClick(appInfo) } ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .heightIn(min = 64.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start ) { AppIcon(modifier = Modifier.size(38.dp), appInfo) Spacer(modifier = Modifier.size(12.dp)) Column(verticalArrangement = Arrangement.Center) { AppLabelText( Modifier.sizeIn(maxWidth = 220.dp), appInfo.appLabel ) } } } } } @Composable fun MemSizeBadge(appState: RunningAppState) { MD3Badge(appState.sizeStr) } @Composable fun NetSpeedBadge(netSpeed: NetSpeedState) { MD3Badge("↑ ${netSpeed.up}/s ↓ ${netSpeed.down}/s") } @Composable fun PSText(appState: RunningAppState) { Text( text = stringResource( id = R.string.running_processes_item_description_p_s, appState.processState.size, appState.serviceCount ), fontSize = 12.sp ) } @Composable fun PText(appState: RunningAppState) { Text( text = stringResource( id = R.string.running_processes_item_description_p, appState.processState.size ), fontSize = 12.sp ) }
392
null
87
2,145
b8b756152e609c96fd07f1f282b77582d8cde647
15,573
Thanox
Apache License 2.0
inappmessaging/src/test/java/io/karte/android/inappmessaging/unit/IAMWebViewTest.kt
y-aimi0805
276,550,949
true
{"Kotlin": 578155, "Java": 19268, "Ruby": 10195, "Shell": 2229, "Groovy": 710}
// // Copyright 2020 PLAID, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.karte.android.inappmessaging.unit import android.net.Uri import android.net.http.SslError import android.view.KeyEvent import android.webkit.SslErrorHandler import android.webkit.WebResourceError import android.webkit.WebResourceRequest import com.google.common.truth.Truth.assertThat import io.karte.android.application import io.karte.android.inappmessaging.InAppMessaging import io.karte.android.inappmessaging.internal.IAMWebView import io.karte.android.inappmessaging.internal.MessageModel import io.karte.android.inappmessaging.internal.ParentView import io.karte.android.inappmessaging.internal.javascript.State import io.karte.android.shadow.CustomShadowWebView import io.karte.android.shadow.customShadowOf import io.karte.android.tracking.Tracker import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.clearMocks import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.slot import io.mockk.verify import org.json.JSONArray import org.json.JSONObject import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowWebView @Suppress("NonAsciiCharacters") @RunWith(RobolectricTestRunner::class) @Config( packageName = "io.karte.android.tracker", sdk = [24], shadows = [CustomShadowWebView::class] ) class IAMWebViewTest { private fun makeStateReady() { webView.onReceivedMessage( "state_changed", JSONObject().put("state", "initialized").toString() ) } val dummy_url = "https://dummy_url/test" val overlay_url = "https://api.karte.io/v0/native/overlay" val empty_data = "<html></html>" private lateinit var webView: IAMWebView private lateinit var shadowWebView: ShadowWebView @MockK private lateinit var adapter: MessageModel.MessageAdapter @MockK private lateinit var parent: ParentView @Before fun init() { MockKAnnotations.init(this, relaxUnitFun = true) createKarteAppMock() webView = IAMWebView(application(), InAppMessaging.Config.enabledWebViewCache) { true } webView.adapter = adapter webView.parentView = parent shadowWebView = Shadows.shadowOf(webView) } @After fun tearDown() { customShadowOf(webView).resetLoadedUrls() } @Test fun EventCallbackでtrackが呼ばれること() { mockkStatic(Tracker::class) val eventNameSlot = slot<String>() val jsonSlot = slot<JSONObject>() every { Tracker.track(capture(eventNameSlot), capture(jsonSlot)) } just Runs val values = JSONObject().put("samplekey", "samplevalue") webView.onReceivedMessage( "event", JSONObject().put("event_name", "some_event").put("values", values).toString() ) verify(exactly = 1) { Tracker.track(any(), any<JSONObject>()) } assertThat(eventNameSlot.captured).isEqualTo("some_event") assertThat(jsonSlot.captured.toString()).isEqualTo(values.toString()) } @Test fun trackerJsの読み込み後にはすぐに読み込むこと() { // 中身の確認に一度読み込む every { adapter.dequeue() } returns null makeStateReady() verify(exactly = 1) { adapter.dequeue() } clearMocks(adapter) every { adapter.dequeue() } returnsMany listOf("test", "test", null) webView.notifyChanged() verify(exactly = 3) { adapter.dequeue() } val loadedUrls = customShadowOf(webView).loadedUrls assertThat(loadedUrls.size).isEqualTo(2) for (uri in loadedUrls) { assertThat(uri).isEqualTo("javascript:window.tracker.handleResponseData('test');") } } @Test fun StateChange_initializedでadapterからデータ取得されること() { every { adapter.dequeue() } returnsMany listOf("test", "test", null) // readyでなければdequeueしない。 webView.notifyChanged() verify(inverse = true) { adapter.dequeue() } makeStateReady() Assert.assertEquals(webView.state, State.READY) verify(exactly = 3) { adapter.dequeue() } val loadedUrls = customShadowOf(webView).loadedUrls assertThat(loadedUrls.size).isEqualTo(2) for (uri in loadedUrls) { assertThat(uri).isEqualTo("javascript:window.tracker.handleResponseData('test');") } } @Test fun StateChange_errorでstateがDESTROYEDに変更されること() { webView.onReceivedMessage( "state_changed", JSONObject() .put("state", "error") .put("message", "samplemessage") .toString() ) Assert.assertEquals(webView.state, State.DESTROYED) } @Test fun startActivityOnOpenUrlCallback() { webView.onReceivedMessage( "open_url", JSONObject().put("url", "http://sampleurl").toString() ) verify(exactly = 1) { parent.openUrl(Uri.parse("http://sampleurl")) } } @Test fun startActivityOnOpenUrlCallbackWithQueryParameters() { webView.onReceivedMessage( "open_url", JSONObject().put("url", "http://sampleurl?hoge=fuga&hogehoge=fugafuga").toString() ) verify(exactly = 1) { parent.openUrl(Uri.parse("http://sampleurl?hoge=fuga&hogehoge=fugafuga")) } } @Test fun DocumentChangedでupdateTouchableRegionsが呼ばれること() { webView.onReceivedMessage( "document_changed", JSONObject() .put( "touchable_regions", JSONArray().put( JSONObject() .put("top", 10.0) .put("bottom", 10.0) .put("left", 10.0) .put("right", 10.0) ) ).toString() ) verify(exactly = 1) { parent.updateTouchableRegions(ofType()) } } @Test fun Visibility_visibleでshowが呼ばれること() { webView.onReceivedMessage("visibility", JSONObject().put("state", "visible").toString()) verify(exactly = 1) { parent.show() } } @Test fun Visibility_invisibleでdismissが呼ばれること() { webView.onReceivedMessage("visibility", JSONObject().put("state", "invisible").toString()) verify(exactly = 1) { parent.dismiss() } } @Test fun backボタンの処理を行うこと() { val backKey = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK) webView.loadUrl(dummy_url) assertThat(webView.canGoBack()).isFalse() assertThat(webView.dispatchKeyEvent(backKey)).isFalse() webView.loadUrl(dummy_url) assertThat(webView.canGoBack()).isTrue() assertThat(webView.dispatchKeyEvent(backKey)).isTrue() assertThat(webView.canGoBack()).isFalse() } @Test fun onReceivedSslErrorでoverlayのロードに失敗するとparentがhandleする() { val error = mockk<SslError>() val handler = mockk<SslErrorHandler>(relaxUnitFun = true) // urlが異なる時はempty_dataをloadしない every { error.url } returns dummy_url shadowWebView.webViewClient.onReceivedSslError(webView, handler, error) assertThat(shadowWebView.lastLoadData).isNull() verify(inverse = true) { parent.errorOccurred() } // urlが同じ時はempty_dataをload webView.loadUrl(dummy_url) every { error.url } returns dummy_url shadowWebView.webViewClient.onReceivedSslError(webView, handler, error) assertThat(shadowWebView.lastLoadData.data).isEqualTo(empty_data) verify(inverse = true) { parent.errorOccurred() } // urlがoverlayの時は親に伝える every { error.url } returns overlay_url shadowWebView.webViewClient.onReceivedSslError(webView, handler, error) verify(exactly = 1) { parent.errorOccurred() } } @Test fun onReceivedHttpErrorでoverlayのロードに失敗するとparentがhandleする() { val webResourceRequest = mockk<WebResourceRequest>() // urlが異なる時はempty_dataをloadしない every { webResourceRequest.url } returns Uri.parse(dummy_url) shadowWebView.webViewClient.onReceivedHttpError(webView, webResourceRequest, null) assertThat(shadowWebView.lastLoadData).isNull() verify(inverse = true) { parent.errorOccurred() } // urlが同じ時はempty_dataをload webView.loadUrl(dummy_url) every { webResourceRequest.url } returns Uri.parse(dummy_url) shadowWebView.webViewClient.onReceivedHttpError(webView, webResourceRequest, null) assertThat(shadowWebView.lastLoadData.data).isEqualTo(empty_data) verify(inverse = true) { parent.errorOccurred() } // urlがoverlayの時は親に伝える every { webResourceRequest.url } returns Uri.parse(overlay_url) shadowWebView.webViewClient.onReceivedHttpError(webView, webResourceRequest, null) verify(exactly = 1) { parent.errorOccurred() } } @Test fun onReceivedErrorでoverlayのロードに失敗するとparentがhandleする() { val description = "dumy error reason" val request = mockk<WebResourceRequest>(relaxed = true) val error = mockk<WebResourceError>() every { error.description } returns description every { request.url } returns Uri.parse(dummy_url) // urlが異なる時はempty_dataをloadしない shadowWebView.webViewClient.onReceivedError(webView, request, error) assertThat(shadowWebView.lastLoadData).isNull() verify(inverse = true) { parent.errorOccurred() } // urlが同じ時はempty_dataをload webView.loadUrl(dummy_url) shadowWebView.webViewClient.onReceivedError(webView, request, error) assertThat(shadowWebView.lastLoadData.data).isEqualTo(empty_data) verify(inverse = true) { parent.errorOccurred() } // urlがoverlayの時は親に伝える every { request.url } returns Uri.parse(overlay_url) shadowWebView.webViewClient.onReceivedError(webView, request, error) verify(exactly = 1) { parent.errorOccurred() } } @Test fun 古いonReceivedErrorでoverlayのロードに失敗するとparentがhandleする() { val errorCode = 0 val description = "dummy description" // urlが異なる時はempty_dataをloadしない shadowWebView.webViewClient.onReceivedError(webView, errorCode, description, dummy_url) assertThat(shadowWebView.lastLoadData).isNull() verify(inverse = true) { parent.errorOccurred() } // urlが同じ時はempty_dataをload webView.loadUrl(dummy_url) shadowWebView.webViewClient.onReceivedError(webView, errorCode, description, dummy_url) assertThat(shadowWebView.lastLoadData.data).isEqualTo(empty_data) verify(inverse = true) { parent.errorOccurred() } // urlがoverlayの時は親に伝える shadowWebView.webViewClient.onReceivedError(webView, errorCode, description, overlay_url) verify(exactly = 1) { parent.errorOccurred() } } @Test fun 非表示時にdestroyされること_cache無効() { val webView = IAMWebView(application(), false) { false } webView.resetOrDestroy() val loadedUrls = customShadowOf(webView).loadedUrls assertThat(loadedUrls.size).isEqualTo(0) assertThat(Shadows.shadowOf(webView).wasDestroyCalled()).isTrue() } @Test fun 非表示時にresetされること_cache有効() { val webView = IAMWebView(application(), true) { false } webView.resetOrDestroy() val loadedUrls = customShadowOf(webView).loadedUrls assertThat(loadedUrls.size).isEqualTo(1) assertThat(loadedUrls.last()).isEqualTo("javascript:window.tracker.resetPageState();") } }
0
null
0
0
578e27ecf330b4c48626a4bee15c35bddba90eaf
12,335
karte-android-sdk
Apache License 2.0
arrow-libs/core/arrow-core/src/nonJvmMain/kotlin/arrow/core/NonFatal.kt
arrow-kt
86,057,409
false
{"Kotlin": 2793646, "Java": 7691}
package arrow.core import arrow.continuations.generic.ControlThrowable import kotlin.coroutines.cancellation.CancellationException public actual fun NonFatal(t: Throwable): Boolean = when (t) { is ControlThrowable, is CancellationException -> false else -> true }
38
Kotlin
436
5,958
5f0da6334b834bad481c7e3c906bee5a34c1237b
278
arrow
Apache License 2.0
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/model/BoundingBoxData.kt
korlibs
80,095,683
false
null
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * 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 com.dragonbones.model import com.dragonbones.core.* import com.dragonbones.geom.* import com.dragonbones.util.* import com.soywiz.kds.* import kotlin.math.* /** * - The base class of bounding box data. * @see dragonBones.RectangleData * @see dragonBones.EllipseData * @see dragonBones.PolygonData * @version DragonBones 5.0 * @language en_US */ /** * - 边界框数据基类。 * @see dragonBones.RectangleData * @see dragonBones.EllipseData * @see dragonBones.PolygonData * @version DragonBones 5.0 * @language zh_CN */ abstract class BoundingBoxData(pool: BaseObjectPool) : BaseObject(pool) { /** * - The bounding box type. * @version DragonBones 5.0 * @language en_US */ /** * - 边界框类型。 * @version DragonBones 5.0 * @language zh_CN */ var type: BoundingBoxType = BoundingBoxType.None /** * @private */ var color: Int = 0x000000 /** * @private */ var width: Double = 0.0 /** * @private */ var height: Double = 0.0 override fun _onClear(): Unit { this.color = 0x000000 this.width = 0.0 this.height = 0.0 } /** * - Check whether the bounding box contains a specific point. (Local coordinate system) * @version DragonBones 5.0 * @language en_US */ /** * - 检查边界框是否包含特定点。(本地坐标系) * @version DragonBones 5.0 * @language zh_CN */ abstract fun containsPoint(pX: Double, pY: Double): Boolean /** * - Check whether the bounding box intersects a specific segment. (Local coordinate system) * @version DragonBones 5.0 * @language en_US */ /** * - 检查边界框是否与特定线段相交。(本地坐标系) * @version DragonBones 5.0 * @language zh_CN */ abstract fun intersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, intersectionPointA: Point? = null, intersectionPointB: Point? = null, normalRadians: Point? = null ): Int } /** * - Cohen–Sutherland algorithm https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm * ---------------------- * | 0101 | 0100 | 0110 | * ---------------------- * | 0001 | 0000 | 0010 | * ---------------------- * | 1001 | 1000 | 1010 | * ---------------------- */ //enum class OutCode(val id: Int) { // InSide(0), // 0000 // Left(1), // 0001 // Right(2), // 0010 // Top(4), // 0100 // Bottom(8) // 1000 //} object OutCode { const val InSide = 0 // 0000 const val Left = 1 // 0001 const val Right = 2 // 0010 const val Top = 4 // 0100 const val Bottom = 8 // 1000 } /** * - The rectangle bounding box data. * @version DragonBones 5.1 * @language en_US */ /** * - 矩形边界框数据。 * @version DragonBones 5.1 * @language zh_CN */ class RectangleBoundingBoxData(pool: BaseObjectPool) : BoundingBoxData(pool) { override fun toString(): String { return "[class dragonBones.RectangleBoundingBoxData]" } companion object { /** * - Compute the bit code for a point (x, y) using the clip rectangle */ private fun _computeOutCode(x: Double, y: Double, xMin: Double, yMin: Double, xMax: Double, yMax: Double): Int { var code = OutCode.InSide // initialised as being inside of [[clip window]] if (x < xMin) { // to the left of clip window code = code or OutCode.Left } else if (x > xMax) { // to the right of clip window code = code or OutCode.Right } if (y < yMin) { // below the clip window code = code or OutCode.Top } else if (y > yMax) { // above the clip window code = code or OutCode.Bottom } return code } /** * @private */ fun rectangleIntersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, xMin: Double, yMin: Double, xMax: Double, yMax: Double, intersectionPointA: Point? = null, intersectionPointB: Point? = null, normalRadians: Point? = null ): Int { var xA = xA var yA = yA var xB = xB var yB = yB val inSideA = xA > xMin && xA < xMax && yA > yMin && yA < yMax val inSideB = xB > xMin && xB < xMax && yB > yMin && yB < yMax if (inSideA && inSideB) { return -1 } var intersectionCount = 0 var outcode0 = RectangleBoundingBoxData._computeOutCode(xA, yA, xMin, yMin, xMax, yMax) var outcode1 = RectangleBoundingBoxData._computeOutCode(xB, yB, xMin, yMin, xMax, yMax) while (true) { if ((outcode0 or outcode1) == 0) { // Bitwise OR is 0. Trivially accept and get out of loop intersectionCount = 2 break } else if ((outcode0 and outcode1) != 0) { // Bitwise AND is not 0. Trivially reject and get out of loop break } // failed both tests, so calculate the line segment to clip // from an outside point to an intersection with clip edge var x = 0.0 var y = 0.0 var normalRadian = 0.0 // At least one endpoint is outside the clip rectangle; pick it. val outcodeOut = if (outcode0 != 0) outcode0 else outcode1 // Now find the intersection point; if ((outcodeOut and OutCode.Top) != 0) { // point is above the clip rectangle x = xA + (xB - xA) * (yMin - yA) / (yB - yA) y = yMin if (normalRadians != null) { normalRadian = -PI * 0.5 } } else if ((outcodeOut and OutCode.Bottom) != 0) { // point is below the clip rectangle x = xA + (xB - xA) * (yMax - yA) / (yB - yA) y = yMax if (normalRadians != null) { normalRadian = PI * 0.5 } } else if ((outcodeOut and OutCode.Right) != 0) { // point is to the right of clip rectangle y = yA + (yB - yA) * (xMax - xA) / (xB - xA) x = xMax if (normalRadians != null) { normalRadian = 0.0 } } else if ((outcodeOut and OutCode.Left) != 0) { // point is to the left of clip rectangle y = yA + (yB - yA) * (xMin - xA) / (xB - xA) x = xMin if (normalRadians != null) { normalRadian = PI } } // Now we move outside point to intersection point to clip // and get ready for next pass. if (outcodeOut == outcode0) { xA = x yA = y outcode0 = RectangleBoundingBoxData._computeOutCode(xA, yA, xMin, yMin, xMax, yMax) if (normalRadians != null) { normalRadians.x = normalRadian.toFloat() } } else { xB = x yB = y outcode1 = RectangleBoundingBoxData._computeOutCode(xB, yB, xMin, yMin, xMax, yMax) if (normalRadians != null) { normalRadians.y = normalRadian.toFloat() } } } if (intersectionCount != 0) { if (inSideA) { intersectionCount = 2 // 10 if (intersectionPointA != null) { intersectionPointA.x = xB.toFloat() intersectionPointA.y = yB.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xB.toFloat() intersectionPointB.y = xB.toFloat() } if (normalRadians != null) { normalRadians.x = (normalRadians.y + PI).toFloat() } } else if (inSideB) { intersectionCount = 1 // 01 if (intersectionPointA != null) { intersectionPointA.x = xA.toFloat() intersectionPointA.y = yA.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xA.toFloat() intersectionPointB.y = yA.toFloat() } if (normalRadians != null) { normalRadians.y = (normalRadians.x + PI).toFloat() } } else { intersectionCount = 3 // 11 if (intersectionPointA != null) { intersectionPointA.x = xA.toFloat() intersectionPointA.y = yA.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xB.toFloat() intersectionPointB.y = yB.toFloat() } } } return intersectionCount } } override fun _onClear(): Unit { super._onClear() this.type = BoundingBoxType.Rectangle } /** * @inheritDoc */ override fun containsPoint(pX: Double, pY: Double): Boolean { val widthH = this.width * 0.5 if (pX >= -widthH && pX <= widthH) { val heightH = this.height * 0.5 if (pY >= -heightH && pY <= heightH) { return true } } return false } /** * @inheritDoc */ override fun intersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, intersectionPointA: Point?, intersectionPointB: Point?, normalRadians: Point? ): Int { val widthH = this.width * 0.5 val heightH = this.height * 0.5 val intersectionCount = RectangleBoundingBoxData.rectangleIntersectsSegment( xA, yA, xB, yB, -widthH, -heightH, widthH, heightH, intersectionPointA, intersectionPointB, normalRadians ) return intersectionCount } } /** * - The ellipse bounding box data. * @version DragonBones 5.1 * @language en_US */ /** * - 椭圆边界框数据。 * @version DragonBones 5.1 * @language zh_CN */ class EllipseBoundingBoxData(pool: BaseObjectPool) : BoundingBoxData(pool) { override fun toString(): String { return "[class dragonBones.EllipseData]" } companion object { /** * @private */ fun ellipseIntersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, xC: Double, yC: Double, widthH: Double, heightH: Double, intersectionPointA: Point? = null, intersectionPointB: Point? = null, normalRadians: Point? = null ): Int { var xA = xA var xB = xB var yA = yA var yB = yB val d = widthH / heightH val dd = d * d yA *= d yB *= d val dX = xB - xA val dY = yB - yA val lAB = sqrt(dX * dX + dY * dY) val xD = dX / lAB val yD = dY / lAB val a = (xC - xA) * xD + (yC - yA) * yD val aa = a * a val ee = xA * xA + yA * yA val rr = widthH * widthH val dR = rr - ee + aa var intersectionCount = 0 if (dR >= 0.0) { val dT = sqrt(dR) val sA = a - dT val sB = a + dT val inSideA = if (sA < 0.0) -1 else if (sA <= lAB) 0 else 1 val inSideB = if (sB < 0.0) -1 else if (sB <= lAB) 0 else 1 val sideAB = inSideA * inSideB if (sideAB < 0) { return -1 } else if (sideAB == 0) { if (inSideA == -1) { intersectionCount = 2 // 10 xB = xA + sB * xD yB = (yA + sB * yD) / d if (intersectionPointA != null) { intersectionPointA.x = xB.toFloat() intersectionPointA.y = yB.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xB.toFloat() intersectionPointB.y = yB.toFloat() } if (normalRadians != null) { normalRadians.x = atan2(yB / rr * dd, xB / rr).toFloat() normalRadians.y = (normalRadians.x + PI).toFloat() } } else if (inSideB == 1) { intersectionCount = 1 // 01 xA = xA + sA * xD yA = (yA + sA * yD) / d if (intersectionPointA != null) { intersectionPointA.x = xA.toFloat() intersectionPointA.y = yA.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xA.toFloat() intersectionPointB.y = yA.toFloat() } if (normalRadians != null) { normalRadians.x = atan2(yA / rr * dd, xA / rr).toFloat() normalRadians.y = (normalRadians.x + PI).toFloat() } } else { intersectionCount = 3 // 11 if (intersectionPointA != null) { intersectionPointA.x = (xA + sA * xD).toFloat() intersectionPointA.y = ((yA + sA * yD) / d).toFloat() if (normalRadians != null) { normalRadians.x = atan2(intersectionPointA.y / rr * dd, intersectionPointA.x / rr).toFloat() } } if (intersectionPointB != null) { intersectionPointB.x = (xA + sB * xD).toFloat() intersectionPointB.y = ((yA + sB * yD) / d).toFloat() if (normalRadians != null) { normalRadians.y = atan2(intersectionPointB.y / rr * dd, intersectionPointB.x / rr).toFloat() } } } } } return intersectionCount } } override fun _onClear(): Unit { super._onClear() this.type = BoundingBoxType.Ellipse } /** * @inheritDoc */ override fun containsPoint(pX: Double, pY: Double): Boolean { var pY = pY val widthH = this.width * 0.5 if (pX >= -widthH && pX <= widthH) { val heightH = this.height * 0.5 if (pY >= -heightH && pY <= heightH) { pY *= widthH / heightH return sqrt(pX * pX + pY * pY) <= widthH } } return false } /** * @inheritDoc */ override fun intersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, intersectionPointA: Point?, intersectionPointB: Point?, normalRadians: Point? ): Int { val intersectionCount = EllipseBoundingBoxData.ellipseIntersectsSegment( xA, yA, xB, yB, 0.0, 0.0, this.width * 0.5, this.height * 0.5, intersectionPointA, intersectionPointB, normalRadians ) return intersectionCount } } /** * - The polygon bounding box data. * @version DragonBones 5.1 * @language en_US */ /** * - 多边形边界框数据。 * @version DragonBones 5.1 * @language zh_CN */ class PolygonBoundingBoxData(pool: BaseObjectPool) : BoundingBoxData(pool) { override fun toString(): String { return "[class dragonBones.PolygonBoundingBoxData]" } /** * @private */ fun polygonIntersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, vertices: DoubleArray, intersectionPointA: Point? = null, intersectionPointB: Point? = null, normalRadians: Point? = null ): Int { var xA = xA var yA = yA if (xA == xB) xA = xB + 0.000001 if (yA == yB) yA = yB + 0.000001 val count = vertices.size val dXAB = xA - xB val dYAB = yA - yB val llAB = xA * yB - yA * xB var intersectionCount = 0 var xC = vertices[count - 2].toDouble() var yC = vertices[count - 1].toDouble() var dMin = 0.0 var dMax = 0.0 var xMin = 0.0 var yMin = 0.0 var xMax = 0.0 var yMax = 0.0 for (i in 0 until count step 2) { val xD = vertices[i + 0].toDouble() val yD = vertices[i + 1].toDouble() if (xC == xD) { xC = xD + 0.0001 } if (yC == yD) { yC = yD + 0.0001 } val dXCD = xC - xD val dYCD = yC - yD val llCD = xC * yD - yC * xD val ll = dXAB * dYCD - dYAB * dXCD val x = (llAB * dXCD - dXAB * llCD) / ll if (((x >= xC && x <= xD) || (x >= xD && x <= xC)) && (dXAB == 0.0 || (x >= xA && x <= xB) || (x >= xB && x <= xA))) { val y = (llAB * dYCD - dYAB * llCD) / ll if (((y >= yC && y <= yD) || (y >= yD && y <= yC)) && (dYAB == 0.0 || (y >= yA && y <= yB) || (y >= yB && y <= yA))) { if (intersectionPointB != null) { var d = x - xA if (d < 0.0) { d = -d } if (intersectionCount == 0) { dMin = d dMax = d xMin = x yMin = y xMax = x yMax = y if (normalRadians != null) { normalRadians.x = (atan2(yD - yC, xD - xC) - PI * 0.5).toFloat() normalRadians.y = normalRadians.x } } else { if (d < dMin) { dMin = d xMin = x yMin = y if (normalRadians != null) { normalRadians.x = (atan2(yD - yC, xD - xC) - PI * 0.5).toFloat() } } if (d > dMax) { dMax = d xMax = x yMax = y if (normalRadians != null) { normalRadians.y = (atan2(yD - yC, xD - xC) - PI * 0.5).toFloat() } } } intersectionCount++ } else { xMin = x yMin = y xMax = x yMax = y intersectionCount++ if (normalRadians != null) { normalRadians.x = (atan2(yD - yC, xD - xC) - PI * 0.5).toFloat() normalRadians.y = normalRadians.x } break } } } xC = xD yC = yD } if (intersectionCount == 1) { if (intersectionPointA != null) { intersectionPointA.x = xMin.toFloat() intersectionPointA.y = yMin.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xMin.toFloat() intersectionPointB.y = yMin.toFloat() } if (normalRadians != null) { normalRadians.y = (normalRadians.x + PI).toFloat() } } else if (intersectionCount > 1) { intersectionCount++ if (intersectionPointA != null) { intersectionPointA.x = xMin.toFloat() intersectionPointA.y = yMin.toFloat() } if (intersectionPointB != null) { intersectionPointB.x = xMax.toFloat() intersectionPointB.y = yMax.toFloat() } } return intersectionCount } /** * @private */ var x: Double = 0.0 /** * @private */ var y: Double = 0.0 /** * - The polygon vertices. * @version DragonBones 5.1 * @language en_US */ /** * - 多边形顶点。 * @version DragonBones 5.1 * @language zh_CN */ var vertices: DoubleArray = DoubleArray(0) override fun _onClear(): Unit { super._onClear() this.type = BoundingBoxType.Polygon this.x = 0.0 this.y = 0.0 this.vertices = DoubleArray(0) } /** * @inheritDoc */ override fun containsPoint(pX: Double, pY: Double): Boolean { var isInSide = false if (pX >= this.x && pX <= this.width && pY >= this.y && pY <= this.height) { var iP = this.vertices.size - 2 for (i in 0 until this.vertices.size step 2) { val yA = this.vertices[iP + 1] val yB = this.vertices[i + 1] if ((yB < pY && yA >= pY) || (yA < pY && yB >= pY)) { val xA = this.vertices[iP] val xB = this.vertices[i] if ((pY - yB) * (xA - xB) / (yA - yB) + xB < pX) { isInSide = !isInSide } } iP = i } } return isInSide } /** * @inheritDoc */ override fun intersectsSegment( xA: Double, yA: Double, xB: Double, yB: Double, intersectionPointA: Point?, intersectionPointB: Point?, normalRadians: Point? ): Int { var intersectionCount = 0 if (RectangleBoundingBoxData.rectangleIntersectsSegment( xA, yA, xB, yB, this.x, this.y, this.x + this.width, this.y + this.height, null, null, null ) != 0 ) { intersectionCount = polygonIntersectsSegment( xA, yA, xB, yB, this.vertices, intersectionPointA, intersectionPointB, normalRadians ) } return intersectionCount } }
102
null
64
1,192
7fa8c9981d09c2ac3727799f3925363f1af82f45
18,928
korge
Apache License 2.0
server-core/src/main/kotlin/com/lightningkite/lightningserver/exceptions/DebugExceptionReporter.kt
lightningkite
512,032,499
false
null
package com.lightningkite.lightningserver.exceptions import com.lightningkite.lightningserver.core.ServerPath import com.lightningkite.lightningserver.http.get import com.lightningkite.lightningserver.logger import com.lightningkite.lightningserver.typed.typed import java.time.Instant object DebugExceptionReporter : ExceptionReporter { val previousErrors = ArrayList<Triple<Instant, Throwable, Any?>>() override suspend fun report(t: Throwable, context: Any?): Boolean { logger.debug( """ Exception Reported: ${t.message}: ${t.stackTraceToString()} """.trimIndent() ) previousErrors.add(Triple(Instant.now(), t, context)) while (previousErrors.size > 100) previousErrors.removeAt(0) return true } val exceptionListEndpoint = ServerPath.root.path("exceptions").get.typed( summary = "List Recent Exceptions", description = "Lists the most recent 100 exceptions to have occurred on this server", errorCases = listOf(), implementation = { user: Unit, input: Unit -> previousErrors.map { Triple( it.first, it.second.stackTraceToString(), it.third.toString() ) } } ) }
1
Kotlin
1
3
a6637772db8eeebd9a611e68fb19b96e9bfa2d77
1,308
lightning-server
MIT License
mall-service/mall-product/src/main/kotlin/com/github/product/vo/Catelog2Vo.kt
andochiwa
409,491,115
false
{"Kotlin": 5143282, "Java": 228835, "TSQL": 18775, "Dockerfile": 134}
package com.github.product.vo import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.ser.std.ToStringSerializer data class Catelog2Vo( @JsonSerialize(using = ToStringSerializer::class) var id: Long? = null, var name: String? = null, @JsonSerialize(using = ToStringSerializer::class) var catelog1Id: Long? = null, var catelog3List: List<Catelog3Vo>? = null, ) { data class Catelog3Vo( @JsonSerialize(using = ToStringSerializer::class) var id: Long? = null, var name: String? = null, @JsonSerialize(using = ToStringSerializer::class) var catelog2Id: Long? = null, ) }
0
Kotlin
1
2
5685d6749a924dddd79d7f06e222b425190c7168
696
Webflux-Mall-Back
MIT License
src/main/kotlin/com/toasttab/pulseman/state/protocol/protobuf/ProtobufState.kt
open-toast
399,150,014
false
null
/* * Copyright (c) 2021 Toast 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.toasttab.pulseman.state.protocol.protobuf import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.SnapshotStateList import com.toasttab.pulseman.AppState import com.toasttab.pulseman.AppStrings import com.toasttab.pulseman.entities.ReceivedMessages import com.toasttab.pulseman.entities.TabValuesV3 import com.toasttab.pulseman.pulsar.MessageHandlingClassImpl import com.toasttab.pulseman.state.JarManagement import com.toasttab.pulseman.state.JarManagementTabs import com.toasttab.pulseman.state.PulsarSettings import com.toasttab.pulseman.state.ReceiveMessage import com.toasttab.pulseman.state.onStateChange import com.toasttab.pulseman.view.protocol.protobuf.protobufUI import com.toasttab.pulseman.view.selectTabViewUI class ProtobufState( appState: AppState, initialSettings: TabValuesV3? = null, pulsarSettings: PulsarSettings, setUserFeedback: (String) -> Unit, onChange: () -> Unit ) { fun cleanUp() { receiveMessage.close() sendMessage.close() } private val protobufSelector = ProtobufMessageClassSelector( pulsarMessageJars = appState.pulsarMessageJars, setUserFeedback = setUserFeedback, onChange = onChange, initialSettings = initialSettings ) private val protobufJarManagement = JarManagement( appState.pulsarMessageJars, protobufSelector.selectedClass, setUserFeedback, onChange ) private val protobufJarManagementTab = JarManagementTabs( listOf( Pair(AppStrings.MESSAGE, protobufJarManagement) ) ) private val sendMessage = SendProtobufMessage( setUserFeedback = setUserFeedback, selectedClass = protobufSelector.selectedClass, pulsarSettings = pulsarSettings, initialSettings = initialSettings, onChange = onChange ) private val receivedMessages: SnapshotStateList<ReceivedMessages> = mutableStateListOf() private val messageHandling = MessageHandlingClassImpl( selectedProtoClass = protobufSelector.selectedClass, receivedMessages = receivedMessages, setUserFeedback = setUserFeedback ) private val receiveMessage = ReceiveMessage( setUserFeedback = setUserFeedback, pulsarSettings = pulsarSettings, receivedMessages = receivedMessages, messageHandling = messageHandling ) private val convertProtoBufMessage = ConvertProtobufMessage( setUserFeedback = setUserFeedback, selectedClass = protobufSelector.selectedClass, convertValue = initialSettings?.protobufSettings?.convertValue, convertType = initialSettings?.protobufSettings?.convertType, onChange = onChange ) fun toProtobufTabValues() = ProtobufTabValuesV3( code = sendMessage.currentCode(), selectedClass = protobufSelector.selectedClass.selected?.cls?.name, convertValue = convertProtoBufMessage.currentConvertValue(), convertType = convertProtoBufMessage.currentConvertType() ) private val selectedView = mutableStateOf(SelectedProtobufView.SEND) @ExperimentalFoundationApi fun getUI(): @Composable () -> Unit { return { protobufUI( selectedProtobufView = selectedView.value, messageClassSelectorUI = protobufSelector.getUI(), receiveMessageUI = receiveMessage.getUI(), sendMessageUI = sendMessage.getUI(), selectTabViewUI = { selectTabViewUI( listOf( Triple(AppStrings.SEND, SelectedProtobufView.SEND) { selectedView.onStateChange(SelectedProtobufView.SEND) }, Triple(AppStrings.RECEIVE, SelectedProtobufView.RECEIVE) { selectedView.onStateChange(SelectedProtobufView.RECEIVE) }, Triple(AppStrings.CONVERT, SelectedProtobufView.BYTE_CONVERT) { selectedView.onStateChange(SelectedProtobufView.BYTE_CONVERT) }, Triple(AppStrings.JARS, SelectedProtobufView.JAR_MANAGEMENT) { selectedView.onStateChange(SelectedProtobufView.JAR_MANAGEMENT) }, Triple(AppStrings.CLASS, SelectedProtobufView.PROTOBUF_CLASS) { selectedView.onStateChange(SelectedProtobufView.PROTOBUF_CLASS) } ), selectedView.value ) }, protobufJarManagementUI = protobufJarManagementTab.getUI(), byteConversionUI = convertProtoBufMessage.getUI() ) } } }
1
Kotlin
4
8
50cc0b09795b998ebc2697e9497d4ce9f0a5ff4c
5,788
pulseman
Apache License 2.0
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/presentation/send/confirm/ConfirmSendFragment.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.presentation.send.confirm import android.os.Bundle import android.view.View import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.core.os.bundleOf import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import jp.co.soramitsu.account.api.presentation.actions.setupExternalActions import jp.co.soramitsu.common.base.BaseComposeBottomSheetDialogFragment import jp.co.soramitsu.wallet.api.presentation.mixin.observeTransferChecks import jp.co.soramitsu.wallet.impl.domain.model.PhishingType import jp.co.soramitsu.wallet.impl.presentation.send.TransferDraft @AndroidEntryPoint class ConfirmSendFragment : BaseComposeBottomSheetDialogFragment<ConfirmSendViewModel>() { companion object { const val KEY_DRAFT = "KEY_DRAFT" const val KEY_PHISHING_TYPE = "KEY_PHISHING_TYPE" fun getBundle(transferDraft: TransferDraft, phishingType: PhishingType?) = bundleOf( KEY_DRAFT to transferDraft, KEY_PHISHING_TYPE to phishingType ) } override val viewModel: ConfirmSendViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupExternalActions(viewModel) observeTransferChecks(viewModel, viewModel::warningConfirmed, viewModel::errorAcknowledged) } @Composable override fun Content(padding: PaddingValues) { val state by viewModel.state.collectAsState() ConfirmSendContent( state = state, callback = viewModel ) } }
8
Kotlin
18
64
f1f913b342f644fdedd3843691f9434bb696d2d3
1,771
fearless-Android
Apache License 2.0
dnq/src/test/kotlin/kotlinx/dnq/incomingLinks/IncomingLinksConstraintsTest.kt
JetBrains
72,845,430
false
{"Kotlin": 1045011, "Java": 1363, "FreeMarker": 567}
/** * Copyright 2006 - 2024 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlinx.dnq.incomingLinks import com.google.common.truth.Truth.assertThat import jetbrains.exodus.database.exceptions.CantRemoveEntityException import jetbrains.exodus.database.exceptions.ConstraintsValidationException import jetbrains.exodus.entitystore.Entity import kotlinx.dnq.* import kotlinx.dnq.link.OnDeletePolicy.FAIL_PER_ENTITY import kotlinx.dnq.link.OnDeletePolicy.FAIL_PER_TYPE import kotlinx.dnq.util.getOldValue import org.junit.Test import kotlin.test.assertFailsWith class IncomingLinksConstraintsTest : DBTest() { class XdComment(entity: Entity) : XdEntity(entity) { companion object : XdNaturalEntityType<XdComment>() var author: XdUser by xdLink1(XdUser::comments, onTargetDelete = FAIL_PER_TYPE { linkedEntities, hasMore -> "User is author of ${linkedEntities.size} comments${if (hasMore) " and even more..." else ""}" }) } class XdIssue(entity: Entity) : XdEntity(entity) { companion object : XdNaturalEntityType<XdIssue>() var id by xdStringProp() var assignee by xdLink1(XdUser, onTargetDelete = FAIL_PER_ENTITY { "assignee of ${it.toXd<XdIssue>().id}" }) } class XdUser(entity: Entity) : XdEntity(entity), NamedXdEntity { companion object : XdNaturalEntityType<XdUser>() var login by xdRequiredStringProp() val comments by xdLink0_N(XdComment::author) override val displayName get() = getOldValue(XdUser::login) ?: login } override fun registerEntityTypes() { XdModel.registerNodes(XdIssue, XdComment, XdUser) } @Test fun deleteUserWhileIssueHasLinksDIE() { val user = transactional { XdUser.new { val user = this login = "looser" (1..11).forEach { index -> XdIssue.new { id = "ID-$index" assignee = user } } (1..4).forEach { XdComment.new { author = user } } } } val ex = assertFailsWith<ConstraintsValidationException> { transactional { user.delete() } } val integrityViolationExceptions = ex.causes assertThat(integrityViolationExceptions).hasSize(1) assertThat(integrityViolationExceptions.first()).isInstanceOf(CantRemoveEntityException::class.java) assertThat(integrityViolationExceptions.first() as CantRemoveEntityException) .hasMessageThat() .isEqualTo("Could not delete looser, because it is referenced as: " + "assignee of ID-1, assignee of ID-2, assignee of ID-3, assignee of ID-4, assignee of ID-5, " + "assignee of ID-6, assignee of ID-7, assignee of ID-8, assignee of ID-9, assignee of ID-10, " + "and more...; " + "User is author of 4 comments; ") } @Test fun deleteIssueWithLinkToUserNoDIE() { val issue = transactional { val user = XdUser.new { login = "me" } XdIssue.new { assignee = user } } transactional { issue.delete() } } }
7
Kotlin
32
86
feffc04edb59c406322ebb8e222579bfc49b836c
3,984
xodus-dnq
Apache License 2.0
mongodb-search-core/src/main/kotlin/io/github/yearnlune/search/core/operator/StartWithOperator.kt
yearnlune
512,971,890
false
{"Kotlin": 137605, "JavaScript": 1872, "TypeScript": 91}
package io.github.yearnlune.search.core.operator import io.github.yearnlune.search.core.extension.escapeSpecialRegexChars import org.springframework.data.mongodb.core.aggregation.AggregationExpression import org.springframework.data.mongodb.core.aggregation.StringOperators import org.springframework.data.mongodb.core.query.Criteria import java.util.regex.Pattern class ContainOperator( searchBy: String, values: List<Any> ) : SearchOperator(searchBy, values) { override fun appendExpression(criteria: Criteria): Criteria = criteria.regex( Pattern.compile( convertRegex(), Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE ) ) override fun buildExpression(): AggregationExpression { return StringOperators.RegexMatch .valueOf(searchBy) .regex(convertRegex()) .options("i") } private fun convertRegex(): String { return values.joinToString("|") { (it.toString()).escapeSpecialRegexChars() } } }
0
Kotlin
0
2
c3aa124d5c1f015e65c1a001b6e5c4c0e51a7ae8
1,022
mongodb-search
Apache License 2.0
server/src/test/kotlin/de/sambalmueslie/openevent/server/event/EventControllerTest.kt
sambalmueslie
270,265,994
false
{"Kotlin": 265865, "Dockerfile": 434, "Batchfile": 61}
package de.sambalmueslie.openevent.server.event import de.sambalmueslie.openevent.server.auth.AuthUtils.Companion.getAuthToken import de.sambalmueslie.openevent.server.event.api.Event import de.sambalmueslie.openevent.server.event.api.EventChangeRequest import de.sambalmueslie.openevent.server.event.api.Period import de.sambalmueslie.openevent.server.event.api.PeriodChangeRequest import de.sambalmueslie.openevent.server.item.ItemDescriptionUtil import de.sambalmueslie.openevent.server.location.LocationUtil import de.sambalmueslie.openevent.server.messaging.api.Message import de.sambalmueslie.openevent.server.user.UserUtils import de.sambalmueslie.openevent.server.user.db.UserData import de.sambalmueslie.openevent.server.user.db.UserRepository import de.sambalmueslie.openevent.test.BaseControllerTest import io.micronaut.core.type.Argument import io.micronaut.data.model.Page import io.micronaut.http.HttpRequest import io.micronaut.http.HttpStatus import io.micronaut.http.client.RxHttpClient import io.micronaut.http.client.annotation.Client import io.micronaut.test.extensions.junit5.annotation.MicronautTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.LocalDateTime import javax.inject.Inject @MicronautTest internal class EventControllerTest(userRepository: UserRepository): BaseControllerTest<Event>(userRepository) { private val baseUrl = "/api/event" private val start = LocalDateTime.of(2020, 12, 1, 20, 15) private val end = LocalDateTime.of(2020, 12, 1, 22, 30) @Test fun `create, read update and delete - admin`() { val item = ItemDescriptionUtil.getCreateRequest() val period = PeriodChangeRequest(start, end) val createRequest = HttpRequest.POST(baseUrl, EventChangeRequest(item, period, null)).bearerAuth(adminToken) val createResult = client.toBlocking().exchange(createRequest, Event::class.java) assertEquals(HttpStatus.OK, createResult.status) val createEvent = createResult.body()!! val description = ItemDescriptionUtil.getCreateDescription(createEvent.description.id) val event = Event(createEvent.id, Period(period.start, period.end), admin, description, null, true) assertEquals(event, createEvent) val getRequest = HttpRequest.GET<String>("$baseUrl/${event.id}").bearerAuth(adminToken) val getResult = client.toBlocking().exchange(getRequest, Event::class.java) assertEquals(HttpStatus.OK, getResult.status) assertEquals(event, getResult.body()) val getAllRequest = HttpRequest.GET<String>(baseUrl).bearerAuth(adminToken) val getAllResult = client.toBlocking().exchange(getAllRequest, Argument.of(Page::class.java, Event::class.java)) assertEquals(HttpStatus.OK, getAllResult.status) assertEquals(listOf(event), getAllResult.body()?.content) val locationRequest = LocationUtil.getCreateRequest() val updateRequest = HttpRequest.PUT("$baseUrl/${event.id}", EventChangeRequest(item, period, locationRequest)).bearerAuth(adminToken) val updateResult = client.toBlocking().exchange(updateRequest, Event::class.java) assertEquals(HttpStatus.OK, updateResult.status) val updateEvent = updateResult.body()!! val location = LocationUtil.getCreateLocation(updateEvent.location!!.id) assertEquals(Event(updateEvent.id, Period(period.start, period.end), admin, description, location, true), updateResult.body()) val deleteRequest = HttpRequest.DELETE<Any>("$baseUrl/${event.id}").bearerAuth(adminToken) val deleteResult = client.toBlocking().exchange(deleteRequest, Argument.STRING) assertEquals(HttpStatus.OK, deleteResult.status) val getAllEmptyResult = client.toBlocking() .exchange(HttpRequest.GET<String>(baseUrl).bearerAuth(adminToken), Argument.of(Page::class.java, Event::class.java)) assertEquals(HttpStatus.OK, getAllEmptyResult.status) assertEquals(emptyList<Event>(), getAllEmptyResult.body()?.content) } override fun getDefaultType() = Event::class.java }
0
Kotlin
0
1
053fb05dbe4242941659518f93dcac4c34b29126
3,936
open-event
Apache License 2.0
compiler/testData/diagnostics/tests/delegation/kt48546.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // FIR: KT-51648 object DelegateTest { var result = "" val f by lazy { result += <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM_WARNING!>f<!>.<!DEBUG_INFO_MISSING_UNRESOLVED!>toString<!>() // Compiler crash "hello" } } object DelegateTest2 { var result = "" val f by lazy { result += <!TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM_WARNING!>f<!> "hello" } }
157
null
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
461
kotlin
Apache License 2.0
src/main/kotlin/app/data/adapters/UserAdapter.kt
bed72
664,335,364
false
{"Kotlin": 39244}
package app.data.adapters import app.domain.core.models.UserInModel import app.external.database.entities.UserEntity class UserAdapter : Adapter<UserInModel, UserEntity> { override fun invoke(data: UserInModel) = UserEntity { name = data.name.value email = data.email.value } }
0
Kotlin
0
0
7bc27f4522b3576eccf107e6f5714345558e3330
304
KingsCross
Apache License 2.0
Problems/Beyond the word/src/Task.kt
Perl99
273,730,854
false
null
import java.util.Scanner fun main(args: Array<String>) { val input = Scanner(System.`in`) val word = input.next() for (l in 'a'..'z') { var found = false for (e in word) { if (l == e) { found = true break } } if (!found) { print(l) } } }
0
Kotlin
0
0
4afb085918697c41a5722f50e8a7bb65fcab0854
364
hyperskill-kotlin-ascii-text-signature
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionFilterController.kt
arkon
127,645,159
false
null
package eu.kanade.tachiyomi.ui.browse.extension import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.ui.setting.SettingsController import eu.kanade.tachiyomi.util.preference.minusAssign import eu.kanade.tachiyomi.util.preference.onChange import eu.kanade.tachiyomi.util.preference.plusAssign import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.LocaleHelper import uy.kohesive.injekt.injectLazy class ExtensionFilterController : SettingsController() { private val extensionManager: ExtensionManager by injectLazy() override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.label_extensions val activeLangs = preferences.enabledLanguages().get() val availableLangs = extensionManager.availableExtensions.groupBy { it.lang }.keys .sortedWith(compareBy({ it !in activeLangs }, { LocaleHelper.getSourceDisplayName(it, context) })) availableLangs.forEach { switchPreference { preferenceScreen.addPreference(this) title = LocaleHelper.getSourceDisplayName(it, context) isPersistent = false isChecked = it in activeLangs onChange { newValue -> if (newValue as Boolean) { preferences.enabledLanguages() += it } else { preferences.enabledLanguages() -= it } true } } } } }
92
null
58
9
2f07f226b8182699884262ac67139454d5b7070d
1,723
tachiyomi
Apache License 2.0
lib/multiservers/src/main/java/eu/kanade/tachiyomi/lib/multiservers/MultiServers.kt
adly98
827,820,894
false
null
package eu.kanade.tachiyomi.lib.multiservers import eu.kanade.tachiyomi.lib.multiservers.dto.IframeResponse import eu.kanade.tachiyomi.lib.multiservers.dto.LeechResponse import eu.kanade.tachiyomi.network.GET import kotlinx.serialization.json.Json import okhttp3.Headers import okhttp3.OkHttpClient class MultiServers(private val client: OkHttpClient, private val headers: Headers) { private val json = Json { ignoreUnknownKeys = true } fun extractedUrls(url: String): List<Provider> { val type = if ("/iframe/" in url) "mirror" else "leech" val newHeaders = headers.newBuilder() .add("X-Inertia", "true") .add("X-Inertia-Partial-Component", "files/$type/video") .add("X-Inertia-Partial-Data", "streams") .add("X-Inertia-Version", "933f5361ce18c71b82fa342f88de9634") .build() val iframe = client.newCall(GET(url, newHeaders)).execute().body.string() val urls = mutableListOf<Provider>() if (type == "mirror") { val resolved = json.decodeFromString<IframeResponse>(iframe) resolved.props.streams.data.forEach { val quality = it.resolution.substringAfter("x") + "p" val size = it.size.let(::convertSize) it.mirrors.forEach { mirror -> val link = if (mirror.link.startsWith("/")) "https:${mirror.link}" else mirror.link urls += Provider(link, mirror.driver, quality, size) } } } else { val resolved = json.decodeFromString<LeechResponse>(iframe) resolved.props.streams.data.forEach { val size = it.size.let(::convertSize) urls += Provider(it.file, "Leech", it.label.substringBefore(" "), size) } } return urls } data class Provider(val url: String, val name: String, val quality: String, val size: String) private fun convertSize(bits: Long): String { val bytes = bits / 8 return when { bytes >= 1 shl 30 -> "%.2f GB".format(bytes / (1 shl 30).toDouble()) bytes >= 1 shl 20 -> "%.2f MB".format(bytes / (1 shl 20).toDouble()) bytes >= 1 shl 10 -> "%.2f KB".format(bytes / (1 shl 10).toDouble()) else -> "$bytes bytes" } } }
0
null
0
2
174fc4d4d401bd18e0928a65a8ca6e3cb40bcde7
2,352
aniyomi-ar-extensions
Apache License 2.0
common/vector/src/main/kotlin/com/curtislb/adventofcode/common/vector/IntVector.kt
curtislb
226,797,689
false
null
package com.curtislb.adventofcode.common.vector import com.curtislb.adventofcode.common.iteration.nestedLoop import kotlin.math.sqrt /** * A vector with mutable [Int] components in a fixed dimensional space. * * @property components The integer component values of the vector. * * @constructor Creates a new instance of [IntVector] with the given [components]. */ class IntVector internal constructor(private val components: IntArray) { /** * The dimensionality of the vector. */ val dimension: Int get() = components.size /** * The x component of the vector, defined as the component value at dimension index 0. * * @throws IndexOutOfBoundsException If the [dimension] of the vector is 0. */ var x: Int get() = this[0] set(value) { this[0] = value } /** * The y component of the vector, defined as the component value at dimension index 1. * * @throws IndexOutOfBoundsException If the [dimension] of the vector is less than 2. */ var y: Int get() = this[1] set(value) { this[1] = value } /** * The z component of the vector, defined as the component value at dimension index 2. * * @throws IndexOutOfBoundsException If the [dimension] of the vector is less than 3. */ var z: Int get() = this[2] set(value) { this[2] = value } /** * Returns the value of the component at the given dimension [index] in the vector. */ operator fun get(index: Int): Int = components[index] /** * Updates the component at the given dimension [index] in the vector to the given [value]. */ operator fun set(index: Int, value: Int) { components[index] = value } /** * Returns a new vector, representing the component-wise sum of this vector and [other]. * * @throws IllegalArgumentException If this vector and [other] have different [dimension]s. */ operator fun plus(other: IntVector): IntVector { checkSameDimension(other) return if (isEmpty()) this else IntVector(components).apply { add(other) } } /** * Returns a new vector, representing the component-wise difference of this vector and [other]. * * @throws IllegalArgumentException If this vector and [other] have different [dimension]s. */ operator fun minus(other: IntVector): IntVector { checkSameDimension(other) return if (isEmpty()) this else IntVector(components).apply { subtract(other) } } /** * Returns a new vector, where each component is the additive inverse of the corresponding * component in this vector. */ operator fun unaryMinus(): IntVector = if (isEmpty()) { this } else { val negComponents = IntArray(components.size) { -components[it] } IntVector(negComponents) } /** * Returns the dot product of this vector and [other]. * * @throws IllegalArgumentException If this vector and [other] have different [dimension]s. */ infix fun dot(other: IntVector): Long { checkSameDimension(other) return components.withIndex().sumOf { it.value.toLong() * other[it.index].toLong() } } /** * Returns a new 3D vector, representing the cross product of this vector and [other]. * * @throws IllegalArgumentException If the [dimension] of this vector or [other] is not 3. */ infix fun cross(other: IntVector): IntVector { require(dimension == 3) { "Left vector dimensionality must be 3: $dimension" } require(other.dimension == 3) { "Right vector dimensionality must be 3: ${other.dimension}" } val crossX = (y * other.z) - (z * other.y) val crossY = (z * other.x) - (x * other.z) val crossZ = (x * other.y) - (y * other.x) return intVectorOf(crossX, crossY, crossZ) } /** * Adds each component of [other] to the corresponding component of this vector. * * @throws IllegalArgumentException If this vector and [other] have different [dimension]s. */ fun add(other: IntVector) { checkSameDimension(other) other.components.forEachIndexed { index, value -> components[index] += value } } /** * Subtracts each component of [other] from the corresponding component of this vector. * * @throws IllegalArgumentException If this vector and [other] have different [dimension]s. */ fun subtract(other: IntVector) { checkSameDimension(other) other.components.forEachIndexed { index, value -> components[index] -= value } } /** * Returns the sum of all components in the vector. */ fun componentSum(): Int = components.sum() /** * Returns the sum of all values produced by the [transform] function applied to each component * of the vector. */ inline fun componentSumOf(transform: (component: Int) -> Int): Int { var total = 0 for (index in 0 until dimension) { total += transform(this[index]) } return total } /** * Returns the length of the vector, measured from the origin in [dimension]-dimensional space. */ fun magnitude(): Double { val sumOfSquares = components.sumOf { component -> component.toDouble().let { it * it } } return sqrt(sumOfSquares) } /** * Returns a sequence of all other vectors with the same [dimension] as this vector whose * component values differ from this vector by at most 1. */ fun neighbors(): Sequence<IntVector> = sequence { nestedLoop(items = listOf(-1, 0, 1), levelCount = dimension) { offsets -> if (offsets.any { it != 0 }) { val neighbor = copy() offsets.forEachIndexed { index, offset -> neighbor[index] += offset } yield(neighbor) } false // Keep iterating } } /** * Returns a new vector with the same component values as this vector. */ fun copy(): IntVector = if (isEmpty()) this else IntVector(components.copyOf()) /** * Returns an array whose values correspond to the components of this vector. */ fun toArray(): IntArray = components.copyOf() /** * Returns a [LongVector] with the same component values as this vector. */ fun toLongVector(): LongVector = if (isEmpty()) { LongVector.EMPTY } else { val longComponents = LongArray(dimension) { components[it].toLong() } LongVector(longComponents) } override fun toString(): String = components.joinToString(prefix = "<", postfix = ">") override fun equals(other: Any?): Boolean = other is IntVector && components.contentEquals(other.components) override fun hashCode(): Int = components.contentHashCode() /** * Checks that this vector and [other] have the same dimensionality. * * @throws [IllegalArgumentException] If this vector and [other] have different [dimension]s. */ private fun checkSameDimension(other: IntVector) { require(dimension == other.dimension) { "Vectors must have the same dimensionality: $dimension != ${other.dimension}" } } /** * Returns `true` if the [dimension] of the vector is 0. */ private fun isEmpty(): Boolean = components.isEmpty() companion object { /** * The empty vector, which has a dimensionality of 0. */ val EMPTY: IntVector = IntVector(IntArray(0)) } } /** * Returns a new [IntVector] with the given [dimension] and all component values initialized to 0. */ fun IntVector(dimension: Int): IntVector = when { dimension == 0 -> IntVector.EMPTY dimension > 0 -> IntVector(IntArray(dimension)) else -> throw IllegalArgumentException("Vector dimensionality must be non-negative: $dimension") } /** * Returns a new [IntVector] with the given [dimension], where all component values are initialized * by calling the specified [init] function. */ fun IntVector(dimension: Int, init: (index: Int) -> Int) = when { dimension == 0 -> IntVector.EMPTY dimension > 0 -> IntVector(IntArray(dimension, init)) else -> throw IllegalArgumentException("Vector dimensionality must be non-negative: $dimension") } /** * Returns a new [IntVector] with the given [components]. */ fun intVectorOf(vararg components: Int): IntVector = if (components.isEmpty()) IntVector.EMPTY else IntVector(components) /** * Returns a new [IntVector] with initial component values that match the values of this array. */ fun IntArray.toVector(): IntVector = if (isEmpty()) IntVector.EMPTY else IntVector(copyOf())
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
8,906
AdventOfCode
MIT License
api/src/main/kotlin/io/github/msengbusch/unitsystem/scope/identifier/FromModule.kt
msengbusch
400,603,984
false
null
package io.github.msengbusch.unitsystem.scope.identifier import javax.inject.Qualifier @Qualifier annotation class FromModule
5
Kotlin
0
0
40183f3bc8db0aed84fcb993d6299c8e78ff4790
128
UnitSystem
MIT License
plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/assemble/PlotFacets.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.core.plot.builder.assemble import org.jetbrains.letsPlot.commons.interval.DoubleSpan import org.jetbrains.letsPlot.core.commons.data.SeriesUtil import org.jetbrains.letsPlot.core.plot.base.DataFrame import org.jetbrains.letsPlot.core.plot.base.data.DataFrameUtil import org.jetbrains.letsPlot.core.plot.builder.assemble.facet.FacetGrid abstract class PlotFacets { abstract val isDefined: Boolean abstract val colCount: Int abstract val rowCount: Int abstract val numTiles: Int abstract val variables: List<String> abstract val freeHScale: Boolean abstract val freeVScale: Boolean fun isFacettable(data: DataFrame): Boolean { return !data.isEmpty && data.rowCount() > 0 && variables.any { DataFrameUtil.hasVariable(data, it) } } /** * @return List of Dataframes, one Dataframe per tile. * Tiles are enumerated by rows, i.e.: * the index is computed like: row * nCols + col */ abstract fun dataByTile(data: DataFrame): List<DataFrame> /** * @return List of FacetTileInfo. * Tiles are enumerated by rows, i.e.: * the index is computed like: row * nCols + col */ abstract fun tileInfos(): List<FacetTileInfo> /** * @param domains Transformed X-mapped data ranges by tile. */ open fun adjustHDomains(domains: List<DoubleSpan?>): List<DoubleSpan?> = domains /** * @param domains Transformed Y-mapped data ranges by tile. */ open fun adjustVDomains(domains: List<DoubleSpan?>): List<DoubleSpan?> = domains abstract fun adjustFreeDisctereHDomainsByTile( domainBeforeFacets: List<Any>, domainByTile: List<Collection<Any>> ): List<List<Any>> abstract fun adjustFreeDisctereVDomainsByTile( domainBeforeFacets: List<Any>, domainByTile: List<Collection<Any>> ): List<List<Any>> companion object { const val DEF_ORDER_DIR = 0 // no ordering val DEF_FORMATTER: (Any) -> String = { it.toString() } val UNDEFINED: PlotFacets = FacetGrid(null, null, emptyList<Any>(), emptyList<Any>(), 1, 1) fun dataByLevelTuple( data: DataFrame, varNames: List<String>, varLevels: List<List<Any>> ): List<Pair<List<Any>, DataFrame>> { // This also checks invariants. val nameLevelTuples = createNameLevelTuples(varNames, varLevels) val indicesByVarByLevel = dataIndicesByVarByLevel(data, varNames, varLevels) val dataByLevelKey = ArrayList<Pair<List<Any>, DataFrame>>() for (nameLevelTuple in nameLevelTuples) { val topName = nameLevelTuple.first().first val topLevel = nameLevelTuple.first().second val indices = ArrayList(indicesByVarByLevel.getValue(topName).getValue(topLevel)) for (i in 1 until nameLevelTuple.size) { val name = nameLevelTuple[i].first val level = nameLevelTuple[i].second val levelIndices = indicesByVarByLevel.getValue(name).getValue(level) indices.retainAll(HashSet(levelIndices)) } val levelKey = nameLevelTuple.map { it.second } // build the data subset val levelData = data.slice(indices) dataByLevelKey.add(levelKey to levelData) } return dataByLevelKey } private fun dataIndicesByVarByLevel( data: DataFrame, varNames: List<String>, varLevels: List<List<Any>> ): Map<String, Map<Any, List<Int>>> { val indicesByVarByLevel = HashMap<String, Map<Any, List<Int>>>() for ((i, varName) in varNames.withIndex()) { val levels = varLevels[i] val indicesByLevel = HashMap<Any, List<Int>>() for (level in levels) { val indices = when { // 'empty' data in layers with no aes mapping (only constants) data.isEmpty -> emptyList() DataFrameUtil.hasVariable(data, varName) -> { val variable = DataFrameUtil.findVariableOrFail(data, varName) SeriesUtil.matchingIndices(data[variable], level) } else -> { // 'data' has no column 'varName' -> the entire data should be shown in each facet. (0 until data.rowCount()).toList() } } indicesByLevel[level] = indices } indicesByVarByLevel[varName] = indicesByLevel } return indicesByVarByLevel } fun createNameLevelTuples( varNames: List<String>, varLevels: List<List<Any>> ): List<List<Pair<String, Any>>> { require(varNames.isNotEmpty()) { "Empty list of facet variables." } require(varNames.size == varNames.distinct().size) { "Facet variables must be distinct, were: $varNames." } check(varNames.size == varLevels.size) return createNameLevelTuplesIntern(varNames, varLevels) } private fun createNameLevelTuplesIntern( varNames: List<String>, varLevels: List<List<Any>> ): List<List<Pair<String, Any>>> { val name = varNames.first() val levels = varLevels.first() val levelKeys = ArrayList<List<Pair<String, Any>>>() for (level in levels) { if (varNames.size > 1) { val subKeys = createNameLevelTuples( varNames.subList(1, varNames.size), varLevels.subList(1, varLevels.size) ) for (subKey in subKeys) { levelKeys.add(listOf(name to level) + subKey) } } else { // exit levelKeys.add(listOf(name to level)) } } return levelKeys } fun reorderLevels( varNames: List<String>, varLevels: List<List<Any>>, ordering: List<Int> ): List<List<Any>> { val orderingByFacet = varNames.zip(ordering).toMap() val result = ArrayList<List<Any>>() for ((i, name) in varNames.withIndex()) { if (i >= varLevels.size) break result.add(reorderVarLevels(name, varLevels[i], orderingByFacet.getValue(name))) } return result } fun reorderVarLevels( name: String?, levels: List<Any>, order: Int ): List<Any> { if (name == null) return levels // We expect either a list of Doubles or a list of Strings. @Suppress("UNCHECKED_CAST") levels as List<Comparable<Any>> return when { order <= -1 -> levels.sortedDescending() order >= 1 -> levels.sorted() else -> levels // not ordered } } } class FacetTileInfo constructor( val col: Int, val row: Int, val colLabs: List<String>, val rowLab: String?, val hasHAxis: Boolean, val hasVAxis: Boolean, val isBottom: Boolean, // true is the tile is the last one in its respective column. val trueIndex: Int // tile index before re-ordering (in facet wrap) ) { override fun toString(): String { return "FacetTileInfo(col=$col, row=$row, colLabs=$colLabs, rowLab=$rowLab)" } } }
97
Kotlin
51
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
8,099
lets-plot
MIT License
app/src/main/java/com/antonioleiva/weatherapp/data/db/DbClasses.kt
15102391937
142,841,471
true
{"Kotlin": 31026}
package com.antonioleiva.weatherapp.data.db import java.util.* class DBCityForecast(val map: MutableMap<String, Any?>, val dailyForecastDB: List<DBDayForecast>) { var _id: Long by map var city: String by map var country: String by map constructor(id: Long, city: String, country: String, dailyForecastDB: List<DBDayForecast>) : this(HashMap(), dailyForecastDB) { this._id = id this.city = city this.country = country } } class DBDayForecast(var map: MutableMap<String, Any?>) { var _id: Long by map var date: Long by map var description: String by map var high: Int by map var low: Int by map var iconUrl: String by map var cityId: Long by map constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long) : this(HashMap()) { this.date = date this.description = description this.high = high this.low = low this.iconUrl = iconUrl this.cityId = cityId } }
0
Kotlin
0
0
f302f92280cc6cb8a3f81c783930bbeb91bc636b
1,021
Kotlin-for-Android-Developers
Apache License 2.0
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/VisualShaderNodeBooleanConstant.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD package godot import godot.icalls._icall_Boolean import godot.icalls._icall_Unit_Boolean import godot.internal.utils.getMethodBind import godot.internal.utils.invokeConstructor import kotlin.Boolean import kotlinx.cinterop.COpaquePointer open class VisualShaderNodeBooleanConstant : VisualShaderNode() { open var constant: Boolean get() { val mb = getMethodBind("VisualShaderNodeBooleanConstant","get_constant") return _icall_Boolean(mb, this.ptr) } set(value) { val mb = getMethodBind("VisualShaderNodeBooleanConstant","set_constant") _icall_Unit_Boolean(mb, this.ptr, value) } override fun __new(): COpaquePointer = invokeConstructor("VisualShaderNodeBooleanConstant", "VisualShaderNodeBooleanConstant") open fun getConstant(): Boolean { val mb = getMethodBind("VisualShaderNodeBooleanConstant","get_constant") return _icall_Boolean( mb, this.ptr) } open fun setConstant(value: Boolean) { val mb = getMethodBind("VisualShaderNodeBooleanConstant","set_constant") _icall_Unit_Boolean( mb, this.ptr, value) } }
17
Kotlin
17
286
8d51f614df62a97f16e800e6635ea39e7eb1fd62
1,193
godot-kotlin-native
MIT License
core/src/main/java/top/xuqingquan/utils/ManifestParser.kt
xuqingquan1995
196,393,794
false
{"Gradle Kotlin DSL": 3, "Java Properties": 2, "YAML": 1, "Shell": 1, "Text": 2, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Gradle": 2, "Java": 21, "XML": 32, "Kotlin": 76, "TOML": 1}
package top.xuqingquan.utils import android.content.Context import android.content.pm.PackageManager import top.xuqingquan.integration.LifecycleConfig import java.util.ArrayList /** * Created by 许清泉 on 2019/4/14 22:59 */ internal class ManifestParser(private val context: Context) { companion object { private const val MODULE_VALUE = "LifecycleConfig" } fun parse(): List<LifecycleConfig> { val modules = ArrayList<LifecycleConfig>() try { val appInfo = context.packageManager.getApplicationInfo( context.packageName, PackageManager.GET_META_DATA ) if (appInfo.metaData != null) { for (key in appInfo.metaData.keySet()) { if (MODULE_VALUE == appInfo.metaData.getString(key)) { modules.add(parseModule(key)) } } } } catch (e: PackageManager.NameNotFoundException) { throw RuntimeException("Unable to find metadata to parse LifecycleConfig", e) } return modules } private fun parseModule(className: String): LifecycleConfig { val clazz: Class<*> try { clazz = Class.forName(className) } catch (e: ClassNotFoundException) { throw IllegalArgumentException("Unable to find LifecycleConfig implementation", e) } val module: Any try { module = clazz.getDeclaredConstructor().newInstance() } catch (e: InstantiationException) { throw RuntimeException("Unable to instantiate LifecycleConfig implementation for $clazz", e) } catch (e: IllegalAccessException) { throw RuntimeException("Unable to instantiate LifecycleConfig implementation for $clazz", e) } if (module !is LifecycleConfig) { throw RuntimeException("Expected instanceof LifecycleConfig, but found: $module") } return module } }
1
null
1
1
44f5b2597e78ba752b6e67f7c35762fe3a056c09
2,000
Scaffold
MIT License
src/test/kotlin/TestGreetingPlugin.kt
MatteoCaval
445,562,187
false
{"Kotlin": 8237}
import io.kotest.core.spec.style.FreeSpec import io.kotest.engine.spec.tempdir import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import java.io.File class TestGreetingPlugin : FreeSpec({ val manifest = Thread.currentThread().contextClassLoader .getResource("plugin-classpath.txt") ?.readText() require(manifest != null) { "Could not load manifest" } val tempDir = tempdir() tempDir.mkdirs() val buildGradleKts = with(File(tempDir, "build.gradle.kts")) { writeText( """ plugins { id("it.unibo.lss.greetings") } greetings { greetWith { "Ciao" } } """.trimIndent() ) } // create a gradle runner val result = GradleRunner.create() .withPluginClasspath(manifest.lines().map { File(it) }) .withProjectDir(tempDir) .withArguments("greet") .build() println(result.output) result.tasks.forEach { it.outcome shouldBe TaskOutcome.SUCCESS } result.tasks.size shouldBe 1 result.output shouldContain "Ciao" })
0
Kotlin
0
0
1019bf4c7170bbb68db241b022aa8c1a8cbcd91f
1,353
lss-plugin-example
MIT License
doctor-plugin/src/integrationTest/java/com/osacky/doctor/TestIntegrationTest.kt
runningcode
200,733,919
false
{"Kotlin": 140166, "Java": 824}
package com.osacky.doctor import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class TestIntegrationTest { @get:Rule val testProjectRoot = TemporaryFolder() @Test fun testIgnoreOnEmptyDirectories() { testProjectRoot.writeBuildGradle( """ |plugins { | id "com.osacky.doctor" |} |doctor { | disallowMultipleDaemons = false | javaHome { | ensureJavaHomeMatches = false | } | failOnEmptyDirectories = true | warnWhenNotUsingParallelGC = false |} """.trimMargin("|"), ) val fixtureName = "java-fixture" testProjectRoot.newFile("settings.gradle").writeText("include '$fixtureName'") testProjectRoot.setupFixture(fixtureName) testProjectRoot.newFolder("java-fixture", "src", "main", "java", "com", "foo") val result = GradleRunner .create() .withProjectDir(testProjectRoot.root) .withGradleVersion("6.7.1") .withPluginClasspath() .withArguments("assemble") .buildAndFail() assertThat(result.output).contains("Empty src dir(s) found. This causes build cache misses. Run the following command to fix it.") } @Test fun testDirectoriesIgnoredIn6dot8() { testProjectRoot.writeBuildGradle( """ |plugins { | id "com.osacky.doctor" |} |doctor { | disallowMultipleDaemons = false | javaHome { | ensureJavaHomeMatches = false | } | failOnEmptyDirectories = true | warnWhenNotUsingParallelGC = false |} """.trimMargin("|"), ) val fixtureName = "java-fixture" testProjectRoot.newFile("settings.gradle").writeText("include '$fixtureName'") testProjectRoot.setupFixture(fixtureName) testProjectRoot.newFolder("java-fixture", "src", "main", "java", "com", "foo") val result = GradleRunner .create() .withProjectDir(testProjectRoot.root) .withGradleVersion("6.8") .withPluginClasspath() .withArguments("assemble") .build() assertThat(result.output).contains("SUCCESS") } @Test fun cleanDependencyFailsBuild() { projectWithCleanDependency(disallowCleanTaskDependencies = true) val result = GradleRunner .create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withArguments("clean") .withGradleVersion("7.3.3") .buildAndFail() assertThat(result.output).contains( """ | > =============================== Gradle Doctor Prescriptions ============================================ | | Adding dependencies to the clean task could cause unexpected build outcomes. | | | Please remove the dependency from task ':clean' on the following tasks: [foo]. | | | See github.com/gradle/gradle/issues/2488 for more information. | | ======================================================================================================== """.trimMargin("|"), ) } @Test fun cleanDependencyDisabledSucceeds() { projectWithCleanDependency(disallowCleanTaskDependencies = false) val result = GradleRunner .create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withArguments("clean") .build() assertThat(result.output).contains("BUILD SUCCESSFUL") } @Test fun cleanDependency74Succeeds() { projectWithCleanDependency(disallowCleanTaskDependencies = true) val result = GradleRunner .create() .withProjectDir(testProjectRoot.root) .withPluginClasspath() .withGradleVersion("7.4") .withArguments("clean") .build() assertThat(result.output).contains("BUILD SUCCESSFUL") } fun projectWithCleanDependency(disallowCleanTaskDependencies: Boolean) { testProjectRoot.writeBuildGradle( """ plugins { id "com.osacky.doctor" id 'java-library' } doctor { disallowMultipleDaemons = false javaHome { ensureJavaHomeMatches = false } warnWhenNotUsingParallelGC = false disallowCleanTaskDependencies = $disallowCleanTaskDependencies } tasks.register('foo') { doFirst { println 'foo' } } tasks.withType(Delete).configureEach { println 'configuring delete' dependsOn 'foo' } """.trimIndent(), ) } }
38
Kotlin
48
736
09ee630bd6ca39e9c16acd01c0ae343732c19f9e
5,617
gradle-doctor
Apache License 2.0
androidApp/src/main/java/com/msabhi/androidApp/counter/entities/CounterAction.kt
abhimuktheeswarar
380,572,734
false
null
/* * Copyright (C) 2021 Abhi Muktheeswarar * * 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.msabhi.androidApp.counter.entities import com.msabhi.flywheel.Action sealed interface CounterAction : Action { object IncrementAction : CounterAction object DecrementAction : CounterAction object ResetAction : CounterAction data class ForceUpdateAction(val count: Int) : CounterAction }
2
Objective-C
4
37
7691042c1715ccff725349de7c3c489d293b3e3c
926
Flywheel
Apache License 2.0
kafkistry-sql/src/main/kotlin/com/infobip/kafkistry/sql/sources/ConsumerGroupsDataSource.kt
infobip
456,885,171
false
null
@file:Suppress("JpaDataSourceORMInspection") package com.infobip.kafkistry.sql.sources import com.infobip.kafkistry.kafka.ConsumerGroupStatus import com.infobip.kafkistry.model.KafkaClusterIdentifier import com.infobip.kafkistry.model.ConsumerGroupId import com.infobip.kafkistry.model.TopicName import com.infobip.kafkistry.service.consumers.ConsumersService import com.infobip.kafkistry.service.consumers.KafkaConsumerGroup import com.infobip.kafkistry.service.consumers.LagStatus import com.infobip.kafkistry.sql.SqlDataSource import org.springframework.stereotype.Component import java.io.Serializable import jakarta.persistence.* @Component class ConsumerGroupsDataSource( private val consumersService: ConsumersService, ) : SqlDataSource<Group> { override fun modelAnnotatedClass(): Class<Group> = Group::class.java override fun supplyEntities(): List<Group> { val allConsumersData = consumersService.allConsumersData() return allConsumersData.clustersGroups.map { clusterGroups -> mapConsumerGroup(clusterGroups.clusterIdentifier, clusterGroups.consumerGroup) } } private fun mapConsumerGroup( clusterIdentifier: KafkaClusterIdentifier, consumerGroup: KafkaConsumerGroup ): Group { return Group().apply { id = ClusterConsumerGroupId().apply { cluster = clusterIdentifier groupId = consumerGroup.groupId } status = consumerGroup.status assignor = consumerGroup.partitionAssignor totalLag = consumerGroup.lag.amount assignments = consumerGroup.topicMembers.flatMap { topicMembers -> topicMembers.partitionMembers.map { member -> ConsumerGroupAssignment().apply { cluster = clusterIdentifier topic = topicMembers.topicName partition = member.partition lag = member.lag.amount offset = member.offset lagPercentage = member.lag.percentage status = member.lag.status memberId = member.member?.memberId clientId = member.member?.clientId memberHost = member.member?.host } } } } } } @Embeddable class ClusterConsumerGroupId : Serializable { lateinit var cluster: KafkaClusterIdentifier lateinit var groupId: ConsumerGroupId } @Entity @Table(name = "Groups") class Group { @EmbeddedId lateinit var id: ClusterConsumerGroupId @Enumerated(EnumType.STRING) lateinit var status: ConsumerGroupStatus lateinit var assignor: String var totalLag: Long? = null @ElementCollection @JoinTable(name = "Groups_Assignments") lateinit var assignments: List<ConsumerGroupAssignment> } @Embeddable class ConsumerGroupAssignment { lateinit var cluster: KafkaClusterIdentifier lateinit var topic: TopicName @Column(nullable = false) var partition: Int? = null var lag: Long? = null var offset: Long? = null var lagPercentage: Double? = null @Enumerated(EnumType.STRING) lateinit var status: LagStatus var memberId: String? = null var clientId: String? = null var memberHost: String? = null }
2
null
6
42
06616ab58ca8bf7708fb8c62d584394f4fa303ab
3,410
kafkistry
Apache License 2.0
presentation/src/main/java/com/duccnv/cleanmoviedb/base/BaseActivity.kt
duccnv-1684
260,399,969
false
null
package com.duccnv.cleanmoviedb.base import dagger.android.support.DaggerAppCompatActivity abstract class BaseActivity : DaggerAppCompatActivity()
1
Kotlin
1
1
d157e2f275b20c8601766ce36c8a91841c133faa
148
clean_movie_db
Apache License 2.0
filepicker/src/main/java/me/rosuh/filepicker/config/DefaultFileDetector.kt
rosuH
158,897,052
false
{"Gradle": 4, "Markdown": 4, "YAML": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 4, "XML": 54, "Kotlin": 42}
package me.rosuh.filepicker.config import me.rosuh.filepicker.bean.FileItemBeanImpl import me.rosuh.filepicker.filetype.* /** * * @author rosu * @date 2018/11/27 */ class DefaultFileDetector : AbstractFileDetector() { var enableCustomTypes: Boolean = false private set private val allDefaultFileType: ArrayList<FileType> by lazy { ArrayList<FileType>() } fun registerDefaultTypes() { with(allDefaultFileType) { clear() add(AudioFileType()) add(RasterImageFileType()) add(CompressedFileType()) add(DataBaseFileType()) add(ExecutableFileType()) add(FontFileType()) add(PageLayoutFileType()) add(TextFileType()) add(VideoFileType()) add(WebFileType()) } enableCustomTypes = false } /** * @author <EMAIL> * @date 2020/9/16 * save user's custom file types */ fun registerCustomTypes(customFileTypes: ArrayList<FileType>) { allDefaultFileType.clear() allDefaultFileType.addAll(customFileTypes) enableCustomTypes = true } fun clear(){ allDefaultFileType.clear() enableCustomTypes = false } override fun fillFileType(itemBeanImpl: FileItemBeanImpl): FileItemBeanImpl { for (type in allDefaultFileType) { if (type.verify(itemBeanImpl.fileName)) { itemBeanImpl.fileType = type break } } return itemBeanImpl } }
10
Kotlin
85
945
3cb6deca053dea5a6a7c4068f39ad7c34f30b014
1,572
AndroidFilePicker
MIT License
core/src/main/kotlin/org/tenkiv/kuantify/gate/control/output/Output.kt
Tenkiv
183,814,098
false
null
/* * Copyright 2019 Tenkiv, Inc. * * 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.tenkiv.kuantify.gate.control.output import org.tenkiv.kuantify.* import org.tenkiv.kuantify.data.* import org.tenkiv.kuantify.gate.* import org.tenkiv.kuantify.gate.control.* import org.tenkiv.physikal.core.* import tec.units.indriya.* import tec.units.indriya.unit.Units.* import javax.measure.* import javax.measure.quantity.* /** * Interface defining classes which act as outputs and send controls or signals to devices. * * @param T The type of signal given by this output. */ public interface Output<T : DaqcValue> : IOStrand<T>, ControlGate<T> /** * An [Output] which sends signals in the form of a [DaqcQuantity]. * * @param Q The type of signal sent by this Output. */ public interface QuantityOutput<Q : Quantity<Q>> : Output<DaqcQuantity<Q>> { /** * Adjust the output by applying a function to the current setting. For example double it or square it. * This will fail with a return [AdjustmentAttempt.UninitialisedSetting] if there hasn't yet been a setting provided * for this [Output] */ public fun adjustOutputOrFail( adjustment: (Double) -> Double ): SettingViability { val setting = valueOrNull return if (setting != null) { setOutput(adjustment(setting.value.valueToDouble())(setting.value.unit)) } else { SettingViability.Unviable( UninitialisedSettingException( this ) ) } } /** * Adjust the output by applying a function to the current setting. For example double it or square it. * If there hasn't yet been a setting provided for this output, this function will suspend until there is one. */ public suspend fun adjustOutput( adjustment: (Double) -> Double ): SettingViability = setOutput(adjustment(getValue().value.valueToDouble())(getValue().value.unit)) } /** * Sets the signal of this output to the correct value as a [DaqcQuantity]. * * @param setting The signal to set as the output. */ public fun <Q : Quantity<Q>> QuantityOutput<Q>.setOutput( setting: ComparableQuantity<Q> ) = setOutput(setting.toDaqc()) /** * An [Output] whose type extends both [DaqcValue] and [Comparable] so it can be used in the default learning module. */ public interface RangedOutput<T> : Output<T>, RangedIOStrand<T> where T : DaqcValue, T : Comparable<T> /** * A [RangedOutput] which uses the [BinaryState] type. */ public interface BinaryStateOutput : RangedOutput<BinaryState> { override val valueRange get() = BinaryState.range } public interface RangedQuantityOutput<Q : Quantity<Q>> : RangedOutput<DaqcQuantity<Q>>, QuantityOutput<Q> { public fun increaseByRatioOfRange( ratioIncrease: Double ): SettingViability { val setting = valueOrNull return if (setting != null) { val newSetting = setting.value * ratioIncrease if (newSetting.toDaqc() in valueRange) { setOutput(setting.value * ratioIncrease) } else { SettingViability.Unviable( SettingOutOfRangeException( this ) ) } } else { SettingViability.Unviable( UninitialisedSettingException( this ) ) } } public fun decreaseByRatioOfRange( ratioDecrease: Double ): SettingViability = increaseByRatioOfRange(-ratioDecrease) /** * Increase the setting by a percentage of the allowable range for this output. */ public fun increaseByPercentOfRange( percentIncrease: ComparableQuantity<Dimensionless> ): SettingViability = increaseByRatioOfRange(percentIncrease.toDoubleIn(PERCENT) / 100) /** * Decrease the setting by a percentage of the allowable range for this output. */ public fun decreaseByPercentOfRange( percentDecrease: ComparableQuantity<Dimensionless> ): SettingViability = decreaseByRatioOfRange(percentDecrease.toDoubleIn(PERCENT) / 100) public fun setOutputToPercentMaximum( percent: ComparableQuantity<Dimensionless> ): SettingViability = setOutputToRatioMaximum(percent.toDoubleIn(PERCENT) / 100) public fun setOutputToRatioMaximum( ratio: Double ): SettingViability = setOutput(ratioOfRange(ratio)) /** * Sets this output to random setting within the allowable range. */ public fun setOutputToRandom(): SettingViability { val random = Math.random() val setting = ratioOfRange(random) return setOutput(setting) } private fun ratioOfRange(ratio: Double): ComparableQuantity<Q> { val min = valueRange.start.toDoubleInSystemUnit() val max = valueRange.endInclusive.toDoubleInSystemUnit() return (ratio * (max - min) + min)(valueRange.start.unit.systemUnit) } } public class RqoAdapter<Q : Quantity<Q>> internal constructor( private val output: QuantityOutput<Q>, public override val valueRange: ClosedRange<DaqcQuantity<Q>> ) : RangedQuantityOutput<Q>, QuantityOutput<Q> by output { public override fun setOutput(setting: DaqcQuantity<Q>): SettingViability { val inRange = setting in valueRange return if (!inRange) { SettingViability.Unviable( SettingOutOfRangeException( this ) ) } else { output.setOutput(setting) } } //TODO: ToString, equals, hashcode } /** * Converts a [QuantityOutput] to a [RqoAdapter] so it can be used in the default learning module. * * @param valueRange The range of acceptable output values. */ public fun <Q : Quantity<Q>> QuantityOutput<Q>.toRangedOutput(valueRange: ClosedRange<DaqcQuantity<Q>>) = RqoAdapter(this, valueRange)
0
Kotlin
0
4
cc774f93c7d47f84c4e22aeb032e48451478beb8
7,028
kuantify
MIT License
modules/ktorium-datetime/src/commonMain/kotlinX/LocalDate.kt
ktorium
316,943,260
false
{"Kotlin": 75228, "JavaScript": 203}
@file:Suppress("PackageDirectoryMismatch") package org.ktorium.datetime import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.plus import org.ktorium.kotlin.ExperimentalSince import org.ktorium.kotlin.KtoriumVersion.Unreleased @ExperimentalSince(Unreleased) public fun LocalDate.Companion.parseOrNull(isoString: String): LocalDate? = runCatching { parse(isoString) }.getOrNull() /** * Get the current date using the specified [timeZone]. */ @ExperimentalSince(Unreleased) public fun LocalDate.Companion.now(timeZone: TimeZone): LocalDate = LocalDateTime.now(timeZone).date /** * Returns a new LocalDate with specified [days] added. */ @ExperimentalSince(Unreleased) public fun LocalDate.plusDays(days: Int): LocalDate = plus(days, DateTimeUnit.DAY) /** * Returns a new LocalDate with the day of month set to the specified [day] */ @ExperimentalSince(Unreleased) public fun LocalDate.withDayOfMonth(day: Int): LocalDate = LocalDate(year, month, day) /** * Returns a new [LocalDateTime] set to the start of the day. */ @ExperimentalSince(Unreleased) public fun LocalDate.asStartOfDay(): LocalDateTime = LocalDateTime(year, month, dayOfMonth, 0, 0, 0, 0) @ExperimentalSince(Unreleased) public fun LocalDate.asEndOfDay(): LocalDateTime = LocalDateTime(this, LocalTime.MAX)
0
Kotlin
0
1
019ed2c96f545f5a725053d37074bca462efb4d5
1,431
ktorium-kotlin
Apache License 2.0
recorder-core/src/main/java/me/shetj/recorder/core/BaseRecorder.kt
SheTieJun
207,213,419
false
null
/* * MIT License * * Copyright (c) 2019 SheTieJun * * 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 me.shetj.recorder.core import android.content.Context import android.media.AudioFormat import android.media.MediaRecorder import android.media.audiofx.AcousticEchoCanceler import android.media.audiofx.AutomaticGainControl import android.media.audiofx.NoiseSuppressor import android.net.Uri import android.os.Handler import android.os.Looper import android.os.Message import android.text.TextUtils import android.util.Log import androidx.annotation.FloatRange import androidx.annotation.IntRange import java.io.File import kotlin.math.max import me.shetj.ndk.lame.LameUtils import me.shetj.player.PlayerListener abstract class BaseRecorder { //region 录音的方式 /来源 Record Type enum class RecorderType { SIM, // 只转码MP3 MIX, // 背景音乐(需要混音+转码Mp3,所以较慢) ST // 变音(需要变音+转码Mp3,所以较慢) } //endregion Record Type protected var mAudioSource = MediaRecorder.AudioSource.VOICE_COMMUNICATION protected var mChannelConfig = AudioFormat.CHANNEL_IN_MONO // defaultLameInChannel =1 protected var mLameInChannel = 1 // 声道数量 /** * 设置LameMp3音频质量,但是好像LAME已经不使用它了,3.90 开始就弃用了,当前版本是3.100 */ protected var mMp3Quality = 3 /** * * 比特率越高,传送的数据越大,音质越好 * * * *16Kbps = 电话音质 * * 24Kbps = 增加电话音质、短波广播、长波广播、欧洲制式中波广播 * * 40Kbps = 美国制式中波广播 * * 56Kbps = 话音 * * 64Kbps = 增加话音(手机铃声最佳比特率设定值、手机单声道MP3播放器最佳设定值) * * 112Kbps = FM调频立体声广播 * * 128Kbps = 磁带(手机立体声MP3播放器最佳设定值、低档MP3播放器最佳设定值) * * 160Kbps = HIFI 高保真(中高档MP3播放器最佳设定值) * * 192Kbps = CD(高档MP3播放器最佳设定值) * * 256Kbps = Studio音乐工作室(音乐发烧友适用) * * 实际上随着技术的进步,比特率也越来越高,MP3的最高比特率为320Kbps,但一些格式可以达到更高的比特率和更高的音质。 * * 比如正逐渐兴起的APE音频格式,能够提供真正发烧级的无损音质和相对于WAV格式更小的体积,其比特率通常为550kbps-----950kbps。 * * * * 32 太低,(96,128) 比较合适,在往上会导致文件很大 */ protected var mLameMp3BitRate = 96 /** * * 采样频率越高, 声音越接近原始数据。 * * * * 44,100 Hz - 音频 CD, 也常用于 MPEG-1 音频(VCD, SVCD, MP3)所用采样率 * * 47,250 Hz - Nippon Columbia (Denon)开发的世界上第一个商用 PCM 录音机所用采样率 * * 48,000 Hz - miniDV、数字电视、DVD、DAT、电影和专业音频所用的数字声音所用采样率 * * 50,400 Hz - 三菱 X-80 数字录音机所用所用采样率 * * * * 48000 一般就够了,太大也会影响文件的大小 */ protected var mSamplingRate = 48000 protected var is2Channel = false // 默认是单声道 //设置过滤器 protected var lowpassFreq: Int = -1 //高于这个频率的声音会被截除 hz protected var highpassFreq: Int = -1//低于这个频率的声音会被截除 hz protected var openVBR = false //region 背景音乐相关 /** * 音量变化监听 */ protected var volumeConfig: VolumeConfig? = null //endregion 背景音乐相关 /** * 文件输出,中途可以替换[updateDataEncode] */ protected var mRecordFile: File? = null // protected var mRecordListener: RecordListener? = null protected var mPermissionListener: PermissionListener? = null //region 系统自带的去噪音,增强以及回音问题 private var mNoiseSuppressor: NoiseSuppressor? = null private var mAcousticEchoCanceler: AcousticEchoCanceler? = null private var mAutomaticGainControl: AutomaticGainControl? = null //endregion 系统自带的去噪音,增强以及回音问题 /** *最大时间 */ protected var mMaxTime: Long = 3600000 // 提醒时间 protected var mRemindTime = (3600000 - 10000).toLong() /** * 是否是自动触发最大时间完成了录音 */ protected var isAutoComplete = false //region 录音的状态,声音和时间 /** * 录音的声音大小 */ protected var mVolume: Int = 0 /** * 记录是否暂停 */ protected var backgroundMusicIsPlay: Boolean = false /** * 背景音乐是否循环 */ protected var bgmIsLoop: Boolean = true /** * 是否需要提醒快到时间 */ protected var isRemind: Boolean = true /** * 是否继续输出在文件末尾录制 */ protected var isContinue = false /** * 录音线程 */ protected var recordThread: Thread? = null /** * 录音是否暂停 */ protected var isPause: Boolean = true protected var isDebug = false /** 声音增强,不建议使用 */ protected var wax = 1f /** * 背景音乐的声音大小(0~1.0) */ protected var bgLevel: Float = 0.3f /** * 录音Recorder 是否在活动,暂停的时候 isActive 还是true,只有录音结束了才会为false */ var isActive = false protected set /** * 当前录音状态 */ var state = RecordState.STOPPED protected set /** * 已录制时间 */ var duration = 0L protected set //endregion 录音的状态和时间 //region public method 公开的方法 val realVolume: Int get() = max(mVolume, 0) protected val handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { super.handleMessage(msg) when (msg.what) { HANDLER_RECORDING -> { if (mRecordListener != null && state == RecordState.RECORDING) { logInfo( "Recording: mDuration = $duration ,volume = " + "$realVolume and state is recording = ${state == RecordState.RECORDING}" ) // 录制回调 mRecordListener!!.onRecording(duration, realVolume) // 提示快到录音时间了 if (isRemind && duration > mRemindTime) { isRemind = false mRecordListener!!.onRemind(duration) } } } HANDLER_START -> { logInfo("started: mDuration = $duration , mRemindTime = $mRemindTime") if (mRecordListener != null) { mRecordListener!!.onStart() } } HANDLER_RESUME -> { logInfo("resume: mDuration = $duration") if (mRecordListener != null) { mRecordListener!!.onResume() } } HANDLER_COMPLETE -> { logInfo("complete: mDuration = $duration") if (mRecordListener != null && mRecordFile != null) { mRecordListener!!.onSuccess(false, mRecordFile!!.absolutePath, duration) duration = 0 } } HANDLER_AUTO_COMPLETE -> { logInfo("auto complete: mDuration = $duration") if (mRecordListener != null && mRecordFile != null) { mRecordListener!!.onSuccess(true, mRecordFile!!.absolutePath, duration) duration = 0 } } HANDLER_ERROR -> { logInfo("error : mDuration = $duration") if (mRecordListener != null) { if (msg.obj != null) { mRecordListener!!.onError(msg.obj as Exception) } else { mRecordListener!!.onError( Exception( "record error:AudioRecord read MIC error maybe not permission!" ) ) } } } HANDLER_PAUSE -> { logInfo("pause: mDuration = $duration") if (mRecordListener != null) { mRecordListener!!.onPause() } } HANDLER_PERMISSION -> { logInfo("permission:record fail ,maybe need permission") if (mPermissionListener != null) { mPermissionListener!!.needPermission() } } HANDLER_RESET -> { logInfo("reset:") if (mRecordListener != null) { mRecordListener!!.onReset() } } HANDLER_MAX_TIME -> if (mRecordListener != null) { mRecordListener!!.onMaxChange(mMaxTime) } else -> { } } } } /** 录音的方式 */ abstract val recorderType: RecorderType /** 设置是否使用耳机配置方式 */ abstract fun setContextToPlugConfig(context: Context): BaseRecorder /** 设置声音配置,设置后,修改设置声音大小会修改系统播放声音的大小 */ abstract fun setContextToVolumeConfig(context: Context): BaseRecorder /** * 设置录音输出文件, * @param outputFile 设置输出路径 * @param isContinue 表示是否拼接在文件末尾,继续录制的一种 */ open fun setOutputFile(outputFile: String, isContinue: Boolean = false): BaseRecorder { if (TextUtils.isEmpty(outputFile)) { val message = Message.obtain() message.what = HANDLER_ERROR message.obj = Exception("outputFile is not null") handler.sendMessage(message) } else { setOutputFile(File(outputFile), isContinue) } return this } /** * 设置录音输出文件 * @param outputFile 设置输出路径 * @param isContinue 表示是否拼接在文件末尾,继续录制的一种 */ open fun setOutputFile(outputFile: File, isContinue: Boolean = false): BaseRecorder { if (outputFile.exists()) { Log.w( TAG, "setOutputFile: outputFile is exists and isContinue == $isContinue ", ) } mRecordFile = outputFile this.isContinue = isContinue return this } /** 设置录音监听 */ abstract fun setRecordListener(recordListener: RecordListener?): BaseRecorder /** 设置没有权限的回调,感觉不是很准 */ abstract fun setPermissionListener(permissionListener: PermissionListener?): BaseRecorder /** 设计背景音乐的url,最好是本地的,否则可能会网络导致卡顿 */ abstract fun setBackgroundMusic(url: String): BaseRecorder /** 是否循环播放,默认true */ abstract fun setLoopMusic(isLoop: Boolean): BaseRecorder /** * 背景音乐的url,为了兼容Android Q,获取不到具体的路径 */ abstract fun setBackgroundMusic( context: Context, uri: Uri, header: MutableMap<String, String>? ): BaseRecorder /** 设置背景音乐的监听 */ abstract fun setBackgroundMusicListener(listener: PlayerListener): BaseRecorder /** 初始Lame录音输出质量 */ open fun setMp3Quality(@IntRange(from = 0, to = 9) mp3Quality: Int): BaseRecorder { if (isActive) { logError("setMp3Quality error ,need state isn't isActive|必须在开始录音前进行配置才有效果") return this } this.mMp3Quality = mp3Quality return this } /** * * 设置比特率,关系声音的质量 * * 比特率越高,传送的数据越大,音质越好 */ open fun setMp3BitRate(@IntRange(from = 16) mp3BitRate: Int): BaseRecorder { if (isActive) { logError("setMp3BitRate error ,need state isn't isActive|必须在开始录音前进行配置才有效果") return this } this.mLameMp3BitRate = mp3BitRate return this } /** * * 设置采样率 48000 * * 采样频率越高, 声音越接近原始数据。 */ open fun setSamplingRate(@IntRange(from = 8000) rate: Int): BaseRecorder { if (isActive) { logError("setSamplingRate error ,need state isn't isActive|必须在开始录音前进行配置才有效果") return this } this.mSamplingRate = rate return this } /** 设置音频声道数量,每次录音前可以设置修改,开始录音后无法修改 */ abstract fun setAudioChannel(@IntRange(from = 1, to = 2) channel: Int = 1): Boolean /** 设置音频来源,每次录音前可以设置修改,开始录音后无法修改 */ abstract fun setAudioSource(@Source audioSource: Int = MediaRecorder.AudioSource.MIC): Boolean /** * 设置最大录制时间,和提醒时间,只能提醒一次 */ open fun setMaxTime(maxTime: Long, remindDiffTime: Long? = 0L): BaseRecorder { if (maxTime < 0) { return this } this.mMaxTime = maxTime handler.sendEmptyMessage(HANDLER_MAX_TIME) if (remindDiffTime != null && remindDiffTime < maxTime) { this.mRemindTime = (maxTime - remindDiffTime) } else { this.mRemindTime = (maxTime - 10000) } return this } /** * 用于继续录制,替换录制,进行时间计算同步 * @param duration * @return */ open fun setCurDuration(duration:Long): BaseRecorder { this.duration = duration return this } /** * 设置滤波器 * lowpassFreq 高于这个频率的声音会被截除 hz, -1 表示不启用 * highpassFreq 低于这个频率的声音会被截除 hz , -1 表示不启用 */ open fun setFilter(lowpassFreq: Int = 3000, highpassFreq: Int = 200): BaseRecorder { if (isActive) { logError("setFilter error ,need state isn't isActive|必须在开始录音前进行配置才有效果") return this } this.lowpassFreq = lowpassFreq this.highpassFreq = highpassFreq return this } /** * 暂时请不要使用,目前存在问题 * @param isEnable * @return */ open fun isEnableVBR(isEnable: Boolean): BaseRecorder { if (isActive) { logError("setFilter error ,need state isn't isActive|必须在开始录音前进行配置才有效果") return this } openVBR = isEnable return this } /** 设置增强系数(不建议修改,因为会产生噪音~) */ open fun setWax(wax: Float): BaseRecorder { this.wax = wax return this } /** 设置背景声音大小 */ abstract fun setBGMVolume(@FloatRange(from = 0.0, to = 1.0) volume: Float): BaseRecorder /** 移除背景音乐 */ abstract fun cleanBackgroundMusic() /** 开始录音 */ abstract fun start() /** * 主动完成录音 */ abstract fun complete() /** * 重新开始录音 */ abstract fun resume() /** 替换后续录音的输出文件路径 */ abstract fun updateDataEncode(outputFilePath: String,isContinue: Boolean) /** 暂停录音 */ abstract fun pause() /** 是否设置了并且开始播放了背景音乐 */ abstract fun isPlayMusic(): Boolean /** 开始播放音乐 */ abstract fun startPlayMusic() /** 是否正在播放音乐 */ abstract fun isPauseMusic(): Boolean /** 暂停背景音乐 */ abstract fun pauseMusic() /** 重新播放背景音乐 */ abstract fun resumeMusic() /**重置*/ abstract fun reset() /**结束释放*/ abstract fun destroy() //endregion public method /** * 是否输出日志 */ open fun setDebug(isDebug: Boolean): BaseRecorder { this.isDebug = isDebug return this } /** * 获取变音控制 */ open fun getSoundTouch(): ISoundTouchCore { throw NullPointerException( "该录音工具不支持变音功能,需要使用STRecorder " + "\n The recorder recorderType does not support SoundTouch," + "u should implementation 'com.github.SheTieJun.Mp3Recorder:recorder-st:1.7.2' 。 " ) } //region 计算真正的时间,如果过程中有些数据太小,就直接置0,防止噪音 /** * 求得平均值之后,如果是平方和则代入常数系数为10的公式中, * 如果是绝对值的则代入常数系数为20的公式中,算出分贝值。 */ protected fun calculateRealVolume(buffer: ShortArray, readSize: Int) { mVolume = LameUtils.getPCMDB(buffer, readSize) if (mVolume < 0) { mVolume = 0 } if (mVolume > 100) { mVolume = 100 } } protected fun calculateRealVolume(buffer: ByteArray) { val shorts = BytesTransUtil.bytes2Shorts(buffer) val readSize = shorts.size calculateRealVolume(shorts, readSize) } //endregion 计算真正的时间,如果过程中有些数据太小,就直接置0,防止噪音 protected fun logInfo(info: String) { if (isDebug) { Log.d(TAG, info) } } protected fun logError(error: String) { Log.e(TAG, error) } /** * 1. 噪声抑制 * 2. 回音消除 * 3. 自动增益控制 */ protected fun initAEC(mAudioSessionId: Int) { if (mAudioSessionId != 0) { if (NoiseSuppressor.isAvailable()) { //噪声抑制 if (mNoiseSuppressor != null) { mNoiseSuppressor!!.release() mNoiseSuppressor = null } mNoiseSuppressor = NoiseSuppressor.create(mAudioSessionId) if (mNoiseSuppressor != null) { mNoiseSuppressor!!.enabled = true Log.i(TAG, "NoiseSuppressor enabled:[噪声抑制器开始]") } else { Log.i(TAG, "Failed to create NoiseSuppressor.") } } else { Log.i(TAG, "Doesn't support NoiseSuppressor:[噪声抑制器开始失败]") } if (AcousticEchoCanceler.isAvailable()) { //回音消除 if (mAcousticEchoCanceler != null) { mAcousticEchoCanceler!!.release() mAcousticEchoCanceler = null } mAcousticEchoCanceler = AcousticEchoCanceler.create(mAudioSessionId) if (mAcousticEchoCanceler != null) { mAcousticEchoCanceler!!.enabled = true Log.i(TAG, "AcousticEchoCanceler enabled:[声学回声消除器开启]") // mAcousticEchoCanceler.setControlStatusListener(listener)setEnableStatusListener(listener) } else { Log.i(TAG, "Failed to initAEC.") mAcousticEchoCanceler = null } } else { Log.i(TAG, "Doesn't support AcousticEchoCanceler:[声学回声消除器开启失败]") } if (AutomaticGainControl.isAvailable()) { //自动增益控制 if (mAutomaticGainControl != null) { mAutomaticGainControl!!.release() mAutomaticGainControl = null } mAutomaticGainControl = AutomaticGainControl.create(mAudioSessionId) if (mAutomaticGainControl != null) { mAutomaticGainControl!!.enabled = true Log.i(TAG, "AutomaticGainControl enabled:[自动增益控制开启]") } else { Log.i(TAG, "Failed to create AutomaticGainControl.") } } else { Log.i(TAG, "Doesn't support AutomaticGainControl:[自动增益控制开启失败]") } } } protected fun releaseAEC() { if (null != mAcousticEchoCanceler) { mAcousticEchoCanceler!!.enabled = false mAcousticEchoCanceler!!.release() mAcousticEchoCanceler = null } if (null != mAutomaticGainControl) { mAutomaticGainControl!!.enabled = false mAutomaticGainControl!!.release() mAutomaticGainControl = null } if (null != mNoiseSuppressor) { mNoiseSuppressor!!.enabled = false mNoiseSuppressor!!.release() mNoiseSuppressor = null } } protected fun mapFormat(format: Int): Int { return when (format) { AudioFormat.ENCODING_PCM_8BIT -> 8 AudioFormat.ENCODING_PCM_16BIT -> 16 else -> 0 } } companion object { const val HANDLER_RECORDING = 0x101 // 正在录音 const val HANDLER_START = HANDLER_RECORDING + 1 // 开始了 const val HANDLER_RESUME = HANDLER_START + 1 // 暂停后开始 const val HANDLER_COMPLETE = HANDLER_RESUME + 1 // 完成 const val HANDLER_AUTO_COMPLETE = HANDLER_COMPLETE + 1 // 最大时间完成 const val HANDLER_ERROR = HANDLER_AUTO_COMPLETE + 1 // 错误 const val HANDLER_PAUSE = HANDLER_ERROR + 1 // 暂停 const val HANDLER_RESET = HANDLER_PAUSE + 1 // 重置 const val HANDLER_PERMISSION = HANDLER_RESET + 1 // 需要权限 const val HANDLER_MAX_TIME = HANDLER_PERMISSION + 1 // 设置了最大时间 const val FRAME_COUNT = 160 val DEFAULT_AUDIO_FORMAT = PCMFormat.PCM_16BIT const val TAG = "Recorder" } }
0
Kotlin
2
21
33de393c74f4fbd7857fa27de42db5a9c38f4d6e
20,784
Mp3Recorder
MIT License
src/main/java/com/razorpay/sampleapp/kotlin/PaymentOptions.kt
razorpay
65,271,132
false
null
package com.razorpay.sampleapp.kotlin import android.app.Activity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.widget.* import android.widget.AdapterView.OnItemClickListener import com.razorpay.BaseRazorpay import com.razorpay.BaseRazorpay.PaymentMethodsCallback import com.razorpay.PaymentResultListener import com.razorpay.Razorpay import com.razorpay.ValidateVpaCallback import com.razorpay.sampleapp.R import org.json.JSONArray import org.json.JSONException import org.json.JSONObject class PaymentOptions : Activity(), PaymentResultListener { var webView: WebView? = null private var frameLayout: FrameLayout? = null var outerBox: ViewGroup? = null var listView: ListView? = null var bankCodesList = ArrayList<String>() var banksList = ArrayList<String>() var walletsList = ArrayList<String>() var banksListAdapter: ArrayAdapter<String>? = null var walletsListAdapter: ArrayAdapter<String>? = null var razorpay: Razorpay? = null var payload = JSONObject("{currency:'INR'}") val context = this val TAG: String = PaymentOptions::class.toString() private class MethodSelected : View.OnClickListener { override fun onClick(p0: View?) { when (p0?.id) { R.id.card -> { PaymentOptions().frameLayout?.removeAllViews() LayoutInflater.from(PaymentOptions().context).inflate(R.layout.fragment_payment_method_card, PaymentOptions().frameLayout, true) PaymentOptions().context.findViewById<Button>(R.id.submit_card_details).setOnClickListener { } } R.id.upi -> { PaymentOptions().frameLayout?.removeAllViews() LayoutInflater.from(PaymentOptions().context).inflate(R.layout.fragment_payment_method_upi,PaymentOptions().frameLayout,true) PaymentOptions().context.findViewById<Button>(R.id.btn_upi_collect_req).setOnClickListener { SubmitUPICollectRequest() } PaymentOptions().context.findViewById<Button>(R.id.btn_upi_intent_flow).setOnClickListener { SubmitUPIIntentDetails() } } R.id.netbanking -> { PaymentOptions().frameLayout?.removeAllViews() LayoutInflater.from(PaymentOptions().context).inflate(R.layout.fragment_method_netbanking_wallet_list, PaymentOptions().frameLayout, true) PaymentOptions().listView = PaymentOptions().context.findViewById<View>(R.id.method_available_options_list) as ListView PaymentOptions().listView?.adapter = PaymentOptions().banksListAdapter PaymentOptions().razorpay?.changeApiKey("rzp_live_wNe75AHP1XyKAl") PaymentOptions().listView?.setOnItemClickListener { parent, view, position, id -> run { PaymentOptions().submitNetbankingDetails(PaymentOptions().bankCodesList[position]) } } } R.id.wallet -> { PaymentOptions().frameLayout?.removeAllViews() LayoutInflater.from(PaymentOptions().context).inflate(R.layout.fragment_method_netbanking_wallet_list,PaymentOptions().frameLayout,true) PaymentOptions().listView = PaymentOptions().context.findViewById(R.id.method_available_options_list) PaymentOptions().listView?.adapter = PaymentOptions().walletsListAdapter PaymentOptions().listView?.setOnItemClickListener { parent, view, position, id -> run{ PaymentOptions().submitWalletDetails(PaymentOptions().walletsList[position]) } } } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment_options) findViewById<TextView>(R.id.card).setOnClickListener { MethodSelected() } findViewById<TextView>(R.id.upi).setOnClickListener { MethodSelected() } findViewById<TextView>(R.id.netbanking).setOnClickListener { MethodSelected() } findViewById<TextView>(R.id.wallet).setOnClickListener { MethodSelected() } webView = findViewById(R.id.payment_webview) frameLayout = findViewById(R.id.frame) outerBox = findViewById(R.id.outerbox) LayoutInflater.from(this).inflate(R.layout.fragment_payment_method_card, frameLayout, true) banksListAdapter = ArrayAdapter(this, R.layout.text_view_list_banks_wallet, banksList) walletsListAdapter = ArrayAdapter(this, R.layout.text_view_list_banks_wallet, walletsList) initRazorpay() createWebView() } private fun createWebView() { razorpay?.setWebView(webView) } private fun initRazorpay() { razorpay = Razorpay(this) razorpay?.getPaymentMethods(object : PaymentMethodsCallback { override fun onPaymentMethodsReceived(result: String?) { /** * This returns JSON data * The structure of this data can be seen at the following link: * https://api.razorpay.com/v1/methods?key_id=rzp_test_1DP5mmOlF5G5ag * */ Log.d("Result", "" + result) inflateLists(result) } override fun onError(error: String?) { Log.e("Get Payment error", error) } }) razorpay?.isValidVpa("stambatgr5@okhdfcbank", object : ValidateVpaCallback { override fun onFailure() { Toast.makeText(this@PaymentOptions, "Error validating VPA", Toast.LENGTH_LONG).show() } override fun onResponse(b: Boolean) { if (b) { Toast.makeText(this@PaymentOptions, "VPA is valid", Toast.LENGTH_LONG).show() } else { Toast.makeText(this@PaymentOptions, "VPA is Not Valid", Toast.LENGTH_LONG).show() } } }) } private fun inflateLists(result: String?) { try { val paymentMethods = JSONObject(result) val banksListJSON = paymentMethods.getJSONObject("netbanking") val walletListJSON = paymentMethods.getJSONObject("wallet") val itr1: Iterator<String> = banksListJSON.keys() while (itr1.hasNext()) { val key = itr1.next() bankCodesList.add(key) try { banksList.add(banksListJSON.getString(key)) } catch (jsonException: JSONException) { Log.e("Reading Banks List", jsonException.localizedMessage) } } val itr2: Iterator<String> = walletListJSON.keys() while (itr2.hasNext()) { val key = itr2.next() try { if (walletListJSON.getBoolean(key)) { walletsList.add(key) } } catch (jsonException: JSONException) { Log.e("Reading Wallets List", jsonException.localizedMessage) } } banksListAdapter?.notifyDataSetChanged() walletsListAdapter?.notifyDataSetChanged() } catch (e: Exception) { Log.e("Parsing Result", e.localizedMessage) } } public class SubmitCardDetails : View.OnClickListener { override fun onClick(view: View?) { val context = PaymentOptions().context val etName = context.findViewById<EditText>(R.id.name) val name = etName.text.toString() val etCardNumber = context.findViewById<EditText>(R.id.cardNumber) val cardNumber = etCardNumber.text.toString() val etDate = context.findViewById<EditText>(R.id.expiry) val date = etDate.text.toString() val index = date.indexOf('/') val month = date.substring(0, index) val year = date.substring(index + 1) val etCvv = context.findViewById<EditText>(R.id.cvv) val cvv = etCvv.text.toString() val payload = PaymentOptions().payload try { payload.put("amount", "100") payload.put("contact", "9999999999") payload.put("email", "[email protected]") } catch (e: Exception) { e.printStackTrace() } try { payload.put("method", "card") payload.put("card[name]", name) payload.put("card[number]", cardNumber) payload.put("card[expiry_month]", month) payload.put("card[expiry_year]", year) payload.put("card[cvv]", cvv) PaymentOptions().sendRequest() } catch (e: Exception) { e.printStackTrace() } } } public class SubmitUPICollectRequest : View.OnClickListener{ override fun onClick(view: View?) { val context = PaymentOptions().context val etVpa = context.findViewById<EditText>(R.id.vpa) val vpa = etVpa.text.toString() var payload = PaymentOptions().payload try{ payload = JSONObject("{currency: 'INR'}") payload.put("amount", "100") payload.put("contact", "9999999999") payload.put("email", "[email protected]") }catch (e: Exception){ e.printStackTrace() } try{ payload.put("method","upi") payload.put("vpa",vpa) PaymentOptions().sendRequest() }catch (e: Exception){ e.printStackTrace() } } } class SubmitUPIIntentDetails : View.OnClickListener { override fun onClick(view: View) { val context = PaymentOptions().context val vpaET = context.findViewById<View>(R.id.vpa) as EditText val vpa = vpaET.text.toString() val payload = PaymentOptions().payload try { payload.put("amount", "111") payload.put("contact", "9999999999") payload.put("email", "[email protected]") //payload.put("upi_app_package_name", "com.google.android.apps.nbu.paisa.user"); payload.put("display_logo", true) } catch (e: Exception) { e.printStackTrace() } try { val jArray = JSONArray() jArray.put("in.org.npci.upiapp") jArray.put("com.snapwork.hdfc") payload.put("description", "Credits towards consultation") //payload.put("key_id","rzp_test_kEVtCVFWAjUQPG"); payload.put("method", "upi") payload.put("_[flow]", "intent") payload.put("preferred_apps_order", jArray) payload.put("other_apps_order", jArray) PaymentOptions().sendRequest() } catch (e: Exception) { e.printStackTrace() } } } fun submitNetbankingDetails(bankName: String?) { try { payload = JSONObject("{currency: 'INR'}") payload.put("amount", "100") payload.put("contact", "9999999999") payload.put("email", "[email protected]") } catch (e: Exception) { e.printStackTrace() } try { payload.put("method", "netbanking") payload.put("bank", bankName) sendRequest() } catch (e: Exception) { e.printStackTrace() } } fun submitWalletDetails(walletName: String?) { try { payload = JSONObject("{currency: 'INR'}") payload.put("amount", "100") payload.put("contact", "9999999999") payload.put("email", "[email protected]") } catch (e: Exception) { e.printStackTrace() } try { payload.put("method", "wallet") payload.put("wallet", walletName) } catch (e: Exception) { e.printStackTrace() } sendRequest() } private fun sendRequest() { razorpay?.validateFields(payload, object : BaseRazorpay.ValidationListener { override fun onValidationError(error: MutableMap<String, String>?) { Log.d(TAG, "Validation failed: " + error?.get("field")) Toast.makeText(this@PaymentOptions, "Validation: " + error?.get("field"), Toast.LENGTH_LONG).show() } override fun onValidationSuccess() { try { webView?.visibility = View.VISIBLE outerBox?.visibility = View.GONE razorpay?.submit(payload, this@PaymentOptions) } catch (e: Exception) { Log.e(TAG, "Excpetion: ", e) e.printStackTrace() } } }) } override fun onBackPressed() { razorpay?.onBackPressed() super.onBackPressed() webView?.visibility = View.GONE outerBox?.visibility = View.VISIBLE } /** * Is called if the payment failed * possible values for code in this sdk are: * 2: in case of network error * 4: response parsing error * 5: This will contain meaningful message and can be shown to user * Format: {"error": {"description": "Expiry year should be greater than current year"}} */ override fun onPaymentError(errorCode: Int, errorDescription: String?) { webView?.visibility = View.GONE outerBox?.visibility = View.VISIBLE Toast.makeText(this@PaymentOptions, "Error $errorCode : $errorDescription",Toast.LENGTH_LONG).show() Log.e(TAG,"onError: $errorCode : $errorDescription") } /** * Is called if the payment was successful * You can now destroy the webview */ override fun onPaymentSuccess(rzpPaymentId: String?) { webView?.visibility = View.GONE outerBox?.visibility = View.VISIBLE Toast.makeText(this@PaymentOptions, "Payment Successful: $rzpPaymentId",Toast.LENGTH_LONG).show() } }
14
null
9
8
fcd817f87e137354b3b77dc68fd3ddbb25f583cc
14,781
razorpay-android-custom-sample-app
MIT License
data/src/main/java/com/example/data/local/PreferencesDataStore.kt
mahmood199
753,995,489
false
{"Kotlin": 129052}
package com.example.data.local import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.doublePreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.stringPreferencesKey import com.example.data.model.local.UserPreferences import com.example.data.model.request.Constants import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import java.io.IOException import javax.inject.Inject class PreferencesDataStore @Inject constructor( private val dataStore: DataStore<Preferences> ) { companion object { const val AUTHORIZATION_TOKEN = "<KEY>" } val userPreferencesFlow: Flow<UserPreferences> = dataStore.data .catch { exception -> if (exception is IOException) { exception.printStackTrace() emit(emptyPreferences()) } else { throw Exception() } } .map { preferences -> val authToken = preferences[PreferencesKeys.AUTH_TOKEN] ?: "" UserPreferences( bearerToken = authToken ) } suspend fun setBearerToken() { dataStore.edit { preferences -> preferences[PreferencesKeys.AUTH_TOKEN] = AUTHORIZATION_TOKEN } } private object PreferencesKeys { val AUTH_TOKEN = stringPreferencesKey("auth_token") } }
0
Kotlin
0
0
a1fb1d447bf3f8b316f8d1d1d0c2122a7c42b6d3
1,649
Dashboard
Apache License 2.0
plugins/kotlin-dataframe/testData/box/remove.kt
Kotlin
259,256,617
false
{"Kotlin": 8227503, "Java": 17608, "JavaScript": 11483, "CSS": 3083, "HTML": 137, "Shell": 73}
import org.jetbrains.kotlinx.dataframe.* import org.jetbrains.kotlinx.dataframe.api.* data class Nested(val d: Double) data class Record(val a: String, val b: Int, val nested: Nested) fun box(): String { val df = listOf(Record("112", 42, Nested(3.0))).toDataFrame(maxDepth = 1) val df1 = df.remove { nested.d } df1.a return "OK" }
235
Kotlin
60
833
54d00e69ae7c06ff254c6591242413eaf7894f01
350
dataframe
Apache License 2.0
app/src/main/kotlin/io/github/nuhkoca/libbra/ui/currency/BindableMultiplier.kt
nuhkoca
252,193,036
false
{"Kotlin": 258455, "Shell": 1250, "Java": 620}
/* * Copyright (C) 2020. Nuh Koca. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.nuhkoca.libbra.ui.currency import androidx.annotation.UiThread import androidx.databinding.BaseObservable import androidx.databinding.Bindable import io.github.nuhkoca.libbra.BR import io.github.nuhkoca.libbra.ui.di.MainScope import io.github.nuhkoca.libbra.util.ext.i import javax.inject.Inject import kotlin.properties.Delegates /** * A [BaseObservable] implementation that holds multiplier entered by responder view. */ @MainScope class BindableMultiplier @Inject constructor() : BaseObservable() { @get:Bindable var multiplier: Float by Delegates.observable(DEFAULT_VALUE) { _, _, newValue -> notifyPropertyChanged(BR.multiplier) i { "Current multiplier is $newValue" } } @UiThread fun reset() { multiplier = DEFAULT_VALUE } private companion object { private const val DEFAULT_VALUE = 1.0f } }
1
Kotlin
11
54
fd6c1560078017c81564b4b8e0717b32b2b31ec0
1,508
libbra
Apache License 2.0
kvision-tools/kvision-gradle-plugin/src/main/kotlin/io/kvision/gradle/KVisionPlugin.kt
rjaros
120,835,750
false
null
package io.kvision.gradle import io.kvision.gradle.tasks.KVConvertPoTask import io.kvision.gradle.tasks.KVGeneratePotTask import io.kvision.gradle.tasks.KVWorkerBundleTask import javax.inject.Inject import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.DuplicatesStrategy import org.gradle.api.provider.Provider import org.gradle.api.provider.ProviderFactory import org.gradle.api.tasks.Copy import org.gradle.api.tasks.TaskCollection import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.bundling.Zip import org.gradle.internal.os.OperatingSystem import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.named import org.gradle.kotlin.dsl.register import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.dsl.KotlinCompile import org.jetbrains.kotlin.gradle.dsl.KotlinJsCompile import org.jetbrains.kotlin.gradle.dsl.KotlinJsProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension abstract class KVisionPlugin @Inject constructor( private val providers: ProviderFactory ) : Plugin<Project> { // private val executor: ExecOperations // private val fileOps: FileSystemOperations // private val providers: ProviderFactory // private val layout: ProjectLayout override fun apply(target: Project) = with(target) { logger.debug("Applying KVision plugin") val kvExtension = createKVisionExtension() with(KVPluginContext(project, kvExtension)) { plugins.withId("org.jetbrains.kotlin.js") { configureJsProject() afterEvaluate { configureNodeEcosystem() } } plugins.withId("org.jetbrains.kotlin.multiplatform") { configureMppProject() afterEvaluate { configureNodeEcosystem() } } } } /** * Initialise the [KVisionExtension] on a [Project]. * * Additionally, set default values for properties that require a [Project] instance. */ private fun Project.createKVisionExtension(): KVisionExtension { return extensions.create("kvision", KVisionExtension::class).apply { nodeBinaryPath.convention(nodeJsBinaryProvider()) kotlinJsStoreDirectory.convention(project.layout.projectDirectory.dir(".kotlin-js-store")) generatedFrontendResources.convention(project.layout.buildDirectory.dir("generated/kvision/frontendResources")) } } /** * Helper class that provides both a Gradle [Project] and [KVisionExtension]. * * This makes it easier to break-up project configuration into extension functions. */ private data class KVPluginContext( private val project: Project, val kvExtension: KVisionExtension, ) : Project by project /** Configure a Kotlin JS project */ private fun KVPluginContext.configureJsProject() { logger.debug("configuring Kotlin/JS plugin") val kotlinJsExtension = extensions.getByType<KotlinJsProjectExtension>() if (kvExtension.enableGradleTasks.get()) { registerGeneratePotFileTask { dependsOn(tasks.all.compileKotlinJs) inputs.files(kotlinJsExtension.sourceSets.main.get().kotlin.files) potFile.set( layout.projectDirectory.file( "src/main/resources/i18n/messages.pot" ) ) } } val convertPoToJsonTask = registerConvertPoToJsonTask { dependsOn(tasks.all.compileKotlinJs) sourceDirectory.set( layout.projectDirectory.dir("src/main/resources/i18n") ) destinationDirectory.set( kvExtension.generatedFrontendResources.dir("i18n") ) } if (kvExtension.enableGradleTasks.get()) { registerZipTask { dependsOn(tasks.all.browserProductionWebpack) } } tasks.all.processResources.configureEach { exclude("**/*.pot") exclude("**/*.po") dependsOn(convertPoToJsonTask) } if (kvExtension.irCompiler.get()) { tasks.all.browserDevelopmentRun.configureEach { dependsOn("developmentExecutableCompileSync") } } kotlinJsExtension.sourceSets.main.configure { resources.srcDir(kvExtension.generatedFrontendResources) } } /** Configure a Kotlin Multiplatform project */ private fun KVPluginContext.configureMppProject() { logger.debug("configuring Kotlin/MPP plugin") if (kvExtension.enableKsp.get()) plugins.apply("com.google.devtools.ksp") val kotlinMppExtension = extensions.getByType<KotlinMultiplatformExtension>() if (kvExtension.enableGradleTasks.get()) { registerGeneratePotFileTask { dependsOn(tasks.all.compileKotlinFrontend) inputs.files(kotlinMppExtension.sourceSets.frontendMain.map { it.kotlin.files }) potFile.set( layout.projectDirectory.file( "src/frontendMain/resources/i18n/messages.pot" ) ) } } val convertPoToJsonTask = registerConvertPoToJsonTask { dependsOn(tasks.all.compileKotlinFrontend) sourceDirectory.set( layout.projectDirectory.dir("src/frontendMain/resources/i18n") ) destinationDirectory.set( kvExtension.generatedFrontendResources.dir("i18n") ) } if (kvExtension.enableWorkerTasks.get()) { registerWorkerBundleTask { dependsOn(tasks.all.workerBrowserProductionWebpack) } } tasks.all.compileKotlinFrontend.configureEach { if (kvExtension.enableKsp.get()) dependsOn("kspCommonMainKotlinMetadata") } tasks.all.compileKotlinBackend.configureEach { if (kvExtension.enableKsp.get()) dependsOn("kspCommonMainKotlinMetadata") } if (kvExtension.enableGradleTasks.get() && kvExtension.enableKsp.get()) { tasks.create("generateKVisionSources") { group = KVISION_TASK_GROUP description = "Generates KVision sources for fullstack interfaces" dependsOn("kspCommonMainKotlinMetadata") } } tasks.all.frontendProcessResources.configureEach { exclude("**/*.pot") exclude("**/*.po") dependsOn(convertPoToJsonTask) } if (kvExtension.irCompiler.get()) { tasks.all.frontendBrowserDevelopmentRun.configureEach { dependsOn("frontendDevelopmentExecutableCompileSync") } } kotlinMppExtension.sourceSets.matching { it.name == "frontendMain" }.configureEach { resources.srcDir(kvExtension.generatedFrontendResources) } if (kvExtension.enableKsp.get()) { dependencies { add("kspCommonMainMetadata", "io.kvision:kvision-ksp-processor:6.1.2") } afterEvaluate { dependencies { add("kspFrontend", "io.kvision:kvision-ksp-processor:6.1.2") } kotlinMppExtension.sourceSets.getByName("commonMain").kotlin.srcDir("build/generated/ksp/metadata/commonMain/kotlin") kotlinMppExtension.sourceSets.getByName("frontendMain").kotlin.srcDir("build/generated/ksp/frontend/frontendMain/kotlin") } tasks.all.kspKotlinFrontend.configureEach { dependsOn("kspCommonMainKotlinMetadata") } } } /** Applied to both Kotlin JS and Kotlin Multiplatform project */ private fun KVPluginContext.registerGeneratePotFileTask( configuration: KVGeneratePotTask.() -> Unit = {} ) { logger.debug("registering KVGeneratePotTask") tasks.withType<KVGeneratePotTask>().configureEach { nodeJsBinary.set(kvExtension.nodeBinaryPath) getTextExtractBin.set( rootNodeModulesDir.file("gettext-extract/bin/gettext-extract") ) configuration() } tasks.register<KVGeneratePotTask>("generatePotFile") } /** Applied to both Kotlin JS and Kotlin Multiplatform project */ private fun KVPluginContext.registerConvertPoToJsonTask( configuration: KVConvertPoTask.() -> Unit = {} ): TaskProvider<KVConvertPoTask> { logger.debug("registering KVConvertPoTask") tasks.withType<KVConvertPoTask>().configureEach { enabled = kvExtension.enableGradleTasks.get() po2jsonBinDir.set( rootNodeModulesDir.file("gettext.js/bin/po2json") ) nodeJsBinary.set(nodeJsBinaryProvider()) configuration() } return tasks.register<KVConvertPoTask>("convertPoToJson") } /** Requires Kotlin JS project */ private fun KVPluginContext.registerZipTask(configuration: Zip.() -> Unit = {}) { logger.debug("registering KVision zip task") val webDir = layout.projectDirectory.dir("src/main/web") tasks.register<Zip>("zip") { group = PACKAGE_TASK_GROUP description = "Builds ZIP archive with the application" destinationDirectory.set(layout.buildDirectory.dir("libs")) from(tasks.provider.browserProductionWebpack.map { it.destinationDirectory }) { include("*.*") } from(webDir) duplicatesStrategy = DuplicatesStrategy.EXCLUDE configuration() } } /** Requires Kotlin MPP project */ private fun KVPluginContext.registerWorkerBundleTask(configuration: KVWorkerBundleTask.() -> Unit = {}) { logger.debug("registering KVWorkerBundleTask") tasks.withType<KVWorkerBundleTask>().configureEach { nodeJsBin.set(nodeJsBinaryProvider()) webpackJs.set( rootNodeModulesDir.file("webpack/bin/webpack.js") ) webpackConfigJs.set( rootProject.layout.buildDirectory.file("js/packages/${rootProject.name}-worker/webpack.config.js") ) workerMainSrcDir.set( layout.projectDirectory.dir("src/workerMain/kotlin") ) workerJsFile.set( layout.buildDirectory.file("processedResources/frontend/main/worker.js") ) executable(nodeJsBin.get()) workingDir( rootProject.layout.buildDirectory.dir("js/packages/${rootProject.name}-worker") ) args( webpackJs.get(), "--config", webpackConfigJs.get(), ) configuration() } tasks.register<KVWorkerBundleTask>("workerBundle") } private fun KVPluginContext.configureNodeEcosystem() { logger.info("configuring Node") rootProject.extensions.configure<YarnRootExtension> { logger.info("configuring Yarn") if (kvExtension.enableResolutions.get()) { // No forced resolutions at the moment } if (kvExtension.enableHiddenKotlinJsStore.get()) { lockFileDirectory = kvExtension.kotlinJsStoreDirectory.get().asFile logger.info("[configureNodeEcosystem.configureYarn] set lockFileDirectory: $lockFileDirectory") } } rootProject.extensions.configure<NodeJsRootExtension> { logger.info("configuring NodeJs") if (kvExtension.enableWebpackVersions.get()) { versions.apply { kvExtension.versions.webpackDevServer.orNull?.let { webpackDevServer.version = it } kvExtension.versions.webpack.orNull?.let { webpack.version = it } kvExtension.versions.webpackCli.orNull?.let { webpackCli.version = it } kvExtension.versions.karma.orNull?.let { karma.version = it } kvExtension.versions.mocha.orNull?.let { mocha.version = it } val versions = listOf( "webpackDevServer: ${webpackDevServer.version}", " webpack: ${webpack.version} ", " webpackCli: ${webpackCli.version} ", " karma: ${karma.version} ", " mocha: ${mocha.version} ", ).joinToString(", ") { it.trim() } logger.info("[configureNodeEcosystem.configureNodeJs] set webpack versions: $versions") } } } } /** task provider helpers - help make the script configurations shorter & more legible */ private val TaskContainer.provider: TaskProviders get() = TaskProviders(this) /** Lazy task providers */ private inner class TaskProviders(private val tasks: TaskContainer) { val processResources: Provider<Copy> get() = provider("processResources") val frontendProcessResources: Provider<Copy> get() = provider("frontendProcessResources") val browserProductionWebpack: Provider<KotlinWebpack> get() = provider("browserProductionWebpack") // Workaround for https://github.com/gradle/gradle/issues/16543 private inline fun <reified T : Task> provider(taskName: String): Provider<T> = providers .provider { taskName } .flatMap { tasks.named<T>(it) } } private val TaskContainer.all: TaskCollections get() = TaskCollections(this) /** Lazy task collections */ private inner class TaskCollections(private val tasks: TaskContainer) { val processResources: TaskCollection<Copy> get() = collection("processResources") val frontendProcessResources: TaskCollection<Copy> get() = collection("frontendProcessResources") val compileKotlinFrontend: TaskCollection<KotlinCompile<*>> get() = collection("compileKotlinFrontend") val compileKotlinBackend: TaskCollection<KotlinCompile<*>> get() = collection("compileKotlinBackend") val compileKotlinJs: TaskCollection<KotlinJsCompile> get() = collection("compileKotlinJs") val browserProductionWebpack: TaskCollection<KotlinWebpack> get() = collection("browserProductionWebpack") val workerBrowserProductionWebpack: TaskCollection<Task> get() = collection("workerBrowserProductionWebpack") val browserDevelopmentRun: TaskCollection<Task> get() = collection("browserDevelopmentRun") val frontendBrowserDevelopmentRun: TaskCollection<Task> get() = collection("frontendBrowserDevelopmentRun") val kspKotlinFrontend: TaskCollection<Task> get() = collection("kspKotlinFrontend") private inline fun <reified T : Task> collection(taskName: String): TaskCollection<T> = tasks.withType<T>().matching { it.name == taskName } } /** * [Provider] for the absolute path of the Node binary that the Kotlin plugin (JS or * Multiplatform) installs into the root project. * * The current operating system is taken into account. */ private fun Project.nodeJsBinaryProvider(): Provider<String> { val nodeJsRootExtension = providers.provider { rootProject.extensions.getByType(NodeJsRootExtension::class) } val nodeDirProvider = nodeJsRootExtension .flatMap { it.nodeJsSetupTaskProvider } .map { it.destination } val isWindowsProvider = providers.provider { OperatingSystem.current().isWindows } val nodeBinDirProvider = isWindowsProvider.zip(nodeDirProvider) { isWindows, nodeDir -> if (isWindows) nodeDir else nodeDir.resolve("bin") } val nodeExecutableProvider = nodeJsRootExtension.zip(isWindowsProvider) { ext, isWindows -> if (isWindows && ext.nodeCommand == "node") "node.exe" else ext.nodeCommand } return nodeExecutableProvider.zip(nodeBinDirProvider) { nodeExecutable, nodeBinDir -> nodeBinDir.resolve(nodeExecutable).absolutePath } } // source set provider helpers private val NamedDomainObjectContainer<KotlinSourceSet>.main: NamedDomainObjectProvider<KotlinSourceSet> get() = named("main") private val NamedDomainObjectContainer<KotlinSourceSet>.frontendMain: NamedDomainObjectProvider<KotlinSourceSet> get() = named("frontendMain") companion object { const val KVISION_TASK_GROUP = "kvision" const val PACKAGE_TASK_GROUP = "package" private val Project.rootNodeModulesDir: DirectoryProperty get() = objects.directoryProperty().convention( rootProject.layout.buildDirectory.dir("js/node_modules/") ) } }
31
null
59
1,062
b33809a2ff07eb36ceacef441f3a0a929b7c4ba2
18,183
kvision
MIT License
dashboard/src/main/java/com/bibek/dashboard/presentation/ui/components/ReminderContent.kt
bibekanandan892
820,073,061
false
{"Kotlin": 148771}
package com.bibek.dashboard.presentation.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.bibek.core.utils.Day import com.bibek.dashboard.R @Composable fun ReminderContent( closeSelection: () -> Unit, onTimeSelect: (Int, Int) -> Unit, onSaveClick: () -> Unit = {}, onDayClick: (Day) -> Unit = {}, onTimeClick: () -> Unit = {}, onCloseSheet: () -> Unit = {}, isShowClock: Boolean, selectedDay: Day? = null, selectedTime: String ) { if (isShowClock) { ClockDialog(closeSelection = { closeSelection() }, onTimeSelect = { hour, min -> onTimeSelect(hour, min) }) } Column( modifier = Modifier .fillMaxWidth() .background(Color(0xFF1C1C1E)) .clip(shape = RoundedCornerShape(20.dp)) .padding(16.dp) ) { TopAppBar( title = { Text(text = stringResource(R.string.select_time), color = Color.White) }, backgroundColor = Color.Transparent, elevation = 0.dp, navigationIcon = { IconButton(onClick = onCloseSheet) { Icon( Icons.Default.Close, contentDescription = stringResource(R.string.back), tint = Color.White ) } }, actions = { selectedDay?.let { IconButton(onClick = { onSaveClick.invoke() }) { Icon( Icons.Default.Check, contentDescription = stringResource(R.string.save), tint = Color.White ) } } } ) Spacer(modifier = Modifier.height(32.dp)) // Time Display Text( text = selectedTime, fontSize = 64.sp, color = Color.White, modifier = Modifier .align(Alignment.CenterHorizontally) .clickable(onClick = onTimeClick) ) Spacer(modifier = Modifier.height(8.dp)) // Schedule Switch Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth() ) { Text(text = stringResource(R.string.select_day), color = Color.Gray) } Spacer(modifier = Modifier.height(16.dp)) // Days of the Week Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth() ) { Day.entries.forEach { day -> DayCircle( day = day, isSelected = selectedDay?.name == day.name, onClick = { onDayClick(day) } ) } } Spacer(modifier = Modifier.height(32.dp)) } } @Composable fun DayCircle(day: Day, isSelected: Boolean, onClick: () -> Unit) { val backgroundColor = if (isSelected) Color.White else Color.DarkGray val textColor = if (isSelected) Color.DarkGray else Color.White Box( modifier = Modifier .size(40.dp) .clip(CircleShape) .background(backgroundColor) .clickable { onClick() }, contentAlignment = Alignment.Center ) { Text( text = day.name.first().toString(), color = textColor, fontWeight = FontWeight.SemiBold ) } }
0
Kotlin
0
0
5844da2f6c85cdff4f5e2d226dc94463a8fc66de
4,915
Recipe-Database
Apache License 2.0
plain-java-sockets/src/main/kotlin/daggerok/SocketClient.kt
daggerok
122,118,350
false
null
package daggerok import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream import java.net.Socket import java.nio.charset.StandardCharsets.UTF_8 class SocketClient { companion object { private val log = LoggerFactory.getLogger(SocketClient::class.java) private const val port = 8080 private val client: Socket by lazy { Socket("127.0.0.1", port) } private fun subscribe(): String { val baos = ByteArrayOutputStream() client.getInputStream().use { var container = ByteArray(1024) val readBytes = it.read(container) if (readBytes != -1) baos.write(container, 0, readBytes) } return baos.toString(UTF_8.name()) } fun publish(data: String = "hello") { val client: Socket by lazy { Socket("127.0.0.1", port) } /* val client = client.getOutputStream() client.write(data.toByteArray()) client.flush() */ client.getOutputStream().use { it.write(data.toByteArray()) } } } }
1
Kotlin
1
3
571e4b868b49d7661073a11d0f2edb1772edce81
1,041
kotlin-examples
MIT License
waypoints-api/src/main/kotlin/de/md5lukas/waypoints/api/WaypointsAPI.kt
Sytm
211,378,928
false
null
package de.md5lukas.waypoints.api import java.util.* /** * This interface provides the entry-point to use the Waypoints API. * * It can be obtained by using a ServiceProvider like this: * ```java * RegisteredServiceProvider<WaypointsAPI> rsp = Bukkit.getServicesManager().getRegistration(WaypointsAPI.class); * WaypointsAPI api = rsp.getProvider(); * ``` * * or with Kotlin like this: * ``` * val rsp = Bukkit.servicesManager.getRegistration(WaypointsAPI::class) * val api = api.provider * ``` * * A very important note regarding this API is, that the default SQLite implementation will execute * everything synchronous. */ interface WaypointsAPI { /** * Check if a player exists in the database. For a player to exist [getWaypointPlayer] only has to * be called once without doing anything else. * * @param uuid The UUID of the player * @return true if the player has been requested before */ @JvmSynthetic suspend fun waypointsPlayerExists(uuid: UUID): Boolean fun waypointsPlayerExistsCF(uuid: UUID) = future { waypointsPlayerExists(uuid) } /** * Get the player-profile for the matching UUID. If the player-profile has never been requested * before, a new profile will be created with default values. * * @param uuid The UUID of the player * @return The player-profile */ @JvmSynthetic suspend fun getWaypointPlayer(uuid: UUID): WaypointsPlayer fun getWaypointPlayerCF(uuid: UUID) = future { getWaypointPlayer(uuid) } /** The abstract holder containing public waypoints and folders. */ val publicWaypoints: WaypointHolder /** The abstract holder containing permission waypoints and folders. */ val permissionWaypoints: WaypointHolder /** * Retrieve a waypoint of any type with the given UUID from the database. * * @param uuid The UUID of the waypoint * @return The waypoint if it exists */ @JvmSynthetic suspend fun getWaypointByID(uuid: UUID): Waypoint? fun getWaypointByIDCF(uuid: UUID) = future { getWaypointByID(uuid) } /** * Retrieve a folder of any type with the given UUID from the database. * * @param uuid The UUID of the folder * @return The folder if it exists */ @JvmSynthetic suspend fun getFolderByID(uuid: UUID): Folder? fun getFolderByIDCF(uuid: UUID) = future { getFolderByID(uuid) } /** Get access to some interesting statistics of total waypoints and folders. */ val statistics: Statistics }
1
null
7
28
b31e54acb0cb8e93c9713492b1c1a0759f1045ed
2,447
waypoints
MIT License
vector/src/main/java/im/vector/app/core/animations/VectorFullTransitionSet.kt
tchapgouv
340,329,238
false
null
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.riotx.core.animations import android.content.Context import android.util.AttributeSet import androidx.transition.ChangeBounds import androidx.transition.ChangeTransform import androidx.transition.Fade import androidx.transition.TransitionSet class VectorFullTransitionSet : TransitionSet { constructor() { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } private fun init() { ordering = ORDERING_TOGETHER addTransition(Fade(Fade.OUT)) .addTransition(ChangeBounds()) .addTransition(ChangeTransform()) .addTransition(Fade(Fade.IN)) } }
55
null
6
9
02c555858daab03fd2bdac159efd55961f3b6ebe
1,307
tchap-android
Apache License 2.0
src/main/java/com/samla/sdk/ISamla.kt
NiekBijman
237,298,269
false
null
package com.samla.sdk import android.app.Activity interface ISamla { fun getActivity() : Activity; }
1
null
1
1
9685137d3cae2d19eb90eebfef579c31f930bf41
106
user-testing-android-sdk
MIT License
src/main/java/com/samla/sdk/ISamla.kt
NiekBijman
237,298,269
false
null
package com.samla.sdk import android.app.Activity interface ISamla { fun getActivity() : Activity; }
1
null
1
1
9685137d3cae2d19eb90eebfef579c31f930bf41
106
user-testing-android-sdk
MIT License
app/src/main/java/com/ctd/cymanage/widget/NoticeDialog.kt
lianwt115
162,071,434
false
{"Java": 370195, "Kotlin": 191947}
package com.ctd.cymanage.widget import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.graphics.BitmapFactory import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton import com.bumptech.glide.Glide import com.ctd.cymanage.R import com.ctd.cymanage.utils.DeviceUtil import com.ctd.cymanage.utils.UiUtils import com.ctd.cymanage.utils.applySchedulers import com.orhanobut.logger.Logger import io.reactivex.Observable import java.util.concurrent.TimeUnit /** * Created by Administrator on 2018\1\8 0008. */ class NoticeDialog : Dialog { constructor(context: Context) : super(context) {} constructor(context: Context, themeResId: Int) : super(context, themeResId) {} protected constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) {} class Builder(private val mContext: Context,private val cancle: Boolean) : DialogInterface.OnDismissListener { private var mLoginDialog: NoticeDialog? = null private var mLayout: View? = null private var mNoticeTVNotice: TextView? = null private var mProgressBar: ProgressBar? = null private var mTopRoot: LinearLayout? = null private var mLine: View? = null private var mType = 0 private var mBtNext: CircularProgressButton? = null private var mListen: BtClickListen? = null private var index = 0 fun create(notice:String): NoticeDialog { val inflater = mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater mLoginDialog = NoticeDialog(mContext, R.style.MyDialog) mLoginDialog!!.setCanceledOnTouchOutside(cancle) mLoginDialog!!.setOnDismissListener(this) mLayout = inflater.inflate(R.layout.dialog_notice, null) mLoginDialog!!.addContentView(mLayout!!, ViewGroup.LayoutParams( DeviceUtil.dip2px(mContext, 180f),LinearLayout.LayoutParams.WRAP_CONTENT )) mNoticeTVNotice = mLayout!!.findViewById(R.id.dialog_text) as TextView mProgressBar = mLayout!!.findViewById(R.id.progress) as ProgressBar mBtNext = mLayout!!.findViewById(R.id.bt_go) as CircularProgressButton mLine = mLayout!!.findViewById(R.id.line) as View mTopRoot = mLayout!!.findViewById(R.id.top_root) as LinearLayout mBtNext?.setFinalCornerRadius(8F) mBtNext?.text = mContext.getString(R.string.next) mBtNext?.background = mContext.getDrawable(R.drawable.bg_acc_8) mBtNext!!.setOnClickListener { if (mListen !=null) { if (mListen!!.btClick()) { mBtNext!!.startAnimation() } } } initView(notice,cancle) return mLoginDialog as NoticeDialog } fun initView(notice: String,cancle: Boolean) { mNoticeTVNotice!!.text=notice mLoginDialog!!.setCanceledOnTouchOutside(cancle) } fun setListen(listen:BtClickListen?,type:Int){ this.mListen = listen this.mType = type when (type) { //只要标题 1 -> { mBtNext!!.visibility = View.GONE mLine!!.visibility = View.GONE mProgressBar!!.visibility = View.GONE } //标题和缓冲进度 2 -> { mBtNext!!.visibility = View.GONE mLine!!.visibility = View.VISIBLE mProgressBar!!.visibility = View.VISIBLE } //标题 按钮 3 -> { mBtNext!!.visibility = View.VISIBLE mLine!!.visibility = View.VISIBLE mProgressBar!!.visibility = View.GONE } } mTopRoot!!.background =mContext.getDrawable(if (type == 1)R.drawable.bg_20dp_0 else R.drawable.bg_20dp_0_top) } fun btFinish(boolean: Boolean){ if (mType == 3) mBtNext!!.doneLoadingAnimation(mContext.resources.getColor(R.color.white),if (boolean) BitmapFactory.decodeResource(mContext.resources,R.mipmap.ic_done) else BitmapFactory.decodeResource(mContext.resources,R.mipmap.error)) Observable.timer(1,TimeUnit.SECONDS).applySchedulers().subscribe({ mLoginDialog!!.dismiss() },{ Logger.e("延迟关闭对话框异常") }) } override fun onDismiss(dialog: DialogInterface?) { mBtNext?.revertAnimation() } interface BtClickListen{ fun btClick():Boolean } } }
1
null
1
1
aed1d6fbdea2b7b949b2e01b14b22fa359a074d8
5,050
pad_table
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/jiraactions/page/SingleSelect.kt
atlassian
162,422,950
false
{"Kotlin": 214499, "Java": 1959}
package com.atlassian.performance.tools.jiraactions.page import com.atlassian.performance.tools.jiraactions.api.page.wait import com.atlassian.performance.tools.jiraactions.api.webdriver.sendKeysWhenClickable import org.openqa.selenium.By import org.openqa.selenium.Keys import org.openqa.selenium.WebDriver import org.openqa.selenium.interactions.Actions import org.openqa.selenium.support.pagefactory.ByChained import org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable import org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated internal class SingleSelect( private val driver: WebDriver, locator: By ) { private val parent: By = ByChained(locator, By.xpath("..")) private val inputLocator = ByChained(parent, By.tagName("input")) fun select(value: String) { driver.findElement(inputLocator).sendKeysWhenClickable(driver, Keys.BACK_SPACE, value, Keys.TAB) } fun select(picker: (List<String>) -> String) { val inputElement = driver.wait(elementToBeClickable(inputLocator)) inputElement.click() val availableValues = parseSuggestions().plus(inputElement.getAttribute("value")!!) inputElement.sendKeys(Keys.BACK_SPACE, picker(availableValues), Keys.TAB) } fun getSuggestions(): List<String> { val dropMenuArrow = driver .wait( elementToBeClickable( ByChained(parent, By.className("drop-menu")) ) ) dropMenuArrow.click() val suggestions = parseSuggestions() // we now have to restore the select to it's usual state, // otherwise we will mess up 'select-all-on-click' behaviour // We click to hide the menu and tab to get out of the input element dropMenuArrow.click() Actions(driver).sendKeys(Keys.TAB, Keys.TAB).build().perform() return suggestions } private fun parseSuggestions(): List<String> { return driver .wait( presenceOfElementLocated(By.cssSelector(".ajs-layer.active")) ) .findElements(By.className("aui-list-item-link")) .map { it.text } } fun getCurrentValue(): String { return driver.findElement(inputLocator).getAttribute("value")!! } }
8
Kotlin
31
26
10b363eda1e171f8342eaeeb6deac843b1d34df3
2,347
jira-actions
Apache License 2.0
shared/src/commonMain/kotlin/com/somabits/spanish/ui/product/BuyVerbDataPackCard.kt
chiljamgossow
581,781,635
false
{"Kotlin": 904768, "Swift": 1817}
package com.somabits.spanish.ui.product import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ShoppingCart import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.somabits.spanish.SharedRes import com.somabits.spanish.stringResource import com.somabits.spanish.ui.theme.cardColorSchemeInverse @Composable fun BuyVerbDataPackCard( modifier: Modifier = Modifier, name: String, formattedPrice: String, verbList: List<String>, onButtonClick: () -> Unit, ) { DataPackCard( modifier = modifier, colorScheme = cardColorSchemeInverse(), title = name, body = stringResource(SharedRes.strings.data_pack_body, verbList.size), verbList = verbList, buttonText = stringResource( SharedRes.strings.data_pack_button, formattedPrice, ), onClick = onButtonClick, imageVector = Icons.Rounded.ShoppingCart, ) }
1
Kotlin
0
0
e680c7048721fb9a2cbfb7cb5a9db3e39ac73b45
990
Spanish
MIT License
src/commonTest/kotlin/GameTests.kt
jonnyzzz
189,975,478
false
null
package org.jonnyzzz.lifegame import kotlin.test.Test class GameTests { @Test fun testMe() { } }
0
Kotlin
2
22
63dba61271e1271d7bce1749977c7d2adf024362
113
kotlin-game-of-life
MIT License