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
core/testing/src/main/kotlin/edu/stanford/spezi/core/testing/CoroutineTestRule.kt
StanfordSpezi
787,513,636
false
{"Kotlin": 994700, "Ruby": 1769, "Shell": 212}
package edu.stanford.spezi.core.testing import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description /** * A JUnit Test Rule that sets the main coroutine dispatcher to a [TestDispatcher] for unit testing. * * This rule allows you to replace the main dispatcher with a test dispatcher, which can be controlled * during tests. It uses an [UnconfinedTestDispatcher] by default, but a custom [TestDispatcher] can be provided. * * Example usage: * * ```kotlin * class ExampleTest { * * @get:Rule * val coroutineTestRule = CoroutineTestRule() * * @Test * fun exampleTest() = runTest { * // Given a scenario that requires coroutines * * // When executing coroutine-based code * * // Then verify the expected outcome * } * } * ``` * * @property testDispatcher The [TestDispatcher] to be used as the main dispatcher during tests. Defaults to [UnconfinedTestDispatcher]. * */ class CoroutineTestRule( private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(), ) : TestWatcher() { /** * Sets the main dispatcher to the provided [testDispatcher] before the test starts. * * @param description The description of the test that is about to be run. */ override fun starting(description: Description?) { Dispatchers.setMain(testDispatcher) } /** * Resets the main dispatcher to the original dispatcher after the test finishes. * * @param description The description of the test that has just finished. */ override fun finished(description: Description?) { Dispatchers.resetMain() } }
8
Kotlin
1
8
ddc790d11b46a3cd19ff86aca50e86f41a1042e3
1,871
SpeziKt
MIT License
app/src/main/java/com/eneskayiklik/word_diary/feature/quiz/StudyViewModel.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.quiz import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.eneskayiklik.swiper.SwipedOutDirection import com.eneskayiklik.word_diary.R import com.eneskayiklik.word_diary.core.data_store.domain.UserPreferenceRepository import com.eneskayiklik.word_diary.core.database.entity.StudySessionEntity import com.eneskayiklik.word_diary.core.database.entity.WordEntity import com.eneskayiklik.word_diary.core.tts.WordToSpeech import com.eneskayiklik.word_diary.feature.folder_list.domain.FolderRepository import com.eneskayiklik.word_diary.core.util.UiEvent import com.eneskayiklik.word_diary.feature.word_list.domain.StudyType import com.eneskayiklik.word_diary.util.extensions.calculateProficiencyLevel import com.eneskayiklik.word_diary.util.extensions.sumOf import com.eneskayiklik.word_diary.util.extensions.sumOfAll import com.eneskayiklik.word_diary.util.extensions.sumOfAllDouble import com.eneskayiklik.word_diary.util.extensions.takeRandom import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class StudyViewModel @Inject constructor( private val folderRepo: FolderRepository, private val tts: WordToSpeech, private val userPreference: UserPreferenceRepository, savedStateHandle: SavedStateHandle ) : ViewModel() { private var _folderId: Int? = null private var _folderLang: String? = null private val _event = MutableSharedFlow<UiEvent>() val event = _event.asSharedFlow() private val _state = MutableStateFlow(StudyState()) val state = _state.asStateFlow() private var _folderWords: List<WordEntity> = emptyList() private val _wordStatistics: HashMap<WordEntity, WordStatistics> = hashMapOf() init { val folderId = savedStateHandle.get<Int>("folderId") ?: throw NullPointerException("folderId can not be null") val studyType = savedStateHandle.get<StudyType>("studyType") _state.update { it.copy(studyType = studyType) } getFolder(folderId) getWords(folderId) } fun onEvent(event: StudyEvent) { when (event) { is StudyEvent.OnWordStudyAction -> { val action = when (event.direction) { SwipedOutDirection.RIGHT -> WordStudyAction.CorrectAnswer SwipedOutDirection.LEFT -> WordStudyAction.WrongAnswer else -> event.actionType } onWordStudyAction( word = event.word, action = action, spentTime = event.totalSpentTime, isFlashcard = event.direction != null ) if (event.actionType == WordStudyAction.CorrectAnswer) { onWordStudyQuestionAnswered(event.word) } } is StudyEvent.SpeakLoud -> tts.speak(event.word.meaning, _folderLang ?: return) is StudyEvent.ShowDialog -> showDialog(event.type) StudyEvent.OnLooping -> _state.update { it.copy(isLoopingEnable = it.isLoopingEnable.not()) } StudyEvent.OnShuffle -> _state.update { it.copy(isShuffleEnable = it.isShuffleEnable.not()) } StudyEvent.OnTimer -> _state.update { it.copy(isTimerEnable = it.isTimerEnable.not()) } StudyEvent.OnSound -> _state.update { it.copy(isVoiceEnabled = it.isVoiceEnabled.not()) } StudyEvent.StartStudy -> startStudy() StudyEvent.FinishStudy -> finishStudy() } } fun onEvent(event: UiEvent) = viewModelScope.launch { _event.emit(event) } private fun showDialog(type: StudyDialogType) = viewModelScope.launch { _state.update { it.copy(dialogType = type) } } private fun startStudy() = viewModelScope.launch { if (_folderWords.isEmpty()) { onEvent(UiEvent.ShowToast(textRes = R.string.uncaught_error)) onEvent(UiEvent.ClearBackstack) return@launch } val studyState = _state.value val currentWords = if ( studyState.isShuffleEnable ) studyState.words.shuffled() else studyState.words val answers = if ( studyState.studyType == StudyType.MultipleChoice ) (_folderWords.takeRandom( 3, listOf(currentWords.first()) ) + currentWords.first()).shuffled() else emptyList() _state.update { it.copy( quizState = QuizState.Started, words = currentWords, choices = answers ) } startTimer() } private fun finishStudy() = viewModelScope.launch { val studyType = _state.value.studyType ?: return@launch val totalHintCount = _wordStatistics.sumOf { it.hintTakeCount }.toDouble() val wrongAnswerCount = _wordStatistics.sumOf { it.wrongAnswerCount }.toDouble() val correctAnswerCount = _wordStatistics.sumOf { it.correctAnswerCount }.toDouble() val totalLetterCount = when (studyType) { StudyType.Write -> _wordStatistics.sumOfAll { wordEntity, wordStatistics -> wordEntity.word.length * wordStatistics.correctAnswerCount } else -> 0 } val totalQuestionCount = _wordStatistics.sumOf { it.seenCount } val accuracy = when (studyType) { StudyType.FlashCard -> (correctAnswerCount / totalQuestionCount) * 100 StudyType.Write -> (1.0 - (totalHintCount / totalLetterCount)) * 100 StudyType.MultipleChoice -> maxOf( (1.0 - (wrongAnswerCount / (totalQuestionCount * 3))), .0 ) * 100 } if (totalQuestionCount == 0 && totalLetterCount == 0) { onEvent(UiEvent.ClearBackstack) } else { _state.update { it.copy( quizState = QuizState.Finished, studyResult = StudyResult( accuracy = accuracy, totalQuestionCount = totalQuestionCount, timeSpent = _state.value.timerText, proficiency = (_wordStatistics.sumOfAllDouble { wordEntity, wordStatistics -> wordEntity.calculateProficiencyLevel( wordStatistics, studyType = studyType, factor = 5.0 ) } + _folderWords.sumOf { w -> w.proficiency }) / _folderWords.size ) ) } updateWordsStatistics(_wordStatistics, studyType) saveSessionResult( folderId = _folderId ?: return@launch, totalTimeSpend = _state.value.spendTime, accuracy = accuracy, studyType = studyType, wordStatistics = _wordStatistics ) updateStreakCount() } } private fun updateStreakCount() = viewModelScope.launch(Dispatchers.IO) { userPreference.setStreakDay(System.currentTimeMillis()) } private fun updateWordsStatistics( wordStatistics: HashMap<WordEntity, WordStatistics>, studyType: StudyType ) = viewModelScope.launch(Dispatchers.IO) { folderRepo.updateWordStatistics(wordStatistics, studyType) } private fun saveSessionResult( folderId: Int, totalTimeSpend: Long, accuracy: Double, studyType: StudyType, wordStatistics: HashMap<WordEntity, WordStatistics> ) = viewModelScope.launch(Dispatchers.IO) { folderRepo.addStudySession( StudySessionEntity( folderId = folderId, date = System.currentTimeMillis(), timeSpent = totalTimeSpend, accuracy = accuracy, sessionType = studyType, wordsInOrder = wordStatistics.map { it.key }, statisticsInOrder = wordStatistics.map { it.value } ) ) } private fun onWordStudyQuestionAnswered(word: WordEntity) = viewModelScope.launch { val stateValue = _state.value if (_folderWords.isEmpty()) { onEvent(UiEvent.ShowToast(textRes = R.string.uncaught_error)) onEvent(UiEvent.ClearBackstack) return@launch } val currentWords = stateValue.words.toMutableList() if (currentWords.size <= 2 && stateValue.isLoopingEnable) { if (stateValue.isShuffleEnable) { var shuffled = _folderWords.shuffled() while (shuffled.first() == currentWords.last()) { shuffled = _folderWords.shuffled() } currentWords += shuffled } else { currentWords += _folderWords } } val firstIndex = currentWords.indexOfFirst { it == word } if (firstIndex >= 0) currentWords.removeAt(firstIndex) if (currentWords.isEmpty()) { finishStudy() } else { when (stateValue.studyType) { StudyType.FlashCard -> onFlashcardStudyAction(currentWords) StudyType.Write -> onWriteStudyAction(currentWords) StudyType.MultipleChoice -> onMultipleChoiceStudyAction(currentWords) else -> return@launch } } } private fun onFlashcardStudyAction(currentWords: List<WordEntity>) = viewModelScope.launch { _state.update { it.copy(words = currentWords) } } private fun onWriteStudyAction(currentWords: List<WordEntity>) = viewModelScope.launch { delay(500) _state.update { it.copy(words = currentWords) } } private fun onMultipleChoiceStudyAction(currentWords: List<WordEntity>) = viewModelScope.launch { if (currentWords.isNotEmpty()) { val answers = (_folderWords.takeRandom( 3, listOf(currentWords.first()) ) + currentWords.first()).shuffled() delay(500) _state.update { it.copy(words = currentWords, choices = answers) } } else { delay(500) _state.update { it.copy(words = currentWords, choices = emptyList()) } } } private fun onWordStudyAction( word: WordEntity, action: WordStudyAction, spentTime: Long, isFlashcard: Boolean ) = viewModelScope.launch { _wordStatistics[word] = _wordStatistics[word]?.let { WordStatistics( hintTakeCount = it.hintTakeCount + if (action == WordStudyAction.HintTaken) 1 else 0, wrongAnswerCount = it.wrongAnswerCount + if (action == WordStudyAction.WrongAnswer) 1 else 0, correctAnswerCount = it.correctAnswerCount + if (action == WordStudyAction.CorrectAnswer) 1 else 0, seenCount = it.seenCount + if (action == WordStudyAction.CorrectAnswer || isFlashcard) 1 else 0, totalSpentTime = it.totalSpentTime + spentTime ) } ?: run { WordStatistics( hintTakeCount = if (action == WordStudyAction.HintTaken) 1 else 0, wrongAnswerCount = if (action == WordStudyAction.WrongAnswer) 1 else 0, correctAnswerCount = if (action == WordStudyAction.CorrectAnswer) 1 else 0, seenCount = if (action == WordStudyAction.CorrectAnswer || isFlashcard) 1 else 0, totalSpentTime = spentTime ) } } private fun startTimer() = viewModelScope.launch(Dispatchers.IO) { val initialTime = System.currentTimeMillis() while (_state.value.quizState == QuizState.Started) { delay(1000) val currentTime = System.currentTimeMillis() - initialTime _state.update { it.copy(spendTime = currentTime) } } } private fun getFolder( folderId: Int ) = viewModelScope.launch(Dispatchers.IO) { _folderId = folderId folderRepo.getFolder(folderId).collectLatest { folder -> _folderLang = folder.folderLangCode _state.update { it.copy(folder = folder) } } } private fun getWords( folderId: Int ) = viewModelScope.launch(Dispatchers.IO) { _folderId = folderId folderRepo.getWords(folderId).collectLatest { words -> if (_folderWords.isEmpty()) { _folderWords = words _state.update { it.copy(words = words) } } } } }
0
Kotlin
0
1
b516446a47cd56b3ff07f17fc588f0b2409a1f2c
13,218
WordDiary
MIT License
platform/vcs-impl/src/com/intellij/vcs/commit/CommitProgressPanel.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.icons.AllIcons import com.intellij.ide.nls.NlsMessages.formatNarrowAndList import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.TooltipDescriptionProvider import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.AppUIExecutor.onUiThread import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.progress.util.ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsBundle.messagePointer import com.intellij.openapi.vcs.changes.InclusionListener import com.intellij.openapi.wm.ex.ProgressIndicatorEx import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.ui.AnimatedIcon import com.intellij.ui.EditorTextComponent import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.util.ui.HtmlPanel import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.UIUtil.getErrorForeground import com.intellij.util.ui.UIUtil.getLabelFont import com.intellij.util.ui.update.Activatable import com.intellij.util.ui.update.UiNotifyConnector import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.jetbrains.annotations.Nls import java.awt.Dimension import java.awt.Font import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.event.HyperlinkEvent import kotlin.properties.Delegates.observable private fun JBLabel.setError(@NlsContexts.Label errorText: String) { text = errorText icon = AllIcons.General.Error foreground = getErrorForeground() isVisible = true } private fun JBLabel.setWarning(@NlsContexts.Label warningText: String) { text = warningText icon = AllIcons.General.Warning foreground = null isVisible = true } open class CommitProgressPanel : NonOpaquePanel(VerticalLayout(4)), CommitProgressUi, InclusionListener, DocumentListener, Disposable { private val scope = CoroutineScope(SupervisorJob() + onUiThread().coroutineDispatchingContext()) .also { Disposer.register(this) { it.cancel() } } private val progressFlow = MutableStateFlow<CommitChecksProgressIndicator?>(null) private var progress: CommitChecksProgressIndicator? by progressFlow::value private val failuresPanel = FailuresPanel() private val label = JBLabel().apply { isVisible = false } override var isEmptyMessage: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable update() } override var isEmptyChanges: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable update() } override var isDumbMode: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable update() } fun setup(commitWorkflowUi: CommitWorkflowUi, commitMessage: EditorTextComponent) { add(label) add(failuresPanel) Disposer.register(commitWorkflowUi, this) commitMessage.addDocumentListener(this) commitWorkflowUi.addInclusionListener(this, this) setupShowProgressInStatusBar() setupProgressVisibilityDelay() setupProgressSpinnerTooltip() } private fun setupShowProgressInStatusBar() = Disposer.register(this, UiNotifyConnector(this, object : Activatable { override fun showNotify() { progress?.let { removeFromStatusBar(it) } } override fun hideNotify() { progress?.let { addToStatusBar(it) } } })) @Suppress("EXPERIMENTAL_API_USAGE") private fun setupProgressVisibilityDelay() { progressFlow .debounce(DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS.toLong()) .onEach { indicator -> if (indicator?.isRunning == true && failuresPanel.isEmpty()) indicator.component.isVisible = true } .launchIn(scope + CoroutineName("Commit checks indicator visibility")) } private fun setupProgressSpinnerTooltip() { val tooltip = CommitChecksProgressIndicatorTooltip({ progress }, { failuresPanel.width }) tooltip.installOn(failuresPanel.iconLabel, this) } override fun dispose() = Unit override fun startProgress(): ProgressIndicatorEx { check(progress == null) { "Commit checks indicator already created" } val indicator = InlineCommitChecksProgressIndicator() Disposer.register(this, indicator) indicator.component.isVisible = false indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() { override fun start() = progressStarted() override fun stop() = progressStopped() }) progress = indicator indicator.start() return indicator } private fun progressStarted() { add(progress!!.component) // we assume `isShowing == true` here - so we do not need to add progress to status bar failuresPanel.clearFailures() } private fun progressStopped() { progress!!.let { remove(it.component) removeFromStatusBar(it) Disposer.dispose(it) } progress = null failuresPanel.endProgress() } private fun addToStatusBar(progress: CommitChecksProgressIndicator) { val frame = WindowManagerEx.getInstanceEx().findFrameFor(null) ?: return val statusBar = frame.statusBar as? StatusBarEx ?: return statusBar.addProgress(progress, CommitChecksTaskInfo()) } private fun removeFromStatusBar(progress: CommitChecksProgressIndicator) = // `finish` tracks list of finished `TaskInfo`-s - so we pass new instance to remove from status bar progress.finish(CommitChecksTaskInfo()) override fun addCommitCheckFailure(text: String, detailsViewer: () -> Unit) { progress?.component?.isVisible = false failuresPanel.addFailure(CommitCheckFailure(text, detailsViewer)) } override fun clearCommitCheckFailures() = failuresPanel.clearFailures() override fun documentChanged(event: DocumentEvent) = clearError() override fun inclusionChanged() = clearError() protected fun update() { val error = buildErrorText() when { error != null -> label.setError(error) isDumbMode -> label.setWarning(message("label.commit.checks.not.available.during.indexing")) else -> label.isVisible = false } } protected open fun clearError() { isEmptyMessage = false isEmptyChanges = false } @NlsContexts.Label protected open fun buildErrorText(): String? = when { isEmptyChanges && isEmptyMessage -> message("error.no.changes.no.commit.message") isEmptyChanges -> message("error.no.changes.to.commit") isEmptyMessage -> message("error.no.commit.message") else -> null } } private class CommitCheckFailure(@Nls val text: String, val detailsViewer: () -> Unit) private class FailuresPanel : JBPanel<FailuresPanel>() { private var nextFailureId = 0 private val failures = mutableMapOf<Int, CommitCheckFailure>() val iconLabel = JBLabel() private val description = FailuresDescriptionPanel() init { layout = BoxLayout(this, BoxLayout.X_AXIS) add(iconLabel) add(description.apply { border = empty(4, 4, 0, 0) }) add(createCommitChecksToolbar(this).component) isOpaque = false isVisible = false } fun isEmpty(): Boolean = failures.isEmpty() fun clearFailures() { isVisible = false iconLabel.icon = null failures.clear() update() } fun addFailure(failure: CommitCheckFailure) { isVisible = true iconLabel.icon = AnimatedIcon.Default() failures[nextFailureId++] = failure update() } fun endProgress() { isVisible = failures.isNotEmpty() if (isVisible) iconLabel.icon = AllIcons.General.Warning } private fun update() { description.failures = failures description.update() } } private class FailuresDescriptionPanel : HtmlPanel() { private val isInitialized = true // workaround as `getBody()` is called from super constructor var failures: Map<Int, CommitCheckFailure> = emptyMap() // For `BoxLayout` to layout "commit checks toolbar" right after failures description override fun getMaximumSize(): Dimension { val size = super.getMaximumSize() if (isMaximumSizeSet) return size return Dimension(size).apply { width = preferredSize.width } } override fun getBodyFont(): Font = getLabelFont() override fun getBody(): String = if (isInitialized) buildDescription().toString() else "" override fun hyperlinkUpdate(e: HyperlinkEvent) = showDetails(e) private fun buildDescription(): HtmlChunk { if (failures.isEmpty()) return HtmlChunk.empty() val failuresLinks = formatNarrowAndList(failures.map { HtmlChunk.link(it.key.toString(), it.value.text) }) return HtmlChunk.raw(message("label.commit.checks.failed", failuresLinks)) } private fun showDetails(event: HyperlinkEvent) { if (event.eventType != HyperlinkEvent.EventType.ACTIVATED) return val failure = failures[event.description.toInt()] ?: return failure.detailsViewer() } } private fun createCommitChecksToolbar(target: JComponent): ActionToolbar = ActionManager.getInstance().createActionToolbar( "ChangesView.CommitChecksToolbar", DefaultActionGroup(RerunCommitChecksAction()), true ).apply { setTargetComponent(target) (this as? ActionToolbarImpl)?.setForceMinimumSize(true) // for `BoxLayout` setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY component.isOpaque = false component.border = null } private class RerunCommitChecksAction : EmptyAction.MyDelegatingAction(ActionManager.getInstance().getAction("Vcs.RunCommitChecks")), TooltipDescriptionProvider { init { templatePresentation.apply { setText(Presentation.NULL_STRING) setDescription(messagePointer("tooltip.rerun.commit.checks")) icon = AllIcons.General.InlineRefresh hoveredIcon = AllIcons.General.InlineRefreshHover } } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
10,804
intellij-community
Apache License 2.0
app/src/main/java/com/craftyblue/gpssjetnik/alpha/MapActivity.kt
craftyBLUE
798,477,194
false
{"Kotlin": 39434}
package com.craftyblue.gpssjetnik.alpha import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.preference.PreferenceManager import android.util.DisplayMetrics import android.util.Log import android.widget.Button import android.widget.EditText import androidx.core.app.ActivityCompat import org.osmdroid.config.Configuration.getInstance import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.util.TileSystem import org.osmdroid.views.MapView import org.osmdroid.views.overlay.ItemizedIconOverlay import org.osmdroid.views.overlay.ItemizedOverlayWithFocus import org.osmdroid.views.overlay.MapEventsOverlay import org.osmdroid.views.overlay.Marker import org.osmdroid.views.overlay.OverlayItem import org.osmdroid.views.overlay.Polygon import org.osmdroid.views.overlay.ScaleBarOverlay import org.osmdroid.views.overlay.gestures.RotationGestureOverlay import kotlin.math.roundToInt lateinit var map : MapView lateinit var currentLocationCircle : TriggerRadius fun refreshTriggers(context: Context) { var displayPins = displayPinAdapter.getDisplayPins() for (i in 0..<displayPins.size) { val circle = TriggerRadius(map) circle.points = Polygon.pointsAsCircle(GeoPoint(displayPins[i].location.latitude, displayPins[i].location.longitude), displayPins[i].radius) circle.fillPaint.color = 0x12121212 circle.outlinePaint.color = 0xFFFF0000.toInt() circle.outlinePaint.strokeWidth = 4f map.overlays.add(circle) } val items = ArrayList<OverlayItem>() //items.add(OverlayItem("Title", "Description", GeoPoint(0.0, 0.0))) for (i in 0..<displayPins.size) { items.add(OverlayItem( displayPins[i].alarmTitle, "${displayPins[i].location.latitude}, ${displayPins[i].location.longitude}\n" + "Trigger radius: ${displayPins[i].radius}m\n" + "Distance: ${displayPins[i].distance.roundToInt()}m", GeoPoint(displayPins[i].location.latitude, displayPins[i].location.longitude))) } var itemsOverlay = ItemizedOverlayWithFocus<OverlayItem>(items, object: ItemizedIconOverlay.OnItemGestureListener<OverlayItem> { override fun onItemSingleTapUp(index:Int, item:OverlayItem):Boolean { //do something Log.d("map tap", "${index} tap") return true } override fun onItemLongPress(index:Int, item:OverlayItem):Boolean { Log.d("map tap", "${index} long press") return true } }, context) itemsOverlay.setFocusItemsOnTap(true); map.overlays.add(itemsOverlay); } fun refreshMapOverlays(context: Context) { map.overlays.clear() val dm : DisplayMetrics = context.resources.displayMetrics val scaleBarOverlay = ScaleBarOverlay(map) scaleBarOverlay.setCentred(true) scaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 10) map.overlays.add(scaleBarOverlay) //https://github.com/osmdroid/osmdroid/issues/295#issuecomment-1044323136 <3 val mapEventsReceiver = MapEventsReceiverImpl(map) val mapEventsOverlay = MapEventsOverlay(mapEventsReceiver) map.overlays.add(mapEventsOverlay) refreshTriggers(context) } fun initMap(context: Context) { map.setTileSource(TileSourceFactory.MAPNIK) map.setMultiTouchControls(true) map.isHorizontalMapRepetitionEnabled = true map.isVerticalMapRepetitionEnabled = false map.controller.setZoom(13) map.isTilesScaledToDpi = true map.controller.setCenter(GeoPoint(currentLocationPin.latitude, currentLocationPin.longitude)) /*var compassOverlay = CompassOverlay(applicationContext, InternalCompassOrientationProvider(applicationContext), map) compassOverlay.enableCompass() map.overlays.add(compassOverlay)*/ /*val overlayGrid = LatLonGridlineOverlay2() map.overlays.add(overlayGrid)*/ centerMarker = Marker(map) circleTrigger = TriggerRadius(map) refreshMapOverlays(context) //mapInitialized = true } fun initCurrentLocationCircle() { currentLocationCircle = TriggerRadius(map) currentLocationCircle.fillPaint.color = 0x24121224 currentLocationCircle.outlinePaint.color = 0xFF0000FF.toInt() currentLocationCircle.outlinePaint.strokeWidth = 4f } fun displayCurrentLocation() { if (map.overlays.contains(currentLocationCircle)) { map.overlays.remove(currentLocationCircle) } currentLocationCircle.points = Polygon.pointsAsCircle( GeoPoint(currentLocationPin.latitude, currentLocationPin.longitude), currentLocationPin.accuracy.toDouble() ) map.overlays.add(currentLocationCircle) map.invalidate() } class MapActivity : Activity() { private val REQUEST_PERMISSIONS_REQUEST_CODE = 1 //lateinit var binding : ActivityMapBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //binding = ActivityMapBinding.inflate(layoutInflater) //setContentView(binding.root) getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this)) setContentView(R.layout.activity_map) map = findViewById<MapView>(R.id.map) //map = binding.map initMap(applicationContext) initCurrentLocationCircle() val rotationGestureOverlay = RotationGestureOverlay(map) var freeRotateButton = findViewById<Button>(R.id.freeRotationButton) freeRotateButton.setOnClickListener { if (map.overlays.contains(rotationGestureOverlay)) { map.overlays.remove(rotationGestureOverlay) map.mapOrientation = 0.0f } else { map.overlays.add(rotationGestureOverlay) } map.invalidate() } var addTriggerButton = findViewById<Button>(R.id.addTriggerButton) var titleEditText = findViewById<EditText>(R.id.titleEditText) addTriggerButton.setOnClickListener { displayPinAdapter.addPin( DisplayPin(geoPointToLocation(centerMarker.position), circleTriggerRadius, "activeNotTriggered", titleEditText.text.toString())) titleEditText.setText("") displayPinAdapter.saveState() refreshMapOverlays(applicationContext) } displayCurrentLocation() } override fun onResume() { super.onResume() map.onResume() registerReceiver(broadcastReceiver, IntentFilter(ACTION_LOCATION_CHANGED), RECEIVER_NOT_EXPORTED) } override fun onPause() { super.onPause() unregisterReceiver(broadcastReceiver) map.onPause() } private val broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == ACTION_LOCATION_CHANGED) { displayCurrentLocation() } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) val permissionsToRequest = ArrayList<String>() var i = 0 while (i < grantResults.size) { permissionsToRequest.add(permissions[i]) i++ } if (permissionsToRequest.size > 0) { ActivityCompat.requestPermissions( this, permissionsToRequest.toTypedArray(), REQUEST_PERMISSIONS_REQUEST_CODE) } } }
0
Kotlin
0
0
57b80630af23b8d387659b7b627eb3588c4791f5
7,280
GPS-Sjetnik
Apache License 2.0
shared/src/commonMain/kotlin/com/multiplatform/kmmcc/data/sources/local/filereader/LocalJsonExceptionParser.kt
shahrozekhan
735,403,154
false
{"Kotlin": 117840, "Ruby": 2612, "Swift": 602}
package com.multiplatform.kmmcc.data.sources.local.filereader import io.ktor.serialization.* class LocalJsonExceptionParser{ fun logParseDisplayMessage(exception: Exception): String { exception.printStackTrace() return when (exception) { is JsonConvertException -> { "Uable to parse" } else -> { "An expected exception occurred!" } } } }
0
Kotlin
2
7
440b9960e956c32896766de2b9048c793eeb370b
453
KMPCurrencyConvertor
MIT License
secdra-admin/src/main/kotlin/com/junjie/secdraadmin/constant/UserConstant.kt
fuzeongit
154,359,683
false
null
package com.junjie.secdraadmin.constant object UserConstant { val nameList = listOf( "醉挽清风", "素衣清颜淡若尘", "夜雨微澜", "以往的誓言", "墨玲珑", "天生傲骨岂能输", "凉薄少女夢", "若只如初见", "秦凝雪月", "镜湖月", "霓裳晚歌", "扬眉共醉", "夏末涼薄", "浪子回头", "青袂婉约", "悔恨当初", "妄念", "不离不弃只是童言无忌", "爱海搁浅", "百合", "浅吟旧情歌", "嫣然一笑", "南玖", "冷心为王", "烟寒若雨", "未语淚先流", "孤音", "浅浅爱", "暮白寒窗雪", "爱在千年梦", "小豆豆", "夏至春掩", "花容月貌为谁妍", "暧昧无关爱情", "奶油桃子", "安之若素", "若遇浅香", "女王霸气", "奈我何", "离夏惜柚子", "夕颜泪痕", "垂耳兔", "蒹葭萋萋,白露未晞", "芯茹芷水", "心如止水", "潇湘夜雨", "一生的爱意", "慕绾晴", "白了少年头", "纵是情长不抵时光", "流光未至", "青莲白雾", "清晓花浅笑", "如梦亦如幻", "笛声何处", "微笑天使", "暖于心", "我是柠檬满是心酸", "青草香氕", "黎夕旧梦", "花落半歌", "年少怎能不多情", "蓝天下的迷彩", "抹布女", "落泪玫瑰", "晴雨天", "此籹子不需要谁来怜惜", "笑到全世界流泪", "梦瑶朵", "十梦九他", "神庙女郎", "半面妆", "南筏", "影伴人久", "冰浅丹青", "晏清窈", "半世晨光", "烟花巷陌", "孤凉", "余默", "凌末语", "飘逸的云", "令若馨", "不会游泳的鱼", "染黛如诗", "萝莉萌主", "醜柒恠", "非洲小白脸", "毫无代价", "纯粹剪爱", "小水滴", "浮梦儿", "日光边境", "若无回忆如何祭奠", "顏夕未歌", "悦诗风吟", "浅夏忆汐", "浅夏琉璃", "繁花散尽", "泪湿青衫", "甜心宝贝", "轻叹花开", "忆清绝", "孤惯", "骨髓里的爱", "陌秋漓", "冬天的雪花", "諵笙", "爱伊梦雪", "雨落雨兮", "发尾与风", "琉璃月", "一缕阳光", "柒月兔子", "亲吻的双鱼", "北港不夏", "漫里风铃音", "纪嫣然", "雨末春晓", "叆叇若紫", "凉薄之人", "曲水无言戏年月", "莫忧离", "慕思瑶", "心已赠人", "冰花雪儿", "狐狸已成精", "米兔兔", "北遇长安", "柠檬为何心酸", "醉沙疆", "雪千寻", "嬡暀苝漂", "故巷旧梦", "我拿青春赌明天", "水月蓝心", "绿水染清风", "南拥夏栀", "聆听风音", "墨染青衣颜", "水袖萦香", "沉香如屑", "雪花拥抱阳光", "离沐倾城", "季节温暖眼瞳", "青春躁動", "漫步繁华街", "将回忆化作烈酒", "干净无过往", "何以为安", "多情必自毙", "冰泪紫茉", "空谷幽兰", "风中雨荷", "忧烟殇往", "一挽青丝", "花开蝶相护", "Sunny晴天", "缘起缘灭", "蝶き梦", "優殤繞指揉", "半城月色半城殇", "我把萧再叹", "樱染", "爱你如初", "夏了南城", "雨馨", "海上花", "时光凉人心", "冰诺飞雪", "流光夏央", "喜留厌走别回头", "女王范", "再见当时", "莛寒梦阮", "落安言", "紫陌蝶", "恬矜儿", "微雨花间", "烟雨蒙蒙", "趁年轻", "伊人恃宠而骄", "晚街听风", "云清璃", "小小怪同学", "桃色玫瑰", "安初夏", "茉莉花", "伴旅", "时光旧巷的少女", "一曦时光", "花小染", "橘柚香", "青涩不及当初", "落幕流苏", "人逝花空", "姐很高,也很傲", "做你怀中小仙女", "抱不住太阳的深海", "一纸荒年", "诗人礼献", "昭谷蓝", "花湮苍笙泪", "七街城酒", "回不去的从前", "猫贪余温", "伴你終老", "权欲萌妹", "花伊自在美", "给脸别傲", "墨染锦年", "尘烟梦雨如墨染", "柒月过后", "柳淡烟", "淡紫色梦境", "伴你久旧", "夏末烟雨", "白灵雪", "画眉如黛", "梦阮尘", "天风海涛", "雪后初暖阳", "一纸水与青", "鹿畔阳光", "傲雪寒梅", "浮生三月初", "雨季莫忧离", "化蝶飞", "不思量ミ自难忘", "蝴蝶为花碎花却随风飞", "右耳环想念", "愿君安好", "墨茜魅", "勿忘心安", "断桥残月", "殇残云", "筙鈤煴揂", "女人活着要有范", "水铃蓝", "阳光不暖人心", "旧城少年", "感情废物", "回头太难", "肩膀的忧伤", "薰衣草花", "青柠衬酸", "绚烂的笑", "久夏青", "过分着迷", "红尘雪", "何必想太多", "酒伴孤独", "橘子味的香蕉", "轻缣素练", "女人堅強便是王", "冷殘夜魅", "浮生若梦", "寄你欢颜", "叶散冰离", "南鸢北筏", "借雨尽凄凉", "旧港听风", "云中朵", "浅凝半夏", "花凌若别离", "念旧", "沙漏里的时光", "一别两宽", "森林牧歌", "落笔画忧愁", "倾心所爱", "姐很宅但不腐", "一抹妖娆", "依恋雨", "素手绾青丝", "心已碎何安慰", "绿水染清风", "泛起酒窝", "东京纷飞旳樱花", "孤街酒客", "夜閑清瑩夢落花", "半城繁華半城傷", "半夏微澜", "顾凉", "浅唁风雨", "涵梦若仙", "安忆雅", "衾枕寒", "落阳一地的殇", "听风看月", "远山如黛", "抓的越紧失去更快", "绯色琉璃", "若小夕", "喵了个汪", "北墓南笙", "南离", "纵有风云起", "南萱儿", "洛灵兮", "公紸吥乖", "柒夏锦年", "貌芳瓷脂", "南风草木香", "抹茶夏天", "琼梦", "忆缱绻", "凌云児", "栀璃鸢年", "岛屿失梦", "音影幻樱", "静夏夜", "一枝花", "打碎面具", "孤海未蓝", "孤街凉巷", "卷帘望月", "孤守一城静待花开", "春天秋水", "芦苇浅浅", "一米阳光", "独守空房", "黎熙熙", "胭脂泪痕", "你没药", "转身你已卟在", "香椿丛林", "樟木板轻拍案", "相爱莫相离", "因为是女子", "玲珑风", "梦屿千寻", "森芋暖暖", "最佳恋人", "轻寒", "故事与旧友", "千山林映雪", "顾安然", "一个转身两个世界", "淡月琉殇", "陌上柳絮傾城雪", "紫吟调", "乖乖兔", "伪天使", "好景不长", "掉控的木偶", "紫梦雅馨", "北沐城歌", "隐匿与心", "夏风如歌", "惊世妖娆", "瑜锦婼殇", "柚子熟了", "浮伤年华ㄣ撒下一地悲凉", "樱花皇后", "江南慕雨", "花朵朵", "素颜如水", "诗霜", "柠檬加醋好心酸", "三千纷繁", "月露桂枝香", "薄情", "繁华已尽", "纯白梵唱", "时年七月", "我很丑", "ー季花开花落", "素兮绕眉", "习惯", "傲姿", "星如雨", "卿幽悠", "莫筱夜", "冰薇", "弯刀眉", "眉目情", "静以修身", "抹茶少女", "秋水伊人", "花开馥郁", "夏未夜微凉", "野媚倾情", "昙花一现", "冷如香", "一世温暖", "叫醒耳朵", "倾尽天下", "倾听梦里花落声", "感情最狗", "下雪次日温暖的光", "如花的旋律", "千山暮雪", "离开我就不要回头", "暮雨而桐", "雨天是我孤独的时候", "微凉的倾城时光", "纸上诺言", "啷个哩个啷", "别怂", "固执", "夕阳下边", "一曲一场叹", "雪落纷纷", "笨吖頭", "微笑是你的唯一", "璇玑涟漪", "芣苢惜凉", "魅雪灵", "酷与孤独", "媚欣焉紫", "萌趴趴", "旧事酒浓", "待我强大给我媳妇一片天下", "暖若安阳", "冷雨葬花", "梦笙", "六弦绿漪", "乖囧猫", "心缘之梦", "撩心不撩汉", "如梦歌", "伊人若梦", "夏末未至允奈", "寂寞的眼泪", "青树柠檬", "两人的开始", "失她失心", "一笑奈何", "漫雪独思", "枯叶蝶的伤", "南月泠雪", "梦儿", "凉人梦", "森蝶呦", "时光待我如初", "半夏微澜", "泽畔东篱", "华年乱了谁的浮生", "紫色风铃幻想", "踏花游湖", "忘川秋叶", "别吵醒寂寞", "当年华褪去生涩", "爱吃甜筒的猫", "柒墨姬", "时有幽花", "森花", "方蕊", "树深时见鹿", "各自生欢", "葱郁风光", "风清淡雅", "柳忆莲", "鹿痴", "喃城旧梦", "无言情话", "彼岸雨露", "百里红妆", "北蒙岛的雨季", "野心少女", "绾千念", "注定孤独无依", "把你藏心里", "抹卜掉的伤痛", "久孤", "情话烫心", "紫陌红尘", "走心小迷妹", "花残满地殇", "梦醒时分", "婧婧的旋转", "天羽葵", "清柠", "歌岛礼失", "紫陌寒", "一米阳光", "花月夜", "一只酷宝贝", "江南烟雨断桥殇", "暮雨浔茶", "赋词半阙", "任心荒芜", "高山流水", "惠采晨", "攒一身善良", "蝴蝶结", "南宫静远", "古雪娃", "你最倾城", "落叶飘零", "浅夏初晴", "糖果控", "瑶风韵蕊", "北岸初晴", "倾弦", "柚子味儿的西瓜" ) }
1
Kotlin
4
11
f75c32e5fb834d456a3182f71aee08029a1629d3
10,167
secdra
MIT License
src/main/java/teksturepako/greenery/common/util/FileUtils.kt
juraj-hrivnak
479,669,760
false
{"Kotlin": 126166, "Java": 731}
package teksturepako.greenery.common.util import java.io.File object FileUtils { operator fun File.div(subFileName: String): File { this.mkdirs() val file = File(this, subFileName) file.mkdirs() return file } }
7
Kotlin
3
9
839c0d449af95d2c6c582f67463ad3f811646342
256
Greenery
MIT License
app/src/test/java/dev/patrickgold/florisboard/snygg/SnyggRuleTest.kt
florisboard
254,202,848
false
null
package dev.patrickgold.florisboard.ime.snygg import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.shouldBe class SnyggRuleTest : FreeSpec({ val validTestPairs = listOf( "button" to SnyggRule(element = "button"), "button-name" to SnyggRule(element = "button-name"), "button042" to SnyggRule(element = "button042"), "button4-test1" to SnyggRule(element = "button4-test1"), "button[code=113]" to SnyggRule(element = "button", codes = listOf(113)), "button[code=-113]" to SnyggRule(element = "button", codes = listOf(-113)), "button[code=113|212]" to SnyggRule(element = "button", codes = listOf(113,212)), "button[code=113][group=1]" to SnyggRule(element = "button", codes = listOf(113), groups = listOf(1)), "button:hover" to SnyggRule(element = "button", hoverSelector = true), "button:focus" to SnyggRule(element = "button", focusSelector = true), "button:pressed" to SnyggRule(element = "button", pressedSelector = true), "button:hover:focus" to SnyggRule(element = "button", hoverSelector = true, focusSelector = true), "button:hover:pressed" to SnyggRule(element = "button", hoverSelector = true, pressedSelector = true), "button:focus:pressed" to SnyggRule(element = "button", focusSelector = true, pressedSelector = true), "button:hover:focus:pressed" to SnyggRule(element = "button", hoverSelector = true, focusSelector = true, pressedSelector = true), "button[code=113][group=1]:pressed" to SnyggRule(element = "button", codes = listOf(113), groups = listOf(1), pressedSelector = true), ) "Test SnyggRule.from()" - { validTestPairs.forEach { (ruleStr, ruleObj) -> "`$ruleStr`" { SnyggRule.from(ruleStr) shouldBe ruleObj } } } "Test SnyggRule.from() with invalid input" - { listOf( "", " ", "button_name", ".button", "#button", "[code=1]", "button#id", "button[code=]", "button[group]", "button[mode=normal]", "button::hover", "button::focus", "button::pressed", ).forEach { ruleStr -> "`$ruleStr` should be null" { SnyggRule.from(ruleStr) shouldBe null } } } "Test SnyggRule.toString()" - { validTestPairs.forEach { (ruleStr, ruleObj) -> "`$ruleStr`" { ruleObj.toString() shouldBe ruleStr } } } })
394
null
150
2,043
bce5199e311d7048ffad14d7421b18a8f9997d24
2,618
florisboard
Apache License 2.0
app/src/main/java/com/minitel/toolboxlite/presentation/viewmodels/SettingsViewModel.kt
Darkness4
394,768,787
false
null
package com.minitel.toolboxlite.presentation.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.minitel.toolboxlite.domain.repositories.CalendarSettingsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor(private val calendarSettingsRepository: CalendarSettingsRepository) : ViewModel() { val calendarSettings = calendarSettingsRepository.watch() .stateIn(viewModelScope, SharingStarted.Lazily, null) val earlyMinutes = MutableStateFlow(0.0f) init { viewModelScope.launch(Dispatchers.Default) { calendarSettings.collect { it?.let { earlyMinutes.value = it.earlyMinutes.toFloat() } } } viewModelScope.launch(Dispatchers.Default) { earlyMinutes.collect { if (calendarSettings.value != null) { calendarSettingsRepository.update(it.toLong()) } } } } private val _openLicences = MutableStateFlow<Unit?>(null) val openLicences: StateFlow<Unit?> get() = _openLicences fun doOpenLicences() { _openLicences.value = Unit } fun openLicencesDone() { _openLicences.value = null } private val _openAbout = MutableStateFlow<Unit?>(null) val openAbout: StateFlow<Unit?> get() = _openAbout fun doOpenAbout() { _openAbout.value = Unit } fun openAboutDone() { _openAbout.value = null } }
7
Kotlin
0
2
3e8b4c18c115237676a76df8c7bcac39be59dcee
1,910
minitel-toolbox-lite
MIT License
devbricksx-compiler/src/main/kotlin/com/dailystudio/devbricksx/ksp/helper/FunctionNames.kt
dailystudio
264,874,323
false
null
package com.dailystudio.devbricksx.ksp.helper enum class FunctionNames { GET_ONE, GET_ONE_LIVE, GET_ONE_FLOW, GET_ALL, GET_ALL_LIVE, GET_ALL_DATA_SOURCE, GET_ALL_FLOW, GET_ALL_LIVE_PAGED, GET_ALL_PAGING_SOURCE, GET_ALL_PAGING_DATA, INSERT, UPDATE, INSERT_OR_UPDATE, DELETE; companion object { fun toWrappedFunc(nameOfFunc: String): String { return buildString { append('_') append(nameOfFunc) } } fun toWrapperFunc(nameOfFunc: String): String { return nameOfFunc.removePrefix("_") } fun nameOfParamInWrappedFunc(nameOfParam: String): String { return buildString { append(nameOfParam) append('_') } } } fun nameOfFunc(): String { val parts = this.name.split("_") return buildString { for ((i, part) in parts.withIndex()) { if (i == 0) { append(part.lowercase()) } else { append(part.lowercase().capitalizeName()) } } } } fun nameOfFuncForType(typeName: String): String { return nameOfFuncForType(typeName, false) } fun nameOfFuncForType(typeName: String, plural: Boolean): String { val nameOfFunc = nameOfFunc() return if (nameOfFunc.contains("getOne")) { nameOfFunc.replaceFirst("getOne", "get${typeName}") } else if (nameOfFunc.contains("getAll")) { nameOfFunc.replaceFirst("getAll", "getAll${typeName}s") } else { buildString { append(nameOfFunc) append(typeName.capitalizeName()) if (plural) { append('s') } } } } fun nameOfPropFuncForType(typeName: String): String { val nameOfFunc = nameOfFunc() return if (nameOfFunc.contains("getOne")) { nameOfFunc.replaceFirst("getOne", "${typeName.lowerCamelCaseName()}") } else if (nameOfFunc.contains("getAll")) { nameOfFunc.replaceFirst("getAll", "all${typeName}s") } else { throw Exception("prop is NOT supported on input function.") } } fun nameOfFuncForCompanion(): String { return toWrappedFunc(nameOfFunc()) } }
1
null
6
63
d62d4b989cb62100700ce540633732b42da7c4f0
2,453
devbricksx-android
Apache License 2.0
app/src/main/java/com/revolgenx/anilib/ui/fragment/home/season/SeasonFragment.kt
rev0lgenX
244,410,204
false
null
package com.revolgenx.anilib.ui.fragment.home.season import android.os.Bundle import android.widget.TextView import com.otaliastudios.elements.Adapter import com.otaliastudios.elements.Presenter import com.otaliastudios.elements.Source import com.otaliastudios.elements.extensions.HeaderSource import com.otaliastudios.elements.extensions.SimplePresenter import com.revolgenx.anilib.R import com.revolgenx.anilib.constant.MediaTagFilterTypes import com.revolgenx.anilib.infrastructure.event.ListEditorResultEvent import com.revolgenx.anilib.infrastructure.event.TagEvent import com.revolgenx.anilib.data.field.TagField import com.revolgenx.anilib.data.field.TagState import com.revolgenx.anilib.data.field.home.SeasonField import com.revolgenx.anilib.common.ui.fragment.BasePresenterFragment import com.revolgenx.anilib.data.model.CommonMediaModel import com.revolgenx.anilib.common.preference.getUserGenre import com.revolgenx.anilib.common.preference.getUserTag import com.revolgenx.anilib.data.field.TagChooserField import com.revolgenx.anilib.infrastructure.event.SeasonEvent import com.revolgenx.anilib.infrastructure.source.home.discover.MediaFormatHeaderSource import com.revolgenx.anilib.ui.dialog.TagChooserDialogFragment import com.revolgenx.anilib.ui.presenter.season.SeasonPresenter import com.revolgenx.anilib.util.registerForEvent import com.revolgenx.anilib.util.unRegisterForEvent import com.revolgenx.anilib.ui.viewmodel.home.season.SeasonViewModel import com.revolgenx.anilib.util.EventBusListener import okhttp3.internal.notify import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.koin.androidx.viewmodel.ext.android.viewModel class SeasonFragment : BasePresenterFragment<CommonMediaModel>(), EventBusListener { private val viewModel by viewModel<SeasonViewModel>() override val basePresenter: Presenter<CommonMediaModel> by lazy { SeasonPresenter(requireContext()) } override val loadingPresenter: Presenter<Unit> get() = Presenter.forLoadingIndicator( requireContext(), R.layout.season_shimmer_loader_layout ) override val baseSource: Source<CommonMediaModel> get() { return viewModel.source ?: createSource() } override fun createSource(): Source<CommonMediaModel> { return viewModel.createSource() } override fun onActivityCreated(savedInstanceState: Bundle?) { if (savedInstanceState == null) { viewModel.field = SeasonField.create(requireContext()) getUserTag(requireContext()).forEach { viewModel.field.tagTagFields[it] = TagField(it, TagState.EMPTY) } getUserGenre(requireContext()).forEach { viewModel.field.genreTagFields[it] = TagField(it, TagState.EMPTY) } viewModel.field.genres?.forEach { viewModel.field.genreTagFields[it]?.tagState = TagState.TAGGED } viewModel.field.tags?.forEach { viewModel.field.tagTagFields[it]?.tagState = TagState.TAGGED } } super.onActivityCreated(savedInstanceState) initListener() } private fun initListener() { } override fun onStart() { super.onStart() registerForEvent() } private fun renewAdapter() { viewModel.field.updateFields(requireContext()) createSource() invalidateAdapter() } override fun adapterBuilder(): Adapter.Builder { val builder = super.adapterBuilder() if (viewModel.isHeaderEnabled()) { builder.addSource(MediaFormatHeaderSource(requireContext())) builder.addPresenter( SimplePresenter<HeaderSource.Data<CommonMediaModel, String>>( requireContext(), R.layout.header_presenter_layout, HeaderSource.ELEMENT_TYPE ) { v, header -> (v as TextView).text = header.header }) } return builder } @Subscribe fun onTagEvent(event: TagEvent) { when (event.tagType) { MediaTagFilterTypes.SEASON_TAG -> { event.tagFields.forEach { viewModel.field.tagTagFields[it.tag]?.tagState = it.tagState } viewModel.field.tags = event.tagFields.filter { it.tagState == TagState.TAGGED }.map { it.tag } .toList() viewModel.field.saveTags(requireContext()) renewAdapter() } MediaTagFilterTypes.SEASON_GENRE -> { event.tagFields.forEach { viewModel.field.genreTagFields[it.tag]?.tagState = it.tagState } viewModel.field.genres = event.tagFields.filter { it.tagState == TagState.TAGGED }.map { it.tag } .toList() viewModel.field.saveGenre(requireContext()) renewAdapter() } else -> {} } } @Subscribe(threadMode = ThreadMode.MAIN) fun onListEditorEvent(event: ListEditorResultEvent) { event.listEditorResultMeta.let { viewModel.updateMediaProgress(it.mediaId, it.progress) } notifyDataSetChanged() } @Subscribe() fun seasonEvent(event:SeasonEvent){ when(event){ SeasonEvent.SeasonFilterEvent -> { renewAdapter() } is SeasonEvent.SeasonChangeEvent -> { viewModel.dispose() renewAdapter() } is SeasonEvent.SeasonHeaderEvent -> { viewModel.isHeaderEnabled(event.showHeader) renewAdapter() } SeasonEvent.SeasonTagEvent -> { openTagChooserDialog( viewModel.field.tagTagFields.values.toList(), MediaTagFilterTypes.SEASON_TAG ) } SeasonEvent.SeasonGenreEvent -> { openTagChooserDialog( viewModel.field.genreTagFields.values.toList(), MediaTagFilterTypes.SEASON_GENRE ) } } } private fun openTagChooserDialog(tags: List<TagField>, tagType: MediaTagFilterTypes) { TagChooserDialogFragment.newInstance( TagChooserField( tagType, tags ) ).show(childFragmentManager, TagChooserDialogFragment::class.java.simpleName) } override fun onStop() { super.onStop() unRegisterForEvent() } }
3
Kotlin
1
24
355d2b5510682d869f18e0113453237af8a1f1cc
6,802
AniLib
Apache License 2.0
src/main/kotlin/drawable/Trace.kt
amollberg
267,279,072
false
null
import coordinates.System import kotlinx.serialization.Serializable import org.openrndr.color.ColorRGBa.Companion.GRAY import org.openrndr.color.ColorRGBa.Companion.TRANSPARENT import org.openrndr.math.Vector2 import kotlin.math.tan @Serializable data class Trace( var system: System, private var traceSegments: MutableList<TraceSegment> = mutableListOf(), override var groupId: Int = -1, override var groupOrdinal: Int = -1 ) : GroupMember() { init { setSystem() } val segments: MutableList<TraceSegment> get() = traceSegments val terminals: List<Terminals> get() = if (traceSegments.isNotEmpty()) traceSegments.map { it.start } + traceSegments.last().end else emptyList() override val bounds: Poly get() = segments.map { it.bounds } .fold(Poly(listOf()), { left, right -> Poly.join(left, right)!! }) constructor(system: System, points: Iterable<TraceSegment>) : this(system, points.toMutableList()) fun add(segment: TraceSegment) { if (traceSegments.isNotEmpty()) { assert(segment.getStart() == traceSegments.last().getEnd()) } traceSegments.add(segment) setSystem() } fun replace(segment: TraceSegment, replacements: List<TraceSegment>) { traceSegments = traceSegments.flatMap { if (it == segment) replacements else listOf(it) }.toMutableList() setSystem() } override fun draw(drawer: OrientedDrawer) { traceSegments.forEach { it.draw(drawer) } isolatedStyle( drawer.drawer, stroke = GRAY, fill = TRANSPARENT ) { if (drawer.extendedVisualization) bounds.draw(drawer) } } fun withSegment(segment: TraceSegment) = Trace(system, traceSegments + segment) private fun setSystem() { traceSegments.forEach { it.system = system } } fun setCoordinateSystem(modelSystem: System) { system = modelSystem setSystem() } fun append( newTerminals: Terminals, angle: Angle = Angle.OBTUSE, reverseKnee: Boolean = false ) { if (traceSegments.isEmpty()) throw IllegalStateException("Empty trace cannot be appended to.") add( TraceSegment( terminals.last(), newTerminals, angle, reverseKnee ) ) } } fun fold(v: Vector2, foldMatrix: Matrix22): Vector2 { return foldMatrix.times(v) } fun unfold(v: Vector2, foldMatrix: Matrix22): Vector2 { return foldMatrix.invert().times(v) } fun snapTo45(firstPoint: Vector2, secondPoint: Vector2): Vector2 { var vec = secondPoint - firstPoint var foldings = mutableListOf<Matrix22>() // Folding if (vec.x < 0) { foldings.add(Matrix22(-1, 0, 0, 1)) vec = fold(vec, foldings.last()) } if (vec.y < 0) { foldings.add(Matrix22(1, 0, 0, -1)) vec = fold(vec, foldings.last()) } if (vec.x < vec.y) { foldings.add(Matrix22(0, 1, 1, 0)) vec = fold(vec, foldings.last()) } // Snap inside 45 degree sector if (vec.x == 0.0) { // Do nothing } else if (vec.y / vec.x < tan(45 / 2.0 * Math.PI / 180)) { // Project to x-axis vec = Vector2(vec.x, 0.0) } else { // Project to diagonal val c = (vec.x + vec.y) / 2 vec = Vector2(c, c) } // Undo folding foldings.reversed().forEach { vec = unfold(vec, it) } return firstPoint + vec } fun trace(system: System, f: TraceBuilder.() -> Unit): Trace { val builder = TraceBuilder(system) builder.f() return builder.result } class TraceBuilder(val system: System) { internal data class TerminalsWithConfig( val terminals: Terminals, val reverseKnee: Boolean ) private val terminalsList: MutableList<TerminalsWithConfig> = mutableListOf() private var reverseKnee = false fun terminals(terminals: Terminals) { terminalsList.add(TerminalsWithConfig(terminals, reverseKnee)) } fun reverseKnee(value: Boolean) { reverseKnee = value } val result: Trace get() = Trace( system, terminalsList.windowed(2) { (start: TerminalsWithConfig, end: TerminalsWithConfig) -> TraceSegment( start.terminals, end.terminals, Angle.OBTUSE, end.reverseKnee ) }.toMutableList() ) }
0
Kotlin
0
0
d08f85dbbb0537b386fb1810a1e2f1b86a92c925
4,738
ArtisanTrace
Apache License 2.0
src/main/kotlin/org/arend/codeInsight/ArendParameterInfoHandler.kt
JetBrains
96,068,447
false
{"Kotlin": 2445827, "Lex": 14516, "Java": 4637, "HTML": 1695, "CSS": 1108, "JavaScript": 713}
package org.arend.codeInsight import com.intellij.lang.parameterInfo.* import com.intellij.openapi.project.ProjectManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.* import org.arend.error.CountingErrorReporter import org.arend.error.DummyErrorReporter import org.arend.ext.error.GeneralError import org.arend.naming.reference.ClassReferable import org.arend.naming.reference.Referable import org.arend.naming.resolving.visitor.ExpressionResolveNameVisitor import org.arend.psi.* import org.arend.psi.ArendElementTypes.* import org.arend.psi.ext.* import org.arend.psi.parentOfType import org.arend.resolving.ArendReferableConverter import org.arend.resolving.DataLocatedReferable import org.arend.resolving.util.ParameterImpl import org.arend.term.abs.Abstract import org.arend.term.abs.BaseAbstractExpressionVisitor import org.arend.term.abs.ConcreteBuilder import org.arend.term.concrete.Concrete import org.arend.resolving.util.parseBinOp import org.arend.term.abs.Abstract.ParametersHolder import org.arend.util.checkConcreteExprIsArendExpr import java.util.Collections.singletonList class ArendParameterInfoHandler: ParameterInfoHandler<ArendReferenceContainer, List<Abstract.Parameter>> { override fun updateUI(p: List<Abstract.Parameter>?, context: ParameterInfoUIContext) { if (p == null) return var curOffset = 0 var text = "" var hlStart = -1; var hlEnd = -1 var ind = 0 var curParam = context.currentParameterIndex for (pm in p) { if (pm is ArendNameTele && pm.identifierOrUnknownList.firstOrNull()?.text == "this") { curParam = if (curParam == -1) -1 else curParam - 1 continue } val nameTypeList = mutableListOf<Pair<String?, String?>>() val vars = pm.referableList if (vars.isNotEmpty()) { vars.mapTo(nameTypeList) { Pair(it?.textRepresentation() ?: "_", exprToString(pm.type)) } } else { nameTypeList.add(Pair("_", exprToString(pm.type))) } for (v in nameTypeList) { if (text != "") { text += ", " } var varText = v.first + if (v.second != null) " : " + v.second else "" if (!pm.isExplicit) { varText = "{$varText}" } text += varText if (ind == curParam) { hlStart = curOffset hlEnd = text.length + 1 } curOffset = text.length + 2 ++ind } } context.setupUIComponentPresentation(text, hlStart, hlEnd, !context.isUIComponentEnabled, false, false, context.defaultParameterColor) } override fun findElementForParameterInfo(context: CreateParameterInfoContext): ArendReferenceContainer? { val offset = context.editor.caretModel.offset //adjustOffset(context.file, context.editor.caretModel.offset) val appExprInfo = findAppExpr(context.file, offset) val ref = appExprInfo?.second val referable = ref?.resolve as? Referable //ref?.referent?.let{ resolveIfNeeded(it, (ref as ArendSourceNode).scope) } val params = referable?.let { getAllParametersForReferable(it, calledFromImportHintAction = true) } if (params != null && params.isNotEmpty()) { context.itemsToShow = arrayOf(params) //(referable as Abstract.ParametersHolder).parameters) } else { context.itemsToShow = null } return appExprInfo?.second } override fun showParameterInfo(element: ArendReferenceContainer, context: CreateParameterInfoContext) { context.showHint(element, element.textRange.startOffset, this) } override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): ArendReferenceContainer? { val offset = context.editor.caretModel.offset // adjustOffset(context.file, context.editor.caretModel.offset) val appExprInfo: Pair<Int, ArendReferenceContainer> = findAppExpr(context.file, offset) ?: return null if (context.parameterOwner != appExprInfo.second) { return null } context.setCurrentParameter(appExprInfo.first) return appExprInfo.second } override fun updateParameterInfo(parameterOwner: ArendReferenceContainer, context: UpdateParameterInfoContext) { } companion object { fun findParamIndex(params: List<Abstract.Parameter>, argsExplicitness: List<Boolean>): Int { if (argsExplicitness.isEmpty()) return -1 val argIsExplicit = argsExplicitness.last() var numExplicitsBefore = 0 var numImplicitsJustBefore = 0 for (i in 0 until argsExplicitness.size - 1) { if (argsExplicitness[i]) { ++numExplicitsBefore numImplicitsJustBefore = 0 } else { ++numImplicitsJustBefore } } var paramIndex = 0 loop@for (p in params.indices) { for (v in params[p].referableList) { if (numExplicitsBefore == 0) { if ((argIsExplicit && params[p].isExplicit) || (!argIsExplicit && numImplicitsJustBefore == 0)) { break@loop } --numImplicitsJustBefore } else if (params[p].isExplicit) { --numExplicitsBefore } ++paramIndex } } return if (numExplicitsBefore == 0 && numImplicitsJustBefore <= 0) paramIndex else -1 } fun getImplicitPrefixForReferable(def: ParametersHolder, newParameters: List<Referable?>? = null, newParametersReceiver: MutableList<Referable?>? = null): MutableList<Abstract.Parameter> { val params = ArrayList<Abstract.Parameter>() val defAncestors = (def as? PsiElement)?.ancestors?.toList()?.filterIsInstance<PsiReferable>() val containingClass = (def as? PsiElement)?.ancestor<ArendDefClass>()?.let {defClass -> if (def is ArendClassField || defAncestors != null && defAncestors.any { defClass.dynamicSubgroups.contains<PsiElement>(it) }) defClass else null } if (containingClass != null) { // constructors in patterns do not have leading {this} argument val thisArg = ArendPsiFactory(containingClass.project).createNameTele("this", containingClass.name, false) params.add(thisArg) newParametersReceiver?.add(thisArg.childOfType<ArendDefIdentifier>()) } val containingData = if (def is ArendConstructor) def.parent?.parent as? ArendDefData else null if (def is ArendConstructor) { if (containingData != null) { for (tele in containingData.parameters) { val type = exprToString(tele.type) for (p in tele.referableList) { params.add(ArendPsiFactory(def.project).createNameTele(p?.textRepresentation() ?: "_", type, false)) } } } else { val constructorClause = def.parent as? ArendConstructorClause val dataBody = constructorClause?.parent as? ArendDataBody val elim = dataBody?.elim val data = dataBody?.parent as? ArendDefData val project = data?.project if (data is Abstract.Definition && elim != null && project != null) { val concreteData: Concrete.GeneralDefinition = ConcreteBuilder.convert( ArendReferableConverter, data, CountingErrorReporter(GeneralError.Level.ERROR, DummyErrorReporter.INSTANCE) ) if (concreteData is Concrete.DataDefinition) { val clause = concreteData.constructorClauses.firstOrNull { it.constructors.map { (it.data as? DataLocatedReferable)?.data?.element }.contains(def) } val clausePatterns = clause?.patterns?.run { val newList = ArrayList(this) ExpressionResolveNameVisitor( ArendReferableConverter, data.scope, mutableListOf(), DummyErrorReporter.INSTANCE, null ).visitPatterns(newList, mutableMapOf()) newList } fun collectNamePatterns(pattern: Concrete.Pattern): List<Concrete.NamePattern> = if (pattern is Concrete.NamePattern) singletonList(pattern) else pattern.patterns.map { collectNamePatterns(it) }.flatten() when { elim.withKw != null -> if (clausePatterns != null) { val dataArgs = data.parameters.map { it.referableList.map { r -> Pair(r, it.isExplicit) } }.flatten() val patternsMap = HashMap<Referable, List<Referable>>() var i = 0; var j = 0; while (i < clausePatterns.size && j < dataArgs.size) { val argument = dataArgs[j] val pattern = clausePatterns[i] if (pattern.isExplicit == argument.second) { argument.first?.let { val patternReferables = collectNamePatterns(pattern).mapNotNull { it.referable } patternsMap[it] = patternReferables patternReferables.map { params.add(ParameterImpl(false, singletonList(it), null)) } } i++ j++ } else if (!argument.second) { j++ } else break } if (newParameters != null && newParametersReceiver != null) { for (nP in newParameters) { newParametersReceiver.addAll(patternsMap[nP] ?: singletonList(nP)) } } } elim.elimKw != null -> { val dataArgs = data.parameters.map { it.referableList }.flatten() val eliminatedArgs = elim.refIdentifierList.map { it.resolve }.filterIsInstance<ArendDefIdentifier>() if (eliminatedArgs.size == clausePatterns?.size) { val dataArgsMapped = dataArgs.map { it -> val elimIndex = eliminatedArgs.indexOf(it) if (elimIndex == -1) singletonList(it) else collectNamePatterns(clausePatterns[elimIndex]).map { it.referable } } dataArgsMapped.flatten().forEach { params.add(ParameterImpl(false, singletonList(it), null)) } if (newParameters != null && newParametersReceiver != null) { newParameters.map { val dataArgIndex = if (it != null) dataArgs.indexOf(it) else -1 if (dataArgIndex != -1) newParametersReceiver.addAll(dataArgsMapped[dataArgIndex]) else newParametersReceiver.add(it) } } } } } } } } } return params } fun getAllParametersForReferable(def: Referable, needImplicitConstructorParameters: Boolean = true, calledFromImportHintAction: Boolean = false): List<Abstract.Parameter> { if (def !is ParametersHolder) return emptyList() val psiFactory = ArendPsiFactory((def as PsiElement).project) val params = ArrayList<Abstract.Parameter>() if (def is ArendDefClass) { ClassReferable.Helper.getNotImplementedFields(def).forEach { val isExplicit = when (it) { is ArendFieldDefIdentifier -> it.isExplicitField else -> true } val type = when (it) { is ArendFieldDefIdentifier -> it.parentFieldTele?.type is ArendClassField -> it.resultType else -> null } params.add(psiFactory.createNameTele(it.refName, type?.text ?: "???", isExplicit)) } return params } if (needImplicitConstructorParameters) params.addAll(getImplicitPrefixForReferable(def)) params.addAll(def.parameters) var resType: ArendExpr? = when (def) { is ArendClassField -> def.resultType; is ArendDefFunction -> def.resultType; else -> null } while (resType != null && calledFromImportHintAction) { resType = when (resType) { is ArendArrExpr -> { params.add(psiFactory.createNameTele(null, exprToString(resType.domain), true)) resType.codomain } is ArendPiExpr -> { params.addAll(resType.parameters) resType.codomain } is ArendAtomFieldsAcc -> resType.atom.tuple?.tupleExprList?.firstOrNull()?.exprIfSingle else -> null } } return params } private fun exprToString(expr: Abstract.Expression?): String? = if (expr != null) ConcreteBuilder.convertExpression(expr).toString() else null private fun isClosingElement(element: PsiElement?) = when (element.elementType) { null, RPAREN, RBRACE, COMMA -> true else -> false } private fun adjustOffset(file: PsiFile, offset: Int) = if (isClosingElement(file.findElementAt(offset))) offset - 1 else offset private fun skipWhitespaces(file: PsiFile, offset: Int): PsiElement? { var shiftedOffset = offset var res:PsiElement? do { res = file.findElementAt(shiftedOffset) --shiftedOffset } while (res is PsiWhiteSpace) if (res?.parentOfType<ArendSourceNode>(false) is ArendDefFunction) { shiftedOffset = offset do { res = file.findElementAt(shiftedOffset) ++shiftedOffset } while (res is PsiWhiteSpace) } return res } private fun findArgInParsedBinopSeq(arg: Abstract.SourceNode, expr: Concrete.Expression, curArgInd: Int, curFunc: ArendReferenceContainer?): Pair<Int, ArendReferenceContainer>? { if (checkConcreteExprIsArendExpr(arg, expr)) { if (curFunc == null) { return (expr.data as? ArendReferenceContainer)?.let { Pair(-1, it) } } return Pair(curArgInd, curFunc) } if (expr is Concrete.AppExpression) { val funcRes = findArgInParsedBinopSeq(arg, expr.function, curArgInd, curFunc) if (funcRes != null) return funcRes var func = (expr.function as? Concrete.ReferenceExpression)?.data as? ArendReferenceContainer var funcReferable = func?.resolve as? Referable // resolvedInScope //func?.referent?.let{ resolveIfNeeded(it, arg.scope)} val argExplicitness = mutableListOf<Boolean>() if (funcReferable !is Abstract.ParametersHolder) { func = null funcReferable = null } for (argument in expr.arguments) { argExplicitness.add(argument.isExplicit) val argRes = findArgInParsedBinopSeq(arg, argument.expression, funcReferable?.let { findParamIndex(getAllParametersForReferable(it, calledFromImportHintAction = true), argExplicitness) } ?: -1, func) if (argRes != null) return argRes } } else if (expr is Concrete.LamExpression) { return findArgInParsedBinopSeq(arg, expr.body, curArgInd, curFunc) } return null } private fun locateArg(arg: Abstract.SourceNode, appExpr: ArendExpr) = appExpr.accept(object: BaseAbstractExpressionVisitor<Void, Pair<Int, ArendReferenceContainer>?>(null) { override fun visitBinOpSequence(data: Any?, left: Abstract.Expression, sequence: Collection<Abstract.BinOpSequenceElem>, params: Void?): Pair<Int, ArendReferenceContainer>? = findArgInParsedBinopSeq(arg, parseBinOp(left, sequence), -1, null) }, null) private fun isNewArgumentPosition(file: PsiFile, offset: Int): Boolean { val element = file.findElementAt(offset) return (element is PsiWhiteSpace || isClosingElement(element)) && file.findElementAt(offset - 1) is PsiWhiteSpace } private fun isBinOpSeq(expr: ArendExpr): Boolean = expr.accept(object: BaseAbstractExpressionVisitor<Void, Boolean>(false) { override fun visitBinOpSequence(data: Any?, left: Abstract.Expression, sequence: Collection<Abstract.BinOpSequenceElem>, params: Void?) = true }, null) private fun isBinOp(def: Referable?, ref: ArendReferenceContainer): Boolean = ref is ArendIPName && ref.infix != null || def is ArendDefFunction && ReferableBase.calcPrecedence(def.prec).isInfix private fun ascendLongName(node: Abstract.SourceNode): Abstract.SourceNode = node.parentSourceNode as? ArendLongName ?: node private fun ascendToLiteral(node: Abstract.SourceNode): Abstract.SourceNode = node.parentSourceNode as? ArendLiteral ?: node private fun ascendLambda(node: Abstract.SourceNode): Abstract.SourceNode? { if (node is ArendLamExpr) { return node } (node.parentSourceNode as? ArendLamExpr)?.let { return it } if (node is ArendRefIdentifier) { (node.parentSourceNode as? ArendLamExpr)?.let { return it } ((node.parentSourceNode as? ArendNameTele)?.parentSourceNode as? ArendLamExpr)?.let { return it } } return null } //TODO: remove this function private fun toArgument(node: Abstract.SourceNode): ArendArgument? { if (node is ArendArgument) { return node } if (node is ArendTupleExpr) { return node.parentSourceNode as? ArendArgument } return null } private fun extractRefFromSourceNode(node: Abstract.SourceNode): ArendReferenceContainer? { if (node is ArendLiteral) { if (node.ipName != null) { return node.ipName } else if (node.longName != null) { return node.longName } } return node as? ArendReferenceContainer } private fun tryToLocateAtTheCurrentLevel(absNode: Abstract.SourceNode, isNewArgPos: Boolean, isLowestLevel: Boolean): Pair<Int, ArendReferenceContainer>? { val absNodeParent = ascendToLiteral(absNode).parentSourceNode ?: return null val refContainer = extractRefFromSourceNode(absNode) if (refContainer != null) { val ref = refContainer.resolve as? Referable val params = ref?.let { getAllParametersForReferable(it, calledFromImportHintAction = true) } if (params != null && params.isNotEmpty()) { val isBinOp = isBinOp(ref, refContainer) val parentAppExprCandidate = absNodeParent.parentSourceNode if (parentAppExprCandidate is ArendExpr) { if (isBinOpSeq(parentAppExprCandidate) && !isBinOp) { val loc = (absNode as? PsiElement)?.parentOfType<ArendExpr>(false)?.let{ locateArg(it, parentAppExprCandidate) } ?: return null if (isNewArgPos && isBinOp(loc.second.resolve as? Referable, refContainer)) { return Pair(0, refContainer) } if (isNewArgPos && isLowestLevel) return Pair(loc.first + 1, loc.second) return loc } } if (isNewArgPos && isLowestLevel) { if (!isBinOp) return Pair(0, refContainer) return Pair(1, refContainer) } return Pair(-1, refContainer) } } var arg: Abstract.SourceNode? = toArgument(absNodeParent) ?: toArgument(absNode) var argLoc: Pair<Int, ArendReferenceContainer>? = null if (arg == null && absNode is ArendRefIdentifier) { arg = ascendToLiteral(absNode) as? ArendSourceNode } val argParent = arg?.parentSourceNode as? ArendExpr if (argParent != null && isBinOpSeq(argParent)) { if (arg is ArendArgument) arg = arg.expression argLoc = arg?.let { locateArg(it, argParent) } // (arg.expression as? ArendSourceNode)?.let{ locateArg(it, argParent) } } else if (absNodeParent is ArendExpr && isBinOpSeq(absNodeParent)) { // (absNodeParent.parentSourceNode is ArendExpr && absNodeParent.parentSourceNode?.let { isBinOpSeq(it as ArendExpr) } == true) { argLoc = (absNode as? ArendExpr)?.let{ locateArg(it, absNodeParent) } } if (argLoc != null) { if (isNewArgPos && isLowestLevel) return Pair(argLoc.first + 1, argLoc.second) return argLoc } return null } private fun ascendTillAppExpr(node: Abstract.SourceNode, isNewArgPos: Boolean): Pair<Int, ArendReferenceContainer>? { val absNode = ascendLongName(node) val res = tryToLocateAtTheCurrentLevel(absNode, isNewArgPos, true) if (res != null) { return res } return ascendLambda(absNode)?.parentSourceNode?.let{ tryToLocateAtTheCurrentLevel(it, isNewArgPos, false) } } private fun findAppExpr(file: PsiFile, offset: Int): Pair<Int, ArendReferenceContainer>? { val isNewArgPos = isNewArgumentPosition(file, offset) val absNode = skipWhitespaces(file, adjustOffset(file, offset))?.let { PsiTreeUtil.findFirstParent(it) { x -> x is Abstract.SourceNode } as? Abstract.SourceNode } ?: return null return ascendTillAppExpr(absNode, isNewArgPos) } } }
71
Kotlin
16
83
bee4b93c49c61dc19a2639f4d2f91190c4115cb5
24,820
intellij-arend
Apache License 2.0
reviewrelic/src/androidTest/java/com/review/relic/RecyclerViewItemCountAssertion.kt
reviewrelic-universe
334,628,433
false
null
package com.review.relic import android.view.View import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.NoMatchingViewException import androidx.test.espresso.ViewAssertion import androidx.test.espresso.matcher.ViewMatchers.assertThat import org.hamcrest.CoreMatchers.`is` class RecyclerViewItemCountAssertion(private val expectedCount: Int) : ViewAssertion { override fun check(view: View, noViewFoundException: NoMatchingViewException?) { if (noViewFoundException != null) { throw noViewFoundException } val recyclerView = view as RecyclerView val adapter = recyclerView.adapter assertThat(adapter?.itemCount, `is`(expectedCount)) } }
0
Kotlin
1
0
583d7a18f7fec1bed1d06c1f373d09a9d15e4f5d
725
android-sdk
Apache License 2.0
libs/rest/rest-server-impl/src/main/kotlin/net/corda/httprpc/server/impl/RestServerImpl.kt
corda
346,070,752
false
null
package net.corda.httprpc.server.impl import net.corda.httprpc.PluggableRestResource import net.corda.httprpc.RestResource import net.corda.httprpc.security.read.RestSecurityManager import net.corda.httprpc.server.RestServer import net.corda.httprpc.server.config.RestServerSettingsProvider import net.corda.httprpc.server.config.impl.RestServerObjectSettingsProvider import net.corda.httprpc.server.config.models.RestServerSettings import net.corda.httprpc.server.impl.apigen.models.Resource import net.corda.httprpc.server.impl.apigen.processing.APIStructureRetriever import net.corda.httprpc.server.impl.apigen.processing.JavalinRouteProviderImpl import net.corda.httprpc.server.impl.apigen.processing.openapi.OpenApiInfoProvider import net.corda.httprpc.server.impl.internal.RestServerInternal import net.corda.httprpc.server.impl.security.RestAuthenticationProviderImpl import net.corda.httprpc.server.impl.security.provider.AuthenticationProvider import net.corda.httprpc.server.impl.security.provider.basic.UsernamePasswordAuthenticationProvider import net.corda.httprpc.server.impl.security.provider.bearer.azuread.AzureAdAuthenticationProvider import net.corda.httprpc.server.impl.websocket.deferred.DeferredWebSocketCloserService import org.slf4j.LoggerFactory import net.corda.v5.base.util.debug import net.corda.v5.base.util.trace import java.nio.file.Path import java.util.concurrent.locks.ReentrantReadWriteLock import java.util.function.Supplier import kotlin.concurrent.write @SuppressWarnings("TooGenericExceptionThrown", "LongParameterList") class RestServerImpl( restResourceImpls: List<PluggableRestResource<out RestResource>>, restSecurityManagerSupplier: Supplier<RestSecurityManager>, restServerSettings: RestServerSettings, multiPartDir: Path, devMode: Boolean ) : RestServer { private companion object { private val log = LoggerFactory.getLogger(this::class.java.enclosingClass) } @Volatile private var running = false private val startStopLock = ReentrantReadWriteLock() private val resources = getResources(restResourceImpls) private val restServerConfigProvider = RestServerObjectSettingsProvider(restServerSettings, devMode) private val restServerInternal = RestServerInternal( JavalinRouteProviderImpl( restServerSettings.context.basePath, restServerSettings.context.version, resources ), RestAuthenticationProviderImpl(createAuthenticationProviders(restServerConfigProvider, restSecurityManagerSupplier)), restServerConfigProvider, OpenApiInfoProvider(resources, restServerConfigProvider), multiPartDir, DeferredWebSocketCloserService() ) override val port: Int get() = restServerInternal.port override fun start() { startStopLock.write { if (!running) { log.info("Started the server") restServerInternal.start() running = true } } } override fun close() { startStopLock.write { if (running) { log.info("Stop the server.") restServerInternal.stop() running = false } } } private fun getResources(restResourceImpls: List<PluggableRestResource<out RestResource>>): List<Resource> { log.debug { "Get resources for RestResource implementations of ${restResourceImpls.joinToString()}." } log.trace { "Generating resource model for http rest" } val resources = try { APIStructureRetriever(restResourceImpls).structure } catch (e: Exception) { "Error during Get resources for RestResource implementations of ${restResourceImpls.joinToString()}".let { msg -> log.error("$msg: ${e.message}") throw Exception(msg, e) } } log.debug { "Http RestResource count: ${resources.size}" } log.debug { "Get resources for RestResource implementations of ${restResourceImpls.joinToString()} completed." } return resources } private fun createAuthenticationProviders( settings: RestServerSettingsProvider, restSecurityManagerSupplier: Supplier<RestSecurityManager> ): Set<AuthenticationProvider> { val result = mutableSetOf<AuthenticationProvider>(UsernamePasswordAuthenticationProvider(restSecurityManagerSupplier)) val azureAdSettings = settings.getSsoSettings()?.azureAd() if (azureAdSettings != null) { result.add(AzureAdAuthenticationProvider.createDefault(azureAdSettings, restSecurityManagerSupplier)) } return result } }
82
Kotlin
7
24
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
4,727
corda-runtime-os
Apache License 2.0
shared_ui_components/src/commonMain/kotlin/com/eyedea/shared_ui_components/composables/ExpandableText.kt
Deorigami
666,239,727
false
null
package com.eyedea.shared_ui_components.composables import androidx.compose.animation.animateContentSize import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.LocalTextStyle import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import com.eyedea.shared_ui_components.style.Colors @Composable fun ExpandableText( modifier: Modifier = Modifier, textModifier: Modifier = Modifier, style: TextStyle = LocalTextStyle.current, fontStyle: FontStyle? = null, text: String, collapsedMaxLine: Int = 3, showMoreText: String = " Show More", showMoreStyle: SpanStyle = style.toSpanStyle().copy(color = Colors.primary500(), fontWeight = FontWeight.W500), showLessText: String = " Show Less", showLessStyle: SpanStyle = style.toSpanStyle().copy(color = Colors.primary500(), fontWeight = FontWeight.W500), textAlign: TextAlign? = null ) { var isExpanded by remember { mutableStateOf(false) } var clickable by remember { mutableStateOf(false) } var lastCharIndex by remember { mutableStateOf(0) } Box(modifier = Modifier .clickable(clickable) { isExpanded = !isExpanded } .then(modifier) ) { Text( modifier = textModifier .fillMaxWidth() .animateContentSize(), text = buildAnnotatedString { if (clickable) { if (isExpanded) { append(text) withStyle(style = showLessStyle) { append(showLessText) } } else { val adjustText = text.substring(startIndex = 0, endIndex = lastCharIndex) .dropLast(showMoreText.length) // .dropLastWhile { it.isWhitespace() || it == '.' } append("$adjustText...") withStyle(style = showMoreStyle) { append(showMoreText) } } } else { append(text) } }, maxLines = if (isExpanded) Int.MAX_VALUE else collapsedMaxLine, fontStyle = fontStyle, onTextLayout = { textLayoutResult -> if (!isExpanded && textLayoutResult.hasVisualOverflow) { clickable = true lastCharIndex = textLayoutResult.getLineEnd(collapsedMaxLine - 1) } }, style = style, textAlign = textAlign ) } }
0
Kotlin
0
0
4b586729a8d5a124e15fcb768c02c3f21253983f
3,188
CMP-Animax
Apache License 2.0
kontroller/src/test/kotlin/no/ssb/kostra/validation/report/ValidationReportTest.kt
statisticsnorway
414,216,275
false
{"Kotlin": 1617964, "TypeScript": 57883, "HTML": 694, "SCSS": 110}
package no.ssb.kostra.validation.report import io.kotest.core.spec.style.BehaviorSpec import io.kotest.data.forAll import io.kotest.data.row import io.kotest.matchers.string.shouldContain import no.ssb.kostra.program.KotlinArguments import java.time.LocalDateTime class ValidationReportTest : BehaviorSpec({ Given("ValidationReport, summary per validation, branch") { forAll( row("Finner ingen data", 0, emptyList()), row("Ingen feil funnet", 1, emptyList()), row( "Oppsummering pr. kontroll", 1, listOf( ValidationReportEntry().copy( ruleName = "Rule 1", messageText = "Message text", lineNumbers = listOf(1) ) ) ), ) { description, numberOfControls, reportEntries -> When(description) { val sut = ValidationReport( validationReportArguments = ValidationReportArguments( kotlinArguments = kotlinArgumentsInTest, validationResult = ValidationResult( reportEntries = reportEntries, numberOfControls = numberOfControls, ) ) ) Then("result should be as expected") { sut.toString() shouldContain description } } } } Given("ValidationReport, summary per validation, severity") { forAll( row(Severity.FATAL, "kontrollene i bli kjørt</div>"), row(Severity.ERROR, "feil som hindrer innsending</div>"), row(Severity.WARNING, "advarsler</div>"), row(Severity.INFO, "informasjonsmeldinger</div>"), row(Severity.OK, "meldinger</div>"), ) { severity, expectedMessaage -> When(severity.name) { val validationReportArguments = ValidationReportArguments( kotlinArguments = kotlinArgumentsInTest.copy( isRunAsExternalProcess = false ), validationResult = ValidationResult( reportEntries = listOf( ValidationReportEntry( severity = severity, ruleName = "Kontroll Test 1", messageText = "Feilmelding", lineNumbers = listOf(1) ) ), numberOfControls = 1, endTime = LocalDateTime.of(2022, 1, 1, 1, 1, 1), ) ) val sut = ValidationReport(validationReportArguments = validationReportArguments) val result = sut.toString() Then("result should be as expected") { result shouldContain expectedMessaage result shouldContain "color: ${severity.info.color}" } } } } Given("ValidationReport, show stats") { forAll( row( "has errors, no stats shown", Severity.ERROR, emptyList(), "Oppsummering pr. kontroll" ), row( "has no errors, no shown", Severity.INFO, listOf( StatsReportEntry( heading = StatsEntryHeading("&nbsp;", "~content~"), entries = listOf(StatsEntry("first", "123")) ) ), "Oppsummering pr. kontroll" ), ) { description, severity, statsReportEntries, expectedMessage -> When(description) { val sut = ValidationReport( validationReportArguments = ValidationReportArguments( kotlinArguments = kotlinArgumentsInTest, validationResult = ValidationResult( reportEntries = listOf(ValidationReportEntry(severity = severity)), numberOfControls = 1, statsReportEntries = statsReportEntries ) ) ) Then("result should be as expected") { sut.toString() shouldContain expectedMessage } } } } }) { companion object { private val kotlinArgumentsInTest = KotlinArguments( skjema = "0A", aargang = "2023", region = "1234", startTime = LocalDateTime.of(2022, 1, 1, 1, 1, 0), isRunAsExternalProcess = true ) } }
1
Kotlin
0
1
e6e4585da07f6518c2d5eece8938368e5f2b8b84
4,916
kostra-kontrollprogram
MIT License
src/main/kotlin/com/marcoeckstein/binance/api/client/prvt/account/Transfer.kt
marco-eckstein
340,113,530
false
{"Kotlin": 161467}
package com.marcoeckstein.binance.api.client.prvt.account import java.math.BigDecimal interface Transfer : Timestamped { val txId: String val uid: String val asset: String val amount: BigDecimal val status: String val type: RollDirection val target: String // It is unclear which types the following properties have, since they seem to always contain the same values: // val clientInfo: null }
0
Kotlin
3
3
caa883355bc10946cb137bcc806d75a9003d32b2
433
binance-api-kotlin
MIT License
ethereumkit/src/main/java/org/p2p/ethereumkit/external/api/coingecko/response/CoinGeckoPriceResponse.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.ethereumkit.external.api.coingecko.response import com.google.gson.annotations.SerializedName import java.math.BigDecimal internal data class CoinGeckoPriceResponse( @SerializedName("usd") val priceInUsd: BigDecimal )
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
244
key-app-android
MIT License
features/test-details/feature/src/main/java/teamcityapp/features/test_details/data/TestDetailsDataManagerImpl.kt
vase4kin
68,111,887
false
{"Gradle": 29, "JSON": 2, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Ignore List": 26, "Batchfile": 1, "Text": 1, "YAML": 5, "INI": 24, "Proguard": 25, "XML": 228, "Java": 33, "Kotlin": 580, "HTML": 1, "Gradle Kotlin DSL": 1}
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package teamcityapp.features.test_details.data import android.text.Html import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import teamcityapp.features.test_details.repository.TestDetailsRepository import javax.inject.Inject class TestDetailsDataManagerImpl @Inject constructor( private val repository: TestDetailsRepository ) : TestDetailsDataManager { private val subscriptions = CompositeDisposable() /** * {@inheritDoc} */ override fun loadData( onSuccess: (test: String) -> Unit, onError: () -> Unit, url: String ) { subscriptions.clear() repository.testOccurrence(url) .subscribeOn(Schedulers.io()) .map { Html.escapeHtml(it.details) } .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onSuccess = { onSuccess(it) }, onError = { onError() } ) .addTo(subscriptions) } /** * {@inheritDoc} */ override fun unsubscribe() { subscriptions.clear() } }
0
Kotlin
11
52
9abb1ed56c127d64679124c38d30b0014ec024de
1,836
TeamCityApp
Apache License 2.0
app/src/main/java/com/nadia/frenzy/utils/NetworkStateListener.kt
NadiaBelhaj
558,358,508
false
{"Kotlin": 125841}
package com.nadia.frenzy.utils interface NetworkStateListener { fun onNetworkDisconnected() }
0
Kotlin
1
0
57bbb11812e5d38710393413fa2296d393a52985
103
Frenzy-Android-App-Front-end
MIT License
vector/src/main/java/im/vector/riotx/features/invite/VectorInviteView.kt
saad100104006
212,864,777
true
{"Gradle": 5, "Markdown": 7, "Java Properties": 2, "Shell": 15, "Text": 3, "Ignore List": 4, "Batchfile": 1, "YAML": 2, "Proguard": 3, "Java": 6, "XML": 454, "Kotlin": 1122, "JSON": 5, "HTML": 1}
/* * 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.app.features.invite import android.content.Context import android.util.AttributeSet import android.view.View import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.updateLayoutParams import im.vector.app.R import im.vector.app.core.di.HasScreenInjector import im.vector.app.core.platform.ButtonStateView import im.vector.app.features.home.AvatarRenderer import kotlinx.android.synthetic.main.vector_invite_view.view.* import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState import org.matrix.android.sdk.api.session.user.model.User import org.matrix.android.sdk.api.util.toMatrixItem import javax.inject.Inject class VectorInviteView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : ConstraintLayout(context, attrs, defStyle) { interface Callback { fun onAcceptInvite() fun onRejectInvite() } enum class Mode { LARGE, SMALL } @Inject lateinit var avatarRenderer: AvatarRenderer var callback: Callback? = null init { if (context is HasScreenInjector) { context.injector().inject(this) } View.inflate(context, R.layout.vector_invite_view, this) inviteAcceptView.callback = object : ButtonStateView.Callback { override fun onButtonClicked() { callback?.onAcceptInvite() } override fun onRetryClicked() { callback?.onAcceptInvite() } } inviteRejectView.callback = object : ButtonStateView.Callback { override fun onButtonClicked() { callback?.onRejectInvite() } override fun onRetryClicked() { callback?.onRejectInvite() } } } fun render(sender: User, mode: Mode = Mode.LARGE, changeMembershipState: ChangeMembershipState) { if (mode == Mode.LARGE) { updateLayoutParams { height = LayoutParams.MATCH_CONSTRAINT } avatarRenderer.render(sender.toMatrixItem(), inviteAvatarView) inviteIdentifierView.text = sender.userId inviteNameView.text = sender.displayName inviteLabelView.text = context.getString(R.string.send_you_invite) } else { updateLayoutParams { height = LayoutParams.WRAP_CONTENT } inviteAvatarView.visibility = View.GONE inviteIdentifierView.visibility = View.GONE inviteNameView.visibility = View.GONE inviteLabelView.text = context.getString(R.string.invited_by, sender.userId) } InviteButtonStateBinder.bind(inviteAcceptView, inviteRejectView, changeMembershipState) } }
2
null
1
2
588e5d6e63ecfee9d93ef3da5987b8deb59f412f
3,355
NovaChat
Apache License 2.0
demo-command/src/main/kotlin/io/holixon/cqrshexagonaldemo/demoparent/command/domain/Link.kt
holixon
747,608,283
false
{"Kotlin": 26026, "TSQL": 2855, "Shell": 72}
package io.holixon.cqrshexagonaldemo.demoparent.command.domain data class Link( var id: Long, var href: String, var rel: String, var render: String?, )
7
Kotlin
0
0
e77edf997fc816ba7ca392fec8df1a537d6611aa
170
cqrs-meets-hexagonal
Apache License 2.0
app/src/main/java/com/tarripoha/android/presentation/main/MainActivity.kt
rajatsangrame
340,683,468
false
{"Kotlin": 147650}
package com.tarripoha.android.presentation.main import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.activity.viewModels import androidx.core.view.GravityCompat import androidx.lifecycle.* import androidx.navigation.NavController import androidx.navigation.findNavController import com.tarripoha.android.R import com.tarripoha.android.databinding.ActivityMainBinding import com.tarripoha.android.presentation.base.BaseActivity import com.tarripoha.android.presentation.login.LoginActivity import com.tarripoha.android.presentation.main.drawer.SideNavItem import com.tarripoha.android.util.* import com.tarripoha.android.Constants import com.tarripoha.android.util.helper.UserHelper import com.tarripoha.android.util.ktx.getPackage import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : BaseActivity() { private lateinit var navController: NavController private val mainViewModel: MainViewModel by viewModels() private lateinit var binding: ActivityMainBinding companion object { private const val SEARCH_DEBOUNCE_TIME_IN_MS = 300L private const val TAG = "MainActivity" fun startMe(context: Context) { val intent = Intent(context, MainActivity::class.java) intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK ) context.startActivity(intent) } } // region Activity Related override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupUI() } /*override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.menu_main, menu) menu.apply { findItem(R.id.menu_search).isVisible = true if (mainViewModel.isUserAdmin()) findItem(R.id.menu_info).isVisible = true } return true }*/ /*override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { if (!showBackBtn) { binding.drawerLayout.openDrawer(GravityCompat.START) } else { hideKeyboard(binding.container.toolbarLayout.searchEt) super.onBackPressed() } true } R.id.menu_search -> { binding.container.toolbarLayout.searchEt.text = null navController.navigate(R.id.action_HomeFragment_to_SearchFragment) true } R.id.menu_info -> { val count = if (mainViewModel.getWordCount().value == null) { 0 } else { mainViewModel.getWordCount().value } TPUtils.showSnackBar(this, "Total words: $count") true } else -> super.onOptionsItemSelected(item) } }*/ override fun onDestroy() { //TextToSpeechUtil.onStop() super.onDestroy() } private fun performAfterDelay(delay: Long = 300L, callback: () -> Unit) { Handler(Looper.getMainLooper()).postDelayed({ callback() }, delay) } fun openDrawer() { binding.drawerLayout.open() } fun onDrawerClick(item: SideNavItem) { val isUserLoggedIn = UserHelper.isLoggedIn() when (item.itemName) { getString(R.string.login_register) -> { binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { LoginActivity.startMe(this) } } getString(R.string.user) -> { // no-op } getString(R.string.saved) -> { if (!isUserLoggedIn) { mainViewModel.setUserMessage(getString(R.string.error_login)) return } binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { navigateToWordListFragment( category = Constants.CATEGORY_SAVED, heading = getString(R.string.saved) ) } } getString(R.string.liked) -> { if (!isUserLoggedIn) { mainViewModel.setUserMessage(getString(R.string.error_login)) return } binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { navigateToWordListFragment( category = Constants.CATEGORY_USER_LIKED, heading = getString(R.string.liked_words) ) } } getString(R.string.requested) -> { if (!isUserLoggedIn) { mainViewModel.setUserMessage(getString(R.string.error_login)) return } binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { navigateToWordListFragment( category = Constants.CATEGORY_USER_REQUESTED, heading = getString(R.string.requested_words) ) } } getString(R.string.pending_approvals) -> { if (!isUserLoggedIn) { mainViewModel.setUserMessage(getString(R.string.error_login)) return } binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { navigateToWordListFragment( category = Constants.CATEGORY_PENDING_APPROVALS, heading = getString(R.string.pending_approvals) ) } } getString(R.string.settings) -> { // no-op } getString(R.string.rate_us) -> { binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { TPUtils.navigateToPlayStore( this, getPackage() ) } } getString(R.string.tell_your_friend) -> { binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { val intent = Intent() intent.action = Intent.ACTION_SEND intent.putExtra( Intent.EXTRA_TEXT, getString(R.string.msg_tell_your_friend) ) intent.type = "text/plain" startActivity(intent) } } getString(R.string.support) -> { // no-op } getString(R.string.help) -> { binding.drawerLayout.closeDrawer(GravityCompat.START) performAfterDelay { //FAQActivity.startMe(this) } // no-op } getString(R.string.logout) -> { // MaterialAlertDialogBuilder(this, R.style.AlertDialogTheme) // .showDialog( // title = getString(R.string.logout), // message = getString(R.string.msg_confirm_logout), // positiveText = getString(R.string.logout), // positiveListener = { // UserHelper.setUser(null) // LoginHelper.logoutUser() // PreferenceHelper.clear() // LoginActivity.startMe(this) // finish() // }, // negativeListener = {} // ) } } } //endregion //region Helper functions private fun setupUI() { setupObservers() setupListeners() setupSearchEditText() navController = findNavController(R.id.nav_host_fragment) navController.setGraph(R.navigation.main_nav_graph) } private fun setupObservers() { mainViewModel.getUserMessage() .observe(this, Observer { it?.let { TPUtils.showSnackBar(this, it) } }) mainViewModel.getErrorMessage() .observe(this, Observer { it?.let { TPUtils.showSnackBar(this, it) } }) // // mainViewModel.getChar() // .observe(this, Observer { it -> // it?.let { // var c = binding.container.toolbarLayout.searchEt.text.toString() // val start = binding.container.toolbarLayout.searchEt.selectionStart // val end = binding.container.toolbarLayout.searchEt.selectionEnd // when { // start == end && start != 0 -> { // c = c.substring(0, start) + it + c.substring(start, c.length) // binding.container.toolbarLayout.searchEt.setText(c) // binding.container.toolbarLayout.searchEt.setSelection(start + it.length) // } // // start < end -> { // c = c.replaceRange(startIndex = start, endIndex = end, it) // binding.container.toolbarLayout.searchEt.setText(c) // binding.container.toolbarLayout.searchEt.setSelection(start + it.length) // } // // else -> { // c += it // binding.container.toolbarLayout.searchEt.setText(c) // binding.container.toolbarLayout.searchEt.setSelection(c.length) // } // } // } // }) // } private fun navigateToWordListFragment( lang: String = Constants.LANG_ANY, category: String, heading: String ) { mainViewModel.resetWordListParams() val param = WordListFragment.WordListFragmentParam( heading = heading, lang = lang, category = category ) mainViewModel.wordListParam = param navController.navigate(R.id.action_HomeFragment_to_WordListFragment) } private fun setupSearchEditText() { /*binding.container.toolbarLayout.searchEt.apply { val d = RxTextView.textChanges(this) .subscribeOn(AndroidSchedulers.mainThread()) .debounce(SEARCH_DEBOUNCE_TIME_IN_MS, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { mainViewModel.setQuery(it.toString()) } compositeDisposable.add(d) doAfterTextChanged { it?.let { editable -> binding.container.toolbarLayout.clearBtn.toggleVisibility(editable) } } }*/ } private fun setupListeners() { } //endregion }
0
Kotlin
0
0
8f9cc8efccb70b9a89ef96ccdccab53f2c1a0190
11,764
tarripoha-android
MIT License
app/src/main/java/com/example/resumeskillapp/core/utils/AnimationExtention.kt
ChorpitaSergiy
518,162,219
false
null
/* * MIT License * * Copyright (C) 2022 Serhii Chorpita * * 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.example.resumeskillapp.core.utils import android.animation.Animator import android.animation.ObjectAnimator import android.view.View fun View.visibleWithAnimation(duration: Long) { if (View.VISIBLE == visibility) return val animator = ObjectAnimator.ofFloat(this, View.ALPHA, 0f, 1f).setDuration(duration) animator.addListener(object : SimpleAnimatorListener() { override fun onAnimationStart(animation: Animator?) { this@visibleWithAnimation.visible() } }) animator.start() } fun View.goneWithAnimation(duration: Long, listener: () -> Unit) { if (View.GONE == visibility) return val animator = ObjectAnimator.ofFloat(this, View.ALPHA, 1f, 0f).setDuration(duration) animator.addListener(object : SimpleAnimatorListener() { override fun onAnimationEnd(animation: Animator?) { listener.invoke() this@goneWithAnimation.gone() } }) animator.start() } fun View.visible() { visibility = View.VISIBLE } fun View.gone() { visibility = View.GONE } abstract class SimpleAnimatorListener : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) = Unit override fun onAnimationEnd(animation: Animator?) = Unit override fun onAnimationCancel(animation: Animator?) = Unit override fun onAnimationStart(animation: Animator?) = Unit }
0
Kotlin
0
0
18d26bbd130419bc85e2c24b62d429ec44cfc7e3
2,546
ResumeSkillApp
MIT License
permission-base/src/main/kotlin/com/github/b1412/permission/graphql/annotation/SchemaDocumentation.kt
b1412
206,295,390
false
null
package com.github.b1412.permission.graphql.annotation import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy.RUNTIME @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FIELD) @Retention(RUNTIME) annotation class SchemaDocumentation(val value: String)
1
Kotlin
1
1
ee02bf12022ad23b334cb90b3f314be048c3d8eb
302
permission-api
Apache License 2.0
reaktive-testing/src/commonMain/kotlin/com/badoo/reaktive/test/single/AsyncTestResult.kt
badoo
174,194,386
false
{"Kotlin": 1507792, "Swift": 2268, "HTML": 956}
package com.badoo.reaktive.test.single expect class AsyncTestResult
2
Kotlin
57
1,171
26788ab67ef85e2e3971e5bc79cce4ed9e3b5636
69
Reaktive
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructureUtils.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.calls import com.intellij.ide.hierarchy.call.CallHierarchyNodeDescriptor import com.intellij.psi.PsiMember fun extractMemberFromDescriptor(nodeDescriptor: CallHierarchyNodeDescriptor): PsiMember? { return nodeDescriptor.enclosingElement }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
498
intellij-kotlin
Apache License 2.0
tools/AlkitabConverterProcesses/src/yuku/alkitabconverter/in_ayt/Proses1.kt
yukuku
5,657,549
false
{"Gradle": 23, "Shell": 4, "Java Properties": 4, "Ignore List": 23, "Batchfile": 2, "EditorConfig": 1, "Text": 108, "Markdown": 1, "Proguard": 19, "XML": 464, "Java": 345, "INI": 2, "YAML": 1, "Python": 6, "Kotlin": 109, "JSON": 6, "HTML": 19, "CSS": 1, "Ant Build System": 1, "PHP": 1, "JAR Manifest": 2, "C++": 2, "C": 8, "Makefile": 2}
package yuku.alkitabconverter.in_ayt import yuku.alkitabconverter.util.Usfm2Usfx import yuku.alkitabconverter.util.UsfmBookName import java.io.File import java.io.PrintWriter // make it relative so it can be used by wordsend (because wordsend can't accept filenames starting with "/") private val MID_DIR = File(System.getProperty("java.io.tmpdir")).relativeTo(File(".").absoluteFile) fun main(args: Array<String>) { val INPUT_TEXT_DIR = args[0] for (inputfn in File(INPUT_TEXT_DIR).listFiles { _, name -> name.endsWith(".SFM") }) { val lines = inputfn.readLines() var splitFile: PrintWriter? = null for (line in lines) { var baris = line // remove ALL BOM (0xfeff) if (baris.isNotEmpty()) { baris = baris.replace("\ufeff", "") } if (baris.startsWith("\\id ")) { val firstSpaceAfterId = baris.indexOf(' ', 4) val newId: String newId = if (firstSpaceAfterId == -1) { baris.substring(4) } else { baris.substring(4, firstSpaceAfterId) } splitFile?.close() val kitab_0 = UsfmBookName.toBookId(newId) val outputfile = File(MID_DIR, String.format("%02d-%s-utf8.usfm", kitab_0, newId)) outputfile.parentFile?.mkdir() splitFile = PrintWriter(outputfile, "utf-8") println("$inputfn -> $outputfile") } // patch: Ganti \s1 dengan \s2 baris = baris.replace("\\s1", "\\s2") // patch: remove erronous U+001A character baris = baris.replace("\u001a", "") splitFile?.println(baris) } splitFile?.close() } val usfms = MID_DIR.list { _, name -> name.endsWith("-utf8.usfm") } for (usfm in usfms) { val usfx = usfm.replace(".usfm", ".usfx.xml") Usfm2Usfx.convert(File(MID_DIR, usfm).path, File(MID_DIR, usfx).path) } }
23
Java
174
310
d43ae4e17650b34b6757d0ddfd8100e44a677f67
2,072
androidbible
Apache License 2.0
core/src/main/java/com/rotor/core/NetworkUtil.kt
rotorlab
124,786,609
false
{"Kotlin": 21018, "Java": 1599}
package com.rotor.core import android.content.Context import android.net.ConnectivityManager /** * Created by efraespada on 11/03/2018. */ class NetworkUtil { companion object { var TYPE_WIFI = 1 var TYPE_MOBILE = 2 var TYPE_NOT_CONNECTED = 0 val NETWORK_STATUS_NOT_CONNECTED = 0 val NETWORK_STAUS_WIFI = 1 val NETWORK_STATUS_MOBILE = 2 fun getConnectivityStatus(context: Context): Int { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo if (null != activeNetwork) { if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE } return TYPE_NOT_CONNECTED } fun getConnectivityStatusString(context: Context): Int { val conn = getConnectivityStatus(context) var status = 0 if (conn == TYPE_WIFI) { status = NETWORK_STAUS_WIFI } else if (conn == TYPE_MOBILE) { status = NETWORK_STATUS_MOBILE } else if (conn == TYPE_NOT_CONNECTED) { status = NETWORK_STATUS_NOT_CONNECTED } return status } } }
1
Kotlin
1
2
96fb73af1be478e24ebcc25c8d5e8cb3f71e1314
1,420
core-kotlin
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/mui/material/PaginationItem.ext.kt
karakum-team
387,062,541
false
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! package mui.material import seskar.js.JsValue import seskar.js.JsVirtual @Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsVirtual sealed external interface PaginationItemColor { companion object { @JsValue("standard") val standard: PaginationItemColor @JsValue("primary") val primary: PaginationItemColor @JsValue("secondary") val secondary: PaginationItemColor } } @Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsVirtual sealed external interface PaginationItemVariant { companion object { @JsValue("text") val text: PaginationItemVariant @JsValue("outlined") val outlined: PaginationItemVariant } } @Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsVirtual sealed external interface PaginationItemShape { companion object { @JsValue("circular") val circular: PaginationItemShape @JsValue("rounded") val rounded: PaginationItemShape } }
1
Kotlin
5
35
7c4376ba64ea84a5c40255d83c8c046978c3843d
1,054
mui-kotlin
Apache License 2.0
src/pt/goanimes/src/eu/kanade/tachiyomi/animeextension/pt/goanimes/GoAnimes.kt
almightyhak
817,607,446
false
null
package eu.kanade.tachiyomi.animeextension.pt.goanimes import eu.kanade.tachiyomi.animeextension.pt.goanimes.extractors.BloggerJWPlayerExtractor import eu.kanade.tachiyomi.animeextension.pt.goanimes.extractors.GoAnimesExtractor import eu.kanade.tachiyomi.animeextension.pt.goanimes.extractors.JsDecoder import eu.kanade.tachiyomi.animeextension.pt.goanimes.extractors.LinkfunBypasser import eu.kanade.tachiyomi.animeextension.pt.goanimes.extractors.PlaylistExtractor import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.lib.bloggerextractor.BloggerExtractor import eu.kanade.tachiyomi.lib.playlistutils.PlaylistUtils import eu.kanade.tachiyomi.multisrc.dooplay.DooPlay import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.await import eu.kanade.tachiyomi.util.asJsoup import eu.kanade.tachiyomi.util.parallelCatchingFlatMapBlocking import okhttp3.Response import org.jsoup.nodes.Element class GoAnimes : DooPlay( "pt-BR", "GoAnimes", "https://goanimes.net", ) { // ============================== Popular =============================== override fun popularAnimeSelector() = "div#featured-titles article.item.tvshows > div.poster" // =============================== Latest =============================== override val latestUpdatesPath = "lancamentos" // ============================== Episodes ============================== override val seasonListSelector = "div#seasons > *" override fun getSeasonEpisodes(season: Element): List<SEpisode> { // All episodes are listed under a single page season.selectFirst(episodeListSelector())?.let { return getSeasonEpisodesRecursive(season) } // Episodes are listed at another page val url = season.attr("href") return client.newCall(GET(url, headers)) .execute() .asJsoup() .let(::getSeasonEpisodes) } private val episodeListNextPageSelector = "div.pagination span.current + a:not(.arrow_pag)" private fun getSeasonEpisodesRecursive(season: Element): List<SEpisode> { var doc = season.root() return buildList { do { if (isNotEmpty()) { doc.selectFirst(episodeListNextPageSelector)?.let { val url = it.attr("abs:href") doc = client.newCall(GET(url, headers)).execute() .asJsoup() } } addAll(super.getSeasonEpisodes(doc)) } while (doc.selectFirst(episodeListNextPageSelector) != null) reversed() } } // ============================ Video Links ============================= override val prefQualityValues = arrayOf("240p", "360p", "480p", "720p", "1080p") override val prefQualityEntries = prefQualityValues private val goanimesExtractor by lazy { GoAnimesExtractor(client, headers) } private val bloggerExtractor by lazy { BloggerExtractor(client) } private val linkfunBypasser by lazy { LinkfunBypasser(client) } private val playlistUtils by lazy { PlaylistUtils(client, headers) } override fun videoListParse(response: Response): List<Video> { val document = response.asJsoup() val players = document.select("ul#playeroptionsul li") return players.parallelCatchingFlatMapBlocking(::getPlayerVideos) } private suspend fun getPlayerVideos(player: Element): List<Video> { val name = player.selectFirst("span.title")!!.text() .replace("FULLHD", "1080p") .replace("HD", "720p") .replace("SD", "480p") val url = getPlayerUrl(player) return when { "player5.goanimes.net" in url -> goanimesExtractor.videosFromUrl(url, name) "https://gojopoolt" in url -> { val headers = headers.newBuilder() .set("referer", url) .build() val script = client.newCall(GET(url, headers)).await() .body.string() .let { JsDecoder.decodeScript(it, false).ifBlank { it } } script.substringAfter("sources: [") .substringBefore(']') .split('{') .drop(1) .mapNotNull { val videoUrl = it.substringAfter("file: ") .substringBefore(", ") .trim('"', '\'', ' ') .ifBlank { return@mapNotNull null } val resolution = it.substringAfter("label: ", "") .substringAfter('"') .substringBefore('"') .ifBlank { name.split('-').last().trim() } val partialName = name.split('-').first().trim() return when { videoUrl.contains(".m3u8") -> { playlistUtils.extractFromHls( videoUrl, url, videoNameGen = { "$partialName - ${it.replace("Video", resolution)}" }, ) } else -> listOf(Video(videoUrl, "$partialName - $resolution", videoUrl, headers)) } } } listOf("/bloggerjwplayer", "/m3u8", "/multivideo").any { it in url } -> { val script = client.newCall(GET(url)).await() .body.string() .let(JsDecoder::decodeScript) when { "/bloggerjwplayer" in url -> BloggerJWPlayerExtractor.videosFromScript(script) "/m3u8" in url -> PlaylistExtractor.videosFromScript(script) "/multivideo" in url -> script.substringAfter("attr") .substringAfter(" \"") .substringBefore('"') .let { goanimesExtractor.videosFromUrl(it, name) } else -> emptyList<Video>() } } "www.blogger.com" in url -> bloggerExtractor.videosFromUrl(url, headers) else -> emptyList<Video>() } } private suspend fun getPlayerUrl(player: Element): String { val type = player.attr("data-type") val id = player.attr("data-post") val num = player.attr("data-nume") val url = client.newCall(GET("$baseUrl/wp-json/dooplayer/v2/$id/$type/$num")) .await() .body.string() .substringAfter("\"embed_url\":\"") .substringBefore("\",") .replace("\\", "") return when { "/protetorlinks/" in url -> { val link = client.newCall(GET(url)).await() .asJsoup() .selectFirst("a[href]")!!.attr("href") client.newCall(GET(link)).await() .use(linkfunBypasser::getIframeUrl) } else -> url } } // ============================= Utilities ============================== override fun List<Video>.sort(): List<Video> { val quality = preferences.getString(videoSortPrefKey, videoSortPrefDefault)!! return sortedWith( compareBy( { it.quality.contains(quality) }, { Regex("""(\d+)p""").find(it.quality)?.groupValues?.get(1)?.toIntOrNull() ?: 0 }, ), ).reversed() } }
55
null
28
93
507dddff536702999357b17577edc48353eab5ad
7,900
aniyomi-extensions
Apache License 2.0
core-starter/src/main/kotlin/com/labijie/application/exception/InvalidPhoneNumberException.kt
hongque-pro
309,874,586
false
{"Kotlin": 1091422, "Java": 72766}
package com.labijie.application.exception import com.labijie.application.ApplicationErrors import com.labijie.application.ErrorCodedException /** * Created with IntelliJ IDEA. * @author <NAME> * @date 2019-12-14 */ class InvalidPhoneNumberException(message:String? = null, val inputPhone: String) : ErrorCodedException(ApplicationErrors.InvalidPhoneNumber, message?:"bad phone number format") {}
0
Kotlin
0
7
7ace1a3912009a1214ac329f787704a1899e63b8
405
application-framework
Apache License 2.0
src/main/kotlin/com/cluttered/cryptocurrency/PublicBittrexClient.kt
cluttered-cryptocurrency
110,364,175
false
null
package com.cluttered.cryptocurrency import com.cluttered.cryptocurrency.services.PublicBittrexService class PublicBittrexClient { val public by lazy { PublicBittrexService.create() } }
0
Kotlin
3
5
02490eeef318b04c3407e56a9cfff0cfd1695bd8
204
bittrex-kotlin-client
MIT License
ChoiceSDK/choicesdk-maps/src/main/java/at/bluesource/choicesdk/maps/common/options/TileOverlayOptions.kt
bluesource
342,192,341
false
null
package at.bluesource.choicesdk.maps.common.options import android.os.Parcel import at.bluesource.choicesdk.maps.common.TileProvider import at.bluesource.choicesdk.maps.common.TileProvider.Companion.toChoiceTileProvider import at.bluesource.choicesdk.maps.factory.TileOverlayOptionsFactory import at.bluesource.choicesdk.maps.gms.GmsTileOverlayOptions import at.bluesource.choicesdk.maps.hms.HmsTileOverlayOptions /** * Common interface for gms hms TileOverlayOptions * * Defines options for a TileOverlay. * * @see com.google.android.gms.maps.model.TileOverlayOptions * @see com.huawei.hms.maps.model.TileOverlayOptions */ interface TileOverlayOptions { fun fadeIn(fadeIn: Boolean): TileOverlayOptions fun getFadeIn(): Boolean fun getTileProvider(): TileProvider? fun getTransparency(): Float fun getZIndex(): Float fun isVisible(): Boolean fun tileProvider(tileProvider: TileProvider?): TileOverlayOptions fun transparency(transparency: Float): TileOverlayOptions fun visible(visible: Boolean): TileOverlayOptions fun writeToParcel(out: Parcel, flags: Int) fun zIndex(zIndex: Float): TileOverlayOptions companion object { fun create(): TileOverlayOptions { return TileOverlayOptionsFactory.getTileOverlayOptions() } @JvmStatic fun com.google.android.gms.maps.model.TileOverlayOptions.toChoice(): TileOverlayOptions { return create() .fadeIn(this.fadeIn) .tileProvider(this.tileProvider?.toChoiceTileProvider()) .transparency(this.transparency) .visible(this.isVisible) .zIndex(this.zIndex) } internal fun TileOverlayOptions.toGmsTileOverlayOptions(): com.google.android.gms.maps.model.TileOverlayOptions? { return when (this) { is GmsTileOverlayOptions -> { this.getTileOverlayOptions() } else -> null } } internal fun TileOverlayOptions.toHmsTileOverlayOptions(): com.huawei.hms.maps.model.TileOverlayOptions? { return when (this) { is HmsTileOverlayOptions -> { this.getTileOverlayOptions() } else -> null } } } }
11
null
19
85
4c70f2711f9ee71aa7ae73ab4d6eaa5a3fa81274
2,363
ChoiceSDK
Apache License 2.0
graphics/src/main/java/com/gamapp/Test.kt
aliHosseinNezhad
507,626,994
false
null
package com.gamapp import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.paint import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import com.gamapp.custom.TimeLine import kotlin.math.abs @Composable fun TestSeekBar() { var value by remember { mutableStateOf(0f) } val interactionSource = remember { MutableInteractionSource() } LaunchedEffect(key1 = interactionSource) { interactionSource.interactions.collect { val interaction = if (it is DragInteraction) when (it) { is DragInteraction.Start -> { "drag/start" } is DragInteraction.Stop -> { "drag/stop" } is DragInteraction.Cancel -> { "drag/cancel" } else -> { "drag/*" } } else if (it is PressInteraction) if (it is PressInteraction.Press) "press/press" else "press/cancel" else "none" Log.i(TAG, "TestSeekBar: $interaction") } } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { TimeLine( value = { value }, onValueChange = { }, currentTime = { 0 }, duration = { 5000 }, interactionSource = interactionSource ) } } const val max = 900f @Preview @Composable fun NestedScrollTest() { var offset by remember { mutableStateOf(max) } fun scrollBy(ds: Float): Float { if (offset == 0f && ds < 0f) return 0.0f if (offset == max && ds > 0f) return 0.0f val pv = offset offset = (ds + offset).coerceIn(0f, max) return offset - pv } val nestedScrollConnection = remember { object : NestedScrollConnection { override fun onPreScroll( available: Offset, source: NestedScrollSource ): Offset { return if (available.y < 0) { val consumed = scrollBy(available.y) Offset(x = 0f, y = consumed) } else Offset.Zero } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { return if (abs(available.y) > 0f && available.y > 0f ) { Offset(0f, scrollBy(available.y)) } else super.onPostScroll(consumed, available, source) } override suspend fun onPreFling(available: Velocity): Velocity { Log.i(TAG, "velocity:$available offset:$offset") return super.onPreFling(available) } } } Column(modifier = Modifier.fillMaxSize()) { Box( modifier = Modifier .fillMaxWidth() .height(80.dp) ) LazyColumn( modifier = Modifier .graphicsLayer { translationY = offset } .nestedScroll(connection = nestedScrollConnection) .fillMaxWidth() .weight(1f) ) { items(100) { Box( modifier = Modifier .fillMaxWidth() .height(60.dp) .background(Color.Blue) ) Spacer(modifier = Modifier.height(8.dp)) } } } }
0
Kotlin
0
2
8eddbdbcd5706072262ed7bd2cf6b2d0a6df6ada
4,638
DMPlayer_public
MIT License
app/src/main/kotlin/com/flxrs/dankchat/data/api/auth/dto/ValidateErrorDto.kt
flex3r
186,238,019
false
{"Kotlin": 977613}
package com.flxrs.dankchat.data.api.auth.dto import androidx.annotation.Keep import kotlinx.serialization.Serializable @Keep @Serializable data class ValidateErrorDto( val status: Int, val message: String )
73
Kotlin
37
266
49d86a05f3bba655881e6e93360f216316cee7c9
216
DankChat
MIT License
src/main/kotlin/net/machina/passman/controllers/EntriesFragmentController.kt
Machina123
260,757,657
false
null
package net.machina.passman.controllers import javafx.scene.control.Alert import javafx.scene.control.ButtonBar import javafx.scene.control.ButtonType import kotlinx.serialization.builtins.list import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import net.machina.passman.models.PasswordEntry import net.machina.passman.storage.DatabaseHandler import net.machina.passman.views.EntriesFragment import tornadofx.* class EntriesFragmentController : Controller() { var context: EntriesFragment? = null var entryList = listOf<PasswordEntry>().toMutableList() var currentEntry: PasswordEntry? = null set(entry) { System.err.println("Setter for currentEntry called for object $entry") field = entry if(entry != null) { context!!.entryName.text = entry.name context!!.entryLogin.text = entry.login if (isPasswordDisplayed) context!!.entryPassword.text = entry.password else context!!.entryPassword.text = getDots(entry.password.length) context!!.editButton.isDisable = false context!!.deleteButton.isDisable = false } } var isPasswordDisplayed = false set(display) { if (currentEntry != null) { if (display) { context!!.entryPassword.text = currentEntry!!.password } else if (!display) { context!!.entryPassword.text = getDots(currentEntry!!.password.length) } } field = display } fun getEntries() { try { val dataJson = DatabaseHandler.read() val json = Json(JsonConfiguration.Stable) entryList = json.parse(PasswordEntry.serializer().list, dataJson).toMutableList() invalidateView() context!!.statusLabel.text = "Database successfully loaded" context!!.dbPathLabel.text = DatabaseHandler.dbPath } catch (e: Exception) { e.printStackTrace() alert(Alert.AlertType.ERROR, "Error", "An error occurred during data deserialization: " + e.message) } } fun saveDatabase(message: String = "Database successfully updated") { try { invalidateView() val json = Json(JsonConfiguration.Stable) val exported = json.stringify(PasswordEntry.serializer().list, entryList.toList()) DatabaseHandler.write(exported) context!!.statusLabel.text = message } catch (e: Exception) { e.printStackTrace() alert(Alert.AlertType.ERROR, "Error", "An error occurred during database saving: " + e.message) } } fun modifyEntry(name: String, newName: String, login: String, password: String) { val element: PasswordEntry = entryList.first { it.name == name } modifyEntry(element, newName, login, password) } fun modifyEntry(obj: PasswordEntry, newName: String, login: String, password: String) { val checkExistingName = entryList.firstOrNull { it.name == newName } if (checkExistingName == null || obj.name == newName) { obj.name = newName obj.login = login obj.password = password saveDatabase("Entry successfully updated") } else { alert(Alert.AlertType.WARNING, "Warning", "Name needs to be unique") } } fun addEntry(name: String, login: String, password: String) { val checkExistingName = entryList.firstOrNull { it.name == name } if (checkExistingName == null) { val element = PasswordEntry(name, login, password) entryList.add(element) System.err.println("addEntry(): list length = " + entryList.size) saveDatabase("New entry successfully added") } else { alert(Alert.AlertType.WARNING, "Warning", "Name needs to be unique") } } fun deleteEntry(obj: PasswordEntry) { System.err.println("Deleting object $obj") System.err.println("Deletion successful? " + entryList.remove(obj)) saveDatabase("Entry successfully deleted") } fun getDots(count: Int): String { val dotChar = "\u2022" var dotted = "" for (i in 1..count) { dotted += dotChar } return dotted } fun invalidateView() { System.err.println("invalidateView() called") currentEntry = null context!!.entryList.selectionModel.clearSelection() context!!.entryName.text = "" context!!.entryLogin.text = "" context!!.entryPassword.text = "" context!!.editButton.isDisable = true context!!.deleteButton.isDisable = true context!!.entryList.items = null context!!.entryList.refresh() context!!.entryList.items = entryList.asObservable() context!!.entryList.refresh() } }
0
Kotlin
1
0
6d057a5aa0e4865c8a834d55d3dba3b516e469d8
5,013
PasswordManager
MIT License
NewsApp/app/src/main/java/com/example/newsapp/ui/DetailNewsFragment.kt
aliahmedbd
474,373,761
false
{"Kotlin": 37878}
package com.example.newsapp.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.webkit.WebViewClient import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.example.newsapp.R import com.example.newsapp.databinding.FragmentDetailNewsBinding import com.example.newsapp.viewmodel.NewsViewModel import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.sharedViewModel class DetailNewsFragment : Fragment() { private lateinit var binding: FragmentDetailNewsBinding private val viewModel: NewsViewModel by sharedViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_detail_news, null, false) lifecycleScope.launch { viewModel.newsURL.collect { loadURL(it) } } return binding.root } private fun loadURL(url: String) { binding.webView.settings.javaScriptEnabled = true binding.webView.webViewClient = WebViewClient() binding.webView.loadUrl(url) } }
0
Kotlin
1
4
78b3f92af0fce375f4dad1032d086d74ee0ecc33
1,354
News-App-MVVM-Kotlin-Coroutine--Flow-Koin-Retrofit-
Apache License 2.0
app/src/main/java/com/bytestore/snaprecyclerview/ItemViewHolder.kt
Humblefool97
357,503,042
false
null
package com.bytestore.snaprecyclerview import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val textView = view.findViewById<TextView>(R.id.textView) fun bind(item: String?) { textView.text = item ?: "-" } }
0
Kotlin
0
0
68261c04e3ca7f8d2d932d7a1818d56c40de6ad6
357
SnapRecyclerView
Apache License 2.0
idea/tests/testData/checker/codeFragments/unusedEquals.kt
JetBrains
278,369,660
false
null
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.UnusedEqualsInspection fun main() { val list = java.util.ArrayList<Int>() <caret>val x = 0 } fun <T> Collection<T>.isAny(predicate: (T) -> Boolean): Boolean { for (item in this) { if (predicate(item)) { return true } } return false }
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
343
intellij-kotlin
Apache License 2.0
pushlib/src/main/java/com/saint/pushlib/opush/OPushInit.kt
saint-li
225,820,695
false
null
package com.saint.pushlib.opush import android.app.Application import android.text.TextUtils import androidx.annotation.NonNull import androidx.annotation.Nullable import com.heytap.msp.push.HeytapPushManager import com.heytap.msp.push.callback.ICallBackResultService import com.saint.pushlib.BasePushInit import com.saint.pushlib.PushConstant import com.saint.pushlib.PushConstant.OPPO import com.saint.pushlib.R import com.saint.pushlib.util.PushLog.Companion.i import com.saint.pushlib.util.PushUtil.getMetaData class OPushInit(isDebug: Boolean, private val application: Application) : BasePushInit(isDebug, application) { private val appSecret = getMetaData(application, "OPPO_SECRET") private val appKey = getMetaData(application, "OPPO_APPKEY") /** * 推送初始化 * * @param isDebug 设置debug模式 * @param application -- */ init { if (!TextUtils.isEmpty(appKey) && !TextUtils.isEmpty(appSecret)) { HeytapPushManager.init(application, isDebug) } else { initFailed(getString(R.string.OPPO), OPPO, "OPPO_APPKEY=$appKey,appSecret=$appSecret") } } override fun loginIn() { if (!TextUtils.isEmpty(appKey) && !TextUtils.isEmpty(appSecret)) { HeytapPushManager.register(application, appKey, appSecret, OPushRegisterCallBack()) } else { initFailed(getString(R.string.OPPO), OPPO, "OPPO_APPKEY=$appKey,appSecret=$appSecret") } } inner class OPushRegisterCallBack : ICallBackResultService { override fun onRegister(code: Int, s: String) { if (code == 0) { showResult("获取RegisterId成功", "registerId:$s") onToken(s, OPPO) } else { showResult("注册失败", "code=$code,msg=$s") initFailed(getString(R.string.OPPO), OPPO, "code=$code,msg=$s") } } override fun onUnRegister(code: Int) { if (code == 0) { showResult("注销成功", "code=$code") } else { showResult("注销失败", "code=$code") } } override fun onGetPushStatus(code: Int, status: Int) { if (code == 0 && status == 0) { showResult("Push状态正常", "code=$code,status=$status") } else { showResult("Push状态错误", "code=$code,status=$status") } } override fun onGetNotificationStatus(code: Int, status: Int) { if (code == 0 && status == 0) { showResult("通知状态正常", "code=$code,status=$status") } else { showResult("通知状态错误", "code=$code,status=$status") } } override fun onError(code: Int, s: String?) { showResult("onError", "onError code = $code msg = $s") } override fun onSetPushTime(code: Int, s: String) { showResult("SetPushTime", "code=$code,result:$s") } } /** * 此方法会将结果进行回显 */ private fun showResult(@Nullable tag: String, @NonNull msg: String) { i("$tag:$msg") } }
0
Kotlin
0
0
7ea600cb78dbbbcd04c7987c82d785ccd91fe9f2
3,115
pushlib
Apache License 2.0
src/main/java/co/com/japl/ui/utils/NumbersUtil.kt
nano871022
875,529,336
false
{"Kotlin": 95501}
package co.japl.android.myapplication.utils import android.util.Log import android.widget.EditText import android.widget.TextView import java.math.BigDecimal import java.text.DecimalFormat class NumbersUtil { companion object { private val formatDecimalMoneyCO = "$ #,###.00" private val formatDecimal = "#,###.00" fun COPtoString(value: BigDecimal): String { return DecimalFormat(formatDecimalMoneyCO).format(value) } fun COPtoString(value: Double): String { return DecimalFormat(formatDecimalMoneyCO).format(value) } fun toString(value: Long): String { return DecimalFormat(formatDecimal).format(value) } fun toString(value: Double): String { return DecimalFormat(formatDecimal).format(value) } fun toString(value: BigDecimal): String { return DecimalFormat(formatDecimal).format(value) } fun toString(field:EditText): String{ return if(field.text?.isNotBlank() == true) { toString(field.text.toString().replace(",", "").toBigDecimal()) }else{ "" } } fun stringCOPToBigDecimal(value:String):BigDecimal{ return if(value.isEmpty()){ BigDecimal.ZERO }else { value.replace(" ", "").replace("$", "").replace("'", "").replace(",", "").trim().toBigDecimal() } } fun toBigDecimal(field:EditText):BigDecimal{ return if(field.text?.isNotBlank() == true) { field.text.toString().replace("$", "").replace(",", "").trim().toBigDecimal() }else{ BigDecimal.ZERO } } fun toBigDecimal(field:String):BigDecimal{ return field?.takeIf { it.isNotBlank() }?.let { it.toString().replace("$", "").replace(",", "").trim().toBigDecimal() }?:BigDecimal.ZERO } fun toBigDecimal(field:TextView):BigDecimal{ return if(field.text?.isNotBlank() == true) { field.text.toString().replace("$", "").replace(",", "").trim().toBigDecimal() }else{ BigDecimal.ZERO } } fun toDouble(field:TextView):Double{ return if(field.text?.isNotBlank() == true){ field.text.toString().replace(",","").replace("%","").trim().toDouble() }else{ 0.0 } } fun toDouble(value:String):Double{ return if(value?.isNotBlank() == true){ value.replace(",","").replace("%","").trim().toDouble() }else{ 0.0 } } fun toLong(value:String):Long{ return if(value?.isNotBlank() == true){ value.replace(",","").replace("%","").trim().toLong() }else{ 0 } } fun isNumber(value:String):Boolean{ if(value.isEmpty()) return false try{ toBigDecimal(value).toDouble() return true }catch(e:NumberFormatException){ return false } } } }
0
Kotlin
0
0
832da9fce9a8b2474091deb36bc2bde93b30cbef
3,266
japl-android-ui
Apache License 2.0
android/JDCache/src/main/java/com/jd/jdcache/JDCacheConstant.kt
JDFED
561,670,655
false
null
package com.jd.jdcache import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob internal object JDCacheConstant { internal val applicationScope by lazy { CoroutineScope(SupervisorJob()) } internal val ioDispatcher by lazy { Dispatchers.IO } internal val mainDispatcher by lazy { Dispatchers.Main.immediate } const val NET_READ_BUFFER_SIZE = 1024 * 10 const val LOCAL_READ_BUFFER_SIZE = 1024 * 2 }
0
HTML
9
89
81f3a37f1caf33f4196e140604aa91c4c92663a2
482
JDHybrid
MIT License
domain/src/main/java/com/anytypeio/anytype/domain/block/interactor/SetLinkAppearance.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.domain.block.interactor import com.anytypeio.anytype.core_models.Block import com.anytypeio.anytype.core_models.Command import com.anytypeio.anytype.core_models.Payload import com.anytypeio.anytype.domain.base.BaseUseCase import com.anytypeio.anytype.domain.base.Either import com.anytypeio.anytype.domain.block.repo.BlockRepository class SetLinkAppearance( private val repository: BlockRepository, ) : BaseUseCase<Payload, SetLinkAppearance.Params>() { data class Params( val contextId: String, val blockId: String, val content: Block.Content.Link ) override suspend fun run(params: Params): Either<Throwable, Payload> = safe { repository.setLinkAppearance( Command.SetLinkAppearance( contextId = params.contextId, blockId = params.blockId, content = params.content ) ) } }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
940
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/example/newsapp/fragment/SavedFragment.kt
ACanERL
634,247,510
false
null
package com.example.newsapp.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.newsapp.R import com.example.newsapp.adapter.NewsAdapter import com.example.newsapp.databinding.FragmentBusinessBinding import com.example.newsapp.databinding.FragmentSavedBinding import com.example.newsapp.viewmodel.NewsViewModel class SavedFragment : Fragment() { private var _binding: FragmentSavedBinding?=null private val binding get() = _binding!! lateinit var viewModel: NewsViewModel lateinit var adapter: NewsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_saved, container, false) } }
0
Kotlin
0
1
96ab70407e1d736fcd0226cf47210ecf1860c3d8
1,013
NewsApp-Kotlin
Apache License 2.0
app/src/main/java/com/omo/rememberme/presentation/peopleList/PeopleState.kt
omer358
810,455,324
false
{"Kotlin": 154396}
package com.omo.rememberme.presentation.peopleList import com.omo.rememberme.domain.model.People data class PeopleState( val people: List<People> = emptyList(), val isLoading: Boolean = false, val error: String? = null )
3
Kotlin
0
0
aaec8a9ac53575524b6f4345296a755b8db9b293
234
Remember-Me
MIT License
app/src/main/java/com/mhappening/gameclock/data/clockthemes/ClockThemeList.kt
Matt-Haywood
769,928,478
false
{"Kotlin": 276837}
package com.mhappening.gameclock.data.clockthemes import com.mhappening.gameclock.R import com.mhappening.gameclock.model.AppTheme import com.mhappening.gameclock.model.ClockFormat import com.mhappening.gameclock.model.ClockThemePreferences import com.mhappening.gameclock.ui.theme.ClockFont class ClockThemeList { fun loadThemes(): List<ClockThemePreferences> { return listOf( ClockThemePreferences( appTheme = AppTheme.Space, thumbnail = R.drawable.thumbnail_space, clockFont = ClockFont.POIRET_ONE, clockFormat = ClockFormat.VERTICAL_TWENTY_FOUR_HOUR ), ClockThemePreferences( appTheme = AppTheme.Fire, thumbnail = R.drawable.thumbnail_pixel_fire, clockFont = ClockFont.PIXELIFY_SANS, ), ClockThemePreferences( appTheme = AppTheme.Light, thumbnail = R.drawable.thumbnail_light, clockFont = ClockFont.GERMANIA_ONE, clockFormat = ClockFormat.VERTICAL_TWELVE_HOUR ), ClockThemePreferences( appTheme = AppTheme.Dark, thumbnail = R.drawable.thumbnail_dark, clockFont = ClockFont.DOPPIO ), ClockThemePreferences( appTheme = AppTheme.CodeFall, thumbnail = R.drawable.thumbnail_codefall, clockFont = ClockFont.TEKO, clockFormat = ClockFormat.TWENTY_FOUR_HOUR_WITH_SECONDS ), ClockThemePreferences( appTheme = AppTheme.DvdDark, thumbnail = R.drawable.thumbnail_gmc_dark, clockFont = ClockFont.TAC_ONE ), ClockThemePreferences( appTheme = AppTheme.DvdLight, thumbnail = R.drawable.thumbnail_gmc_light, clockFont = ClockFont.MONOTON_REGULAR ), ClockThemePreferences( appTheme = AppTheme.PinkAF, thumbnail = R.drawable.thumbnail_pinkaf, clockFont = ClockFont.WELLFLEET ), ClockThemePreferences( appTheme = AppTheme.Cat, thumbnail = R.drawable.thumbnail_cat, clockFont = ClockFont.WELLFLEET ) ) } }
0
Kotlin
0
1
96fab1ca52d9ddede722300c1c42fe6324c4110a
2,413
Game-Clock
Apache License 2.0
app/src/main/java/com/mhappening/gameclock/data/clockthemes/ClockThemeList.kt
Matt-Haywood
769,928,478
false
{"Kotlin": 276837}
package com.mhappening.gameclock.data.clockthemes import com.mhappening.gameclock.R import com.mhappening.gameclock.model.AppTheme import com.mhappening.gameclock.model.ClockFormat import com.mhappening.gameclock.model.ClockThemePreferences import com.mhappening.gameclock.ui.theme.ClockFont class ClockThemeList { fun loadThemes(): List<ClockThemePreferences> { return listOf( ClockThemePreferences( appTheme = AppTheme.Space, thumbnail = R.drawable.thumbnail_space, clockFont = ClockFont.POIRET_ONE, clockFormat = ClockFormat.VERTICAL_TWENTY_FOUR_HOUR ), ClockThemePreferences( appTheme = AppTheme.Fire, thumbnail = R.drawable.thumbnail_pixel_fire, clockFont = ClockFont.PIXELIFY_SANS, ), ClockThemePreferences( appTheme = AppTheme.Light, thumbnail = R.drawable.thumbnail_light, clockFont = ClockFont.GERMANIA_ONE, clockFormat = ClockFormat.VERTICAL_TWELVE_HOUR ), ClockThemePreferences( appTheme = AppTheme.Dark, thumbnail = R.drawable.thumbnail_dark, clockFont = ClockFont.DOPPIO ), ClockThemePreferences( appTheme = AppTheme.CodeFall, thumbnail = R.drawable.thumbnail_codefall, clockFont = ClockFont.TEKO, clockFormat = ClockFormat.TWENTY_FOUR_HOUR_WITH_SECONDS ), ClockThemePreferences( appTheme = AppTheme.DvdDark, thumbnail = R.drawable.thumbnail_gmc_dark, clockFont = ClockFont.TAC_ONE ), ClockThemePreferences( appTheme = AppTheme.DvdLight, thumbnail = R.drawable.thumbnail_gmc_light, clockFont = ClockFont.MONOTON_REGULAR ), ClockThemePreferences( appTheme = AppTheme.PinkAF, thumbnail = R.drawable.thumbnail_pinkaf, clockFont = ClockFont.WELLFLEET ), ClockThemePreferences( appTheme = AppTheme.Cat, thumbnail = R.drawable.thumbnail_cat, clockFont = ClockFont.WELLFLEET ) ) } }
0
Kotlin
0
1
96fab1ca52d9ddede722300c1c42fe6324c4110a
2,413
Game-Clock
Apache License 2.0
app/src/main/java/me/devsaki/hentoid/parsers/content/MrmContent.kt
avluis
37,775,708
false
{"C": 4044011, "Kotlin": 2689694, "Java": 705445, "C++": 465431, "CMake": 44472, "M4": 42737, "Shell": 41599, "Roff": 38560, "Makefile": 33752, "Python": 26865, "HTML": 6592, "JavaScript": 6327, "CSS": 1842, "Go": 1235}
package me.devsaki.hentoid.parsers.content import me.devsaki.hentoid.database.domains.Attribute import me.devsaki.hentoid.database.domains.AttributeMap import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.enums.AttributeType import me.devsaki.hentoid.enums.Site import me.devsaki.hentoid.enums.StatusContent import me.devsaki.hentoid.parsers.ParseHelper import me.devsaki.hentoid.util.Helper import me.devsaki.hentoid.util.StringHelper import org.jsoup.nodes.Element import pl.droidsonroids.jspoon.annotation.Selector class MrmContent : BaseContentParser() { @Selector(value = "article h1", defValue = "") private lateinit var title: String @Selector(value = "time.entry-time", attr = "datetime", defValue = "") private lateinit var uploadDate: String @Selector(".entry-header .entry-meta .entry-categories a") private var categories: List<Element>? = null @Selector(value = ".entry-header .entry-terms a[href*='/lang/']") private var languages: List<Element>? = null @Selector(value = ".entry-header .entry-terms a[href*='/genre/']") private var genres: List<Element>? = null @Selector(value = ".entry-header .entry-tags a[href*='/tag/']") private var tags: List<Element>? = null @Selector(value = ".entry-content img") private var images: List<Element>? = null override fun update(content: Content, url: String, updateImages: Boolean): Content { content.setSite(Site.MRM) if (url.isEmpty()) return Content().setStatus(StatusContent.IGNORED) content.setRawUrl(url) if (title.isNotEmpty()) { title = StringHelper.removeNonPrintableChars(title.trim { it <= ' ' }) content.setTitle(title) } else content.setTitle(NO_TITLE) content.setUploadDate( Helper.parseDatetimeToEpoch( uploadDate, "yyyy-MM-dd'T'HH:mm:ssXXX" ) ) // e.g. 2022-03-20T00:09:43+07:00 images?.let { if (it.isNotEmpty()) content.setCoverImageUrl(ParseHelper.getImgSrc(it[0])) } val attributes = AttributeMap() // On MRM, most titles are formatted "[Artist] Title" although there's no actual artist field on the book page if (title.startsWith("[")) { val closingBracketIndex = title.indexOf(']') if (closingBracketIndex > -1) { val attribute = Attribute( AttributeType.ARTIST, title.substring(1, closingBracketIndex), "", Site.MRM ) attributes.add(attribute) } } ParseHelper.parseAttributes(attributes, AttributeType.CATEGORY, categories, false, Site.MRM) ParseHelper.parseAttributes(attributes, AttributeType.LANGUAGE, languages, false, Site.MRM) ParseHelper.parseAttributes(attributes, AttributeType.TAG, genres, false, Site.MRM) ParseHelper.parseAttributes(attributes, AttributeType.TAG, tags, false, Site.MRM) content.putAttributes(attributes) if (updateImages) { content.setImageFiles(emptyList()) content.setQtyPages(0) } return content } }
173
C
80
983
2971c6c60a7d09e20b635d3e99519516258b3c4a
3,273
Hentoid
Apache License 2.0
kobalt-runner-agent/src/main/kotlin/com/buildServer/kobalt/agent/KobaltLoggingListener.kt
dmitry-zhuravlev
70,356,271
false
null
package com.buildServer.kobalt.agent import jetbrains.buildServer.agent.BuildProgressLogger import jetbrains.buildServer.agent.runner.ProcessListenerAdapter import jetbrains.buildServer.messages.DefaultMessagesInfo /** * @author Dmitry Zhuravlev * Date: 08/10/2016 */ internal class KobaltLoggingListener(val buildLogger: BuildProgressLogger) : ProcessListenerAdapter() { val errorMessages = mutableListOf<String>() override fun onStandardOutput(text: String) { buildLogger.message(text) } override fun onErrorOutput(text: String) { errorMessages += text } override fun processFinished(exitCode: Int) = if (exitCode != 0 && errorMessages.isNotEmpty()) { buildLogger.activityStarted("Kobalt failure", DefaultMessagesInfo.BLOCK_TYPE_TARGET) flushErrorMessages() buildLogger.activityFinished("Kobalt failure", DefaultMessagesInfo.BLOCK_TYPE_TARGET) } else { flushErrorMessages() } private fun flushErrorMessages() = with(errorMessages) { for (errorMessage in this) { buildLogger.warning(errorMessage) } errorMessages.clear() } }
0
Kotlin
0
0
23dc942f8dacebe439aa21c29bfa7b990a9fdbe8
1,229
kobalt-runner-teamcity-plugin
Apache License 2.0
app/src/main/java/com/dekow/githubuserinfo/domain/model/UserDetails.kt
Mohameddekow
499,757,162
false
{"Kotlin": 66031}
package com.dekow.githubuserinfo.domain.model import com.google.gson.annotations.SerializedName data class UserDetails ( val avatarUrl: String? = null, val bio: String? = null, val blog: String? = null, val company: String? = null, val htmlUrl: String? = null, val followers: Int? = null, val followersUrl: String? = null, val following: Int? = null, val followingUrl: String? = null, val id: Int? = null, val location: String? = null, val login: String? = null, val name: String? = null, val organizationsUrl: String? = null, val publicRepos: Int? = null, val receivedEventsUrl: String? = null, val reposUrl: String? = null, val starredUrl: String? = null, val twitterUsername: String? = null, val url: String? = null, val placeHolderId : Int? = null, val publicGist : Int? = null, val nodeId : String? = null )
0
Kotlin
4
6
0a7c630d18fce22b84a32e39b7a097b2abe9aa7e
907
GithubUserInfo
MIT License
octicons/src/commonMain/kotlin/compose/icons/octicons/Megaphone16.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.octicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 compose.icons.Octicons public val Octicons.Megaphone16: ImageVector get() { if (_megaphone16 != null) { return _megaphone16!! } _megaphone16 = Builder(name = "Megaphone16", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(15.571f, 0.572f) arcTo(0.75f, 0.75f, 0.0f, false, true, 16.0f, 1.25f) lineTo(14.777f, 0.668f) curveToRelative(0.001f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f) lineToRelative(-0.015f, 0.012f) lineToRelative(-0.076f, 0.056f) arcToRelative(5.508f, 5.508f, 0.0f, false, true, -0.345f, 0.224f) arcToRelative(9.982f, 9.982f, 0.0f, false, true, -1.463f, 0.719f) curveToRelative(-1.322f, 0.528f, -3.351f, 1.07f, -6.124f, 1.071f) arcToRelative(1.6f, 1.6f, 0.0f, false, false, -0.861f, -0.25f) horizontalLineTo(4.0f) arcToRelative(4.0f, 4.0f, 0.0f, false, false, -1.499f, 7.71f) arcToRelative(0.758f, 0.758f, 0.0f, false, false, -0.001f, 0.04f) curveToRelative(0.0f, 2.32f, 0.486f, 3.93f, 0.813f, 4.75f) curveToRelative(0.262f, 0.66f, 0.897f, 1.0f, 1.517f, 1.0f) horizontalLineToRelative(1.197f) curveToRelative(0.685f, 0.0f, 1.228f, -0.389f, 1.546f, -0.857f) curveToRelative(0.317f, -0.466f, 0.468f, -1.09f, 0.31f, -1.696f) curveToRelative(-0.2f, -0.767f, -0.382f, -1.835f, -0.383f, -3.183f) curveToRelative(2.394f, 0.086f, 4.177f, 0.577f, 5.378f, 1.057f) arcToRelative(9.965f, 9.965f, 0.0f, false, true, 1.463f, 0.719f) arcToRelative(5.7f, 5.7f, 0.0f, false, true, 0.421f, 0.28f) lineToRelative(0.014f, 0.012f) horizontalLineToRelative(0.002f) arcTo(0.75f, 0.75f, 0.0f, false, false, 16.0f, 11.75f) verticalLineTo(1.25f) lineTo(14.777f, 0.668f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.794f, -0.096f) close() moveTo(4.002f, 10.5f) curveToRelative(0.033f, 1.969f, 0.45f, 3.306f, 0.704f, 3.946f) curveToRelative(0.004f, 0.01f, 0.01f, 0.02f, 0.027f, 0.03f) arcToRelative(0.185f, 0.185f, 0.0f, false, false, 0.097f, 0.024f) horizontalLineToRelative(1.197f) curveToRelative(0.083f, 0.0f, 0.202f, -0.047f, 0.305f, -0.2f) arcToRelative(0.608f, 0.608f, 0.0f, false, false, 0.1f, -0.475f) arcToRelative(14.036f, 14.036f, 0.0f, false, true, -0.43f, -3.329f) arcToRelative(1.64f, 1.64f, 0.0f, false, true, -0.11f, 0.004f) horizontalLineToRelative(-1.89f) close() moveTo(7.5f, 8.763f) curveToRelative(2.601f, 0.087f, 4.573f, 0.62f, 5.935f, 1.166f) curveToRelative(0.41f, 0.164f, 0.766f, 0.33f, 1.065f, 0.483f) verticalLineTo(2.588f) curveToRelative(-0.3f, 0.154f, -0.654f, 0.319f, -1.065f, 0.483f) curveTo(12.073f, 3.616f, 10.1f, 4.15f, 7.5f, 4.237f) verticalLineToRelative(4.526f) close() moveTo(14.777f, 0.668f) close() moveTo(1.5f, 6.5f) arcTo(2.5f, 2.5f, 0.0f, false, true, 4.0f, 4.0f) horizontalLineToRelative(1.893f) curveToRelative(0.059f, 0.0f, 0.107f, 0.048f, 0.107f, 0.107f) verticalLineToRelative(4.786f) arcTo(0.107f, 0.107f, 0.0f, false, true, 5.893f, 9.0f) horizontalLineTo(4.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, true, -2.5f, -2.5f) close() } } .build() return _megaphone16!! } private var _megaphone16: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
4,797
compose-icons
MIT License
app/src/main/java/com/starwars/app/character/presentation/component/CharacterItem.kt
ali-yousuf
701,354,114
false
{"Kotlin": 78507}
package com.starwars.app.character.presentation.component import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.starwars.app.character.domain.entity.Character @Composable fun CharacterItem(character: Character){ Box(modifier = Modifier.padding(top = 8.dp)) { Card( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant, ), modifier = Modifier .fillMaxWidth() ) { Column { Text( text = character.name!!, modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = character.birthYear!!, modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = character.gender!!, modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) } } } }
0
Kotlin
0
0
679427a636e9704e50de9740c72a7c783735a0c3
1,690
StarWars
Apache License 2.0
mvp/lib-core-mvp/src/main/java/ru/surfstudio/android/core/mvp/loadstate/BaseLoadStateRenderer.kt
surfstudio
139,034,657
false
{"Kotlin": 2966626, "Java": 1025166, "FreeMarker": 104337, "Groovy": 43020, "C++": 1542, "Ruby": 884, "CMake": 285, "Shell": 33, "Makefile": 25}
/* Copyright (c) 2018-present, SurfStudio 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 ru.surfstudio.android.core.mvp.loadstate import android.view.View import kotlin.reflect.KClass /** * Базовый класс, от которого предполагается наследовать собственные в проекте * хранит Map, в котором каждому стейту соответствует представление * хранит список лямбд, которые должны быть выполненными при том или ином стейте */ abstract class BaseLoadStateRenderer : LoadStateRendererInterface { abstract val defaultState: LoadStateInterface private val presentations = mutableMapOf<Class<*>, LoadStatePresentation<*>>() private val doForStateActions = mutableListOf<Pair< (state: LoadStateInterface) -> Boolean, (isSuitableState: Boolean) -> Unit>>() private var _currentState: LoadStateInterface? = null private val currentState: LoadStateInterface get() { if (_currentState == null) { _currentState = defaultState } return _currentState!! } override fun render(loadState: LoadStateInterface?) { loadState ?: return getPresentation(currentState.javaClass).hideState(currentState, loadState) getPresentation(loadState.javaClass).showState(loadState, currentState) doForStateActions.forEach { it.second(it.first(loadState)) } _currentState = loadState } /** * @return BaseLoadStateRenderer in Fluent interface style */ fun <T : LoadStateInterface> putPresentation( loadState: Class<T>, presentationStrategy: LoadStatePresentation<T>): BaseLoadStateRenderer { presentations[loadState] = presentationStrategy return this } /** * @return BaseLoadStateRenderer in Fluent interface style */ fun <T : LoadStateInterface> putPresentation( loadState: KClass<T>, presentationStrategy: LoadStatePresentation<T>): BaseLoadStateRenderer { presentations[loadState.java] = presentationStrategy return this } @Suppress("UNCHECKED_CAST") protected fun <T : LoadStateInterface> getPresentation(loadStateClass: Class<T>) = presentations[loadStateClass] as? LoadStatePresentation<T> ?: throw UnknownLoadStateException(loadStateClass.simpleName) @Suppress("UNCHECKED_CAST") protected fun <T : LoadStateInterface> getPresentation(loadStateClass: KClass<T>) = presentations[loadStateClass.java] as? LoadStatePresentation<T> ?: throw UnknownLoadStateException(loadStateClass.java.simpleName) //region forStates fun forState( loadState: Class<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(loadState), run, elseRun) fun forState( loadState: KClass<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(loadState.java), run, elseRun) fun forStates( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(firstLoadState, secondLoadState), run, elseRun) fun forStates( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(firstLoadState.java, secondLoadState.java), run, elseRun) fun forStates( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(firstLoadState, secondLoadState, thirdLoadState), run, elseRun) fun forStates( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null) = forStates( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), run, elseRun) fun forStates( loadStates: List<Class<out LoadStateInterface>>, run: (() -> Unit)? = null, elseRun: (() -> Unit)? = null): BaseLoadStateRenderer { val check = { state: LoadStateInterface -> loadStates.contains(state::class.java) } val action = { check: Boolean -> if (check) { run?.invoke() } else { elseRun?.invoke() } ?: Unit } doForStateActions.add(Pair(check, action)) return this } //endregion //region doWithCheck fun doWithCheck( loadState: Class<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(loadState), action) return this } fun doWithCheck( loadState: KClass<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(loadState.java), action) return this } fun doWithCheck( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(firstLoadState, secondLoadState), action) return this } fun doWithCheck( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(firstLoadState.java, secondLoadState.java), action) return this } fun doWithCheck( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(firstLoadState, secondLoadState, thirdLoadState), action) return this } fun doWithCheck( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doWithCheck(listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), action) return this } fun doWithCheck(loadStates: List<Class<out LoadStateInterface>>, action: (check: Boolean) -> Unit): BaseLoadStateRenderer { doForStateActions.add(Pair( { it: LoadStateInterface -> loadStates.contains(it::class.java) }, { it: Boolean -> action.invoke(it) })) return this } //endregion //region setViewsVisibleFor fun setViewsVisibleFor( loadStates: List<Class<out LoadStateInterface>>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE): BaseLoadStateRenderer { setViewsVisibilityFor(loadStates, views, View.VISIBLE, visibilityWhenHidden) return this } fun setViewsVisibleFor( loadState: Class<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(loadState), views, visibilityWhenHidden) fun setViewsVisibleFor( loadState: KClass<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(loadState.java), views, visibilityWhenHidden) fun setViewsVisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(firstLoadState, secondLoadState), views, visibilityWhenHidden) fun setViewsVisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(firstLoadState.java, secondLoadState.java), views, visibilityWhenHidden) fun setViewVisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewVisibleFor( listOf(firstLoadState, secondLoadState), view, visibilityWhenHidden) fun setViewVisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewVisibleFor( listOf(firstLoadState.java, secondLoadState.java), view, visibilityWhenHidden) fun setViewsVisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(firstLoadState, secondLoadState, thirdLoadState), views, visibilityWhenHidden) fun setViewsVisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, views: List<View>, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), views, visibilityWhenHidden) fun setViewVisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewVisibleFor( listOf(firstLoadState, secondLoadState, thirdLoadState), view, visibilityWhenHidden) fun setViewVisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewVisibleFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), view, visibilityWhenHidden) fun setViewVisibleFor( loadStates: List<Class<out LoadStateInterface>>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( loadStates, listOf(view), visibilityWhenHidden) fun setViewVisibleFor( loadState: Class<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(loadState), listOf(view), visibilityWhenHidden) fun setViewVisibleFor( loadState: KClass<out LoadStateInterface>, view: View, visibilityWhenHidden: Int = View.INVISIBLE) = setViewsVisibleFor( listOf(loadState.java), listOf(view), visibilityWhenHidden) //endregion //region setViewsInvisibleFor fun setViewsInvisibleFor( loadStates: List<Class<out LoadStateInterface>>, views: List<View>): BaseLoadStateRenderer { setViewsVisibilityFor(loadStates, views, View.INVISIBLE, View.VISIBLE) return this } fun setViewsInvisibleFor( loadState: Class<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(loadState), views) fun setViewsInvisibleFor( loadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(loadState.java), views) fun setViewsInvisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(firstLoadState, secondLoadState), views) fun setViewsInvisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(firstLoadState.java, secondLoadState.java), views) fun setViewInvisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, view: View) = setViewInvisibleFor( listOf(firstLoadState, secondLoadState), view) fun setViewInvisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, view: View) = setViewInvisibleFor( listOf(firstLoadState.java, secondLoadState.java), view) fun setViewsInvisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(firstLoadState, secondLoadState, thirdLoadState), views) fun setViewsInvisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsInvisibleFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), views) fun setViewInvisibleFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, view: View) = setViewInvisibleFor( listOf(firstLoadState, secondLoadState, thirdLoadState), view) fun setViewInvisibleFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, view: View) = setViewInvisibleFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), view) fun setViewInvisibleFor( loadStates: List<Class<out LoadStateInterface>>, view: View) = setViewsInvisibleFor( loadStates, listOf(view)) fun setViewInvisibleFor( loadState: Class<out LoadStateInterface>, view: View) = setViewsInvisibleFor( listOf(loadState), listOf(view)) fun setViewInvisibleFor( loadState: KClass<out LoadStateInterface>, view: View) = setViewsInvisibleFor( listOf(loadState.java), listOf(view)) //endregion //region setViewsGoneFor fun setViewsGoneFor( loadStates: List<Class<out LoadStateInterface>>, views: List<View>): BaseLoadStateRenderer { setViewsVisibilityFor(loadStates, views, View.GONE, View.VISIBLE) return this } fun setViewsGoneFor( loadState: Class<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(loadState), views) fun setViewsGoneFor( loadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(loadState.java), views) fun setViewsGoneFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(firstLoadState, secondLoadState), views) fun setViewsGoneFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(firstLoadState.java, secondLoadState.java), views) fun setViewGoneFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, view: View) = setViewGoneFor( listOf(firstLoadState, secondLoadState), view) fun setViewGoneFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, view: View) = setViewGoneFor( listOf(firstLoadState.java, secondLoadState.java), view) fun setViewsGoneFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(firstLoadState, secondLoadState, thirdLoadState), views) fun setViewsGoneFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, views: List<View>) = setViewsGoneFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), views) fun setViewGoneFor( firstLoadState: Class<out LoadStateInterface>, secondLoadState: Class<out LoadStateInterface>, thirdLoadState: Class<out LoadStateInterface>, view: View) = setViewGoneFor( listOf(firstLoadState, secondLoadState, thirdLoadState), view) fun setViewGoneFor( firstLoadState: KClass<out LoadStateInterface>, secondLoadState: KClass<out LoadStateInterface>, thirdLoadState: KClass<out LoadStateInterface>, view: View) = setViewGoneFor( listOf(firstLoadState.java, secondLoadState.java, thirdLoadState.java), view) fun setViewGoneFor( loadStates: List<Class<out LoadStateInterface>>, view: View) = setViewsGoneFor( loadStates, listOf(view)) fun setViewGoneFor( loadState: Class<out LoadStateInterface>, view: View) = setViewsGoneFor( listOf(loadState), listOf(view)) fun setViewGoneFor( loadState: KClass<out LoadStateInterface>, view: View) = setViewsGoneFor( listOf(loadState.java), listOf(view)) //endregion private fun setViewsVisibilityFor( loadStates: List<Class<out LoadStateInterface>>, views: List<View>, ifVisibility: Int, elseVisibility: Int): BaseLoadStateRenderer { forStates( loadStates, { views.forEach { it.visibility = ifVisibility } }, { views.forEach { it.visibility = elseVisibility } }) return this } }
5
Kotlin
30
249
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
22,262
SurfAndroidStandard
Apache License 2.0
matrix-sdk-android/src/androidTestRustCrypto/java/org/matrix/android/sdk/internal/database/CryptoSanityMigrationTest.kt
tchapgouv
340,329,238
false
null
/* * Copyright 2023 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.database import android.content.Context import androidx.test.platform.app.InstrumentationRegistry import io.mockk.spyk import io.realm.Realm import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.matrix.android.sdk.TestBuildVersionSdkIntProvider import org.matrix.android.sdk.api.securestorage.SecretStoringUtils import org.matrix.android.sdk.internal.crypto.RustEncryptionConfiguration import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreMigration import org.matrix.android.sdk.internal.crypto.store.db.RealmCryptoStoreModule import org.matrix.android.sdk.internal.crypto.store.db.RustMigrationInfoProvider import org.matrix.android.sdk.internal.util.time.Clock import org.matrix.olm.OlmManager import java.io.File import java.security.KeyStore class CryptoSanityMigrationTest { @get:Rule val configurationFactory = TestRealmConfigurationFactory() lateinit var context: Context var realm: Realm? = null @Before fun setUp() { // Ensure Olm is initialized OlmManager() context = InstrumentationRegistry.getInstrumentation().context } @After fun tearDown() { realm?.close() } private val keyStore = spyk(KeyStore.getInstance("AndroidKeyStore")).also { it.load(null) } @Test fun cryptoDatabaseShouldMigrateGracefully() { val realmName = "crypto_store_20.realm" val rustMigrationInfo = RustMigrationInfoProvider( File(configurationFactory.root, "test_rust"), RustEncryptionConfiguration( "foo", RealmKeysUtils( context, SecretStoringUtils(context, keyStore, TestBuildVersionSdkIntProvider(), false) ) ), ) val migration = RealmCryptoStoreMigration( object : Clock { override fun epochMillis(): Long { return 0L } }, rustMigrationInfo ) val realmConfiguration = configurationFactory.createConfiguration( realmName, "7b9a21a8a311e85d75b069a343c23fc952fc3fec5e0c83ecfa13f24b787479c487c3ed587db3dd1f5805d52041fc0ac246516e94b27ffa699ff928622e621aca", RealmCryptoStoreModule(), migration.schemaVersion, migration ) configurationFactory.copyRealmFromAssets(context, realmName, realmName) realm = Realm.getInstance(realmConfiguration) } }
4
null
6
9
786e66d1aceeb1928d43c720633151c7ec284448
3,292
tchap-android
Apache License 2.0
app/src/main/kotlin/com/epicdima/sfct/exsearch/parameters/SingleParameterItem.kt
EpicDima
286,760,945
false
null
package com.epicdima.sfct.exsearch.parameters import android.content.Context import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import com.epicdima.sfct.R import com.epicdima.sfct.core.usecases.ExsearchParams import com.epicdima.sfct.exsearch.Parameter import com.epicdima.sfct.exsearch.ParametersFragment import com.epicdima.sfct.exsearch.ParametersStorage import com.epicdima.sfct.utils.getEnumString import com.epicdima.sfct.utils.getEnumStrings /** * @author EpicDima */ class SingleParameterItem<T>( private val parameter: Parameter<T>, private val converter: (value: T, context: Context) -> String ) { val currentValue: MutableLiveData<T> = MutableLiveData(parameter.actualValue.value!!) fun isDefault() = (currentValue.value == parameter.defaultValue) fun reset() { currentValue.value = parameter.defaultValue } fun resetActual() { reset() parameter.reset() } fun setActualToCurrent() { if (currentValue.value != parameter.actualValue.value) { currentValue.value = parameter.actualValue.value } } fun setCurrentToActual() { if (parameter.actualValue.value != currentValue.value) { parameter.actualValue.value = currentValue.value } } fun convertToStringOfSelected(context: Context) = converter(currentValue.value!!, context) } fun ParametersStorage.createExamsParameter() = SingleParameterItem(exams) { value, context -> if (value.isEmpty()) { context.getString(R.string.exam_empty) } else { context.getEnumStrings(ExsearchParams.Exam::class.java) .filter { value.contains(it.key) } .values.joinToString(", ") } } fun ParametersStorage.createRegionParameter() = SingleParameterItem(region) { value, context -> context.getEnumString(value) } fun ParametersStorage.createTeachFormParameter() = SingleParameterItem(teachForm) { value, context -> context.getEnumString(value) } fun ParametersStorage.createTypeOfInstitutionParameter() = SingleParameterItem(typeOfInstitution) { value, context -> context.getEnumString(value) } fun ParametersStorage.createPaymentFormParameter() = SingleParameterItem(paymentForm) { value, context -> context.getEnumString(value) } fun ParametersStorage.createRangeOfPointsParameter() = SingleParameterItem(rangeOfPoints) { value, context -> context.getEnumString(value) } fun ParametersStorage.createPointsParameter() = SingleParameterItem(points) { value, context -> if (value.isEmpty()) context.getString(R.string.points_unspecified) else value } fun ParametersStorage.createDormitoryParameter() = SingleParameterItem(dormitory) { value, context -> context.getEnumString(value) } fun <T> LifecycleOwner.observeParameter( context: Context, singleParameterItem: SingleParameterItem<T>, parameterViewItem: ParametersFragment.ParameterViewItem, callback: (() -> Unit)? = null ) { singleParameterItem.currentValue.observe(this) { if (callback != null) { callback() } parameterViewItem.apply { singleParameterItem.apply { selected.set(convertToStringOfSelected(context)) defaultValue.set(isDefault()) } } } }
0
Kotlin
0
1
b6db1270bce60c4802a7c79705ee18e326a2b222
3,390
SFCT
Apache License 2.0
src/main/java/me/shadowalzazel/mcodyssey/mobs/hostile/SculkCrawler.kt
ShadowAlzazel
511,383,377
false
null
package me.shadowalzazel.mcodyssey.mobs.hostile import me.shadowalzazel.mcodyssey.mobs.base.OdysseyMob import org.bukkit.entity.EntityType object SculkCrawler: OdysseyMob("Sculk Crawler", EntityType.SPIDER, 10.0) { // TODO: Add }
0
Kotlin
0
3
f12c2f2877584cb0e2487e4607f4743acfea8874
237
MinecraftOdyssey
MIT License
app/src/main/kotlin/uz/mahmudxon/currency/ui/currencyDetails/CurrencyDetailsViewModel.kt
Mahmudxon
314,833,106
false
{"Kotlin": 132588}
package uz.mahmudxon.currency.ui.currencyDetails import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uz.mahmudxon.currency.data.repo.GetCommercialBankData import uz.mahmudxon.currency.data.repo.GetCurrencyChart import uz.mahmudxon.currency.model.Currency import uz.mahmudxon.currency.util.moneyStringToDouble import uz.mahmudxon.currency.util.toMoneyString import javax.inject.Inject @HiltViewModel class CurrencyDetailsViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val getCurrencyChart: GetCurrencyChart, private val getCommercialBankData: GetCommercialBankData ) : ViewModel() { private val _state = MutableStateFlow( CurrencyDetailsState( currency = savedStateHandle.get<Currency>("currency"), localValue = "${savedStateHandle.get<Currency>("currency")?.rate?.toMoneyString()}", foreignValue = "1" ) ) val state = _state.asStateFlow() init { getData() } private fun getData() { getCurrencyChart.execute(_state.value.currency!!.code) .onEach { _state.value = _state.value.copy(isLoading = it.isLoading) it.data?.let { data -> _state.value = _state.value.copy( chart = data.takeLast(365) ) } _state.value = _state.value.copy( error = if (it.error == null) -1 else 1 ) } .launchIn(CoroutineScope(IO)) if (_state.value.currency?.code == "USD" || _state.value.currency?.code == "EUR" || _state.value.currency?.code == "RUB") { _state.value = _state.value.copy(sellingAvailable = true) getCommercialBankData.execute(_state.value.currency!!.code) .onEach { _state.value = _state.value.copy( sellingLoading = it.isLoading ) it.data?.let { _state.value = _state.value.copy( bankPrices = it.sortedBy { it.bank.name } ) } } .launchIn(CoroutineScope(IO)) } } fun onEvent(event: CurrencyDetailsEvent) { when (event) { is CurrencyDetailsEvent.Refresh -> { getData() } is CurrencyDetailsEvent.SwitchCurrency -> { _state.value = _state.value.copy( isForeignCurrencyTop = !_state.value.isForeignCurrencyTop ) } is CurrencyDetailsEvent.ForeignCurrencyInput -> { val d = _state.value.currency?.rate ?: 1.0 val v = event.value.moneyStringToDouble() val localValue = v * d _state.value = _state.value.copy( foreignValue = if (event.value.isEmpty()) "" else v.toMoneyString(), localValue = localValue.toMoneyString() ) } is CurrencyDetailsEvent.LocalCurrencyInput -> { val d = _state.value.currency?.rate ?: 1.0 val v = event.value.moneyStringToDouble() val foreignValue = v / d _state.value = _state.value.copy( localValue = if (event.value.isEmpty()) "" else v.toMoneyString(), foreignValue = foreignValue.toMoneyString() ) } } } }
0
Kotlin
1
3
04268b92eab88dc5e92b80d15240c843a4ce8473
3,893
Currency
Apache License 1.1
app/src/main/java/com/trilema/doctrinalang/ui/time/TimeFragment.kt
jimmycw74
298,804,278
false
null
package com.trilema.doctrinalang.ui.time import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.TransitionDrawable import android.os.Bundle import android.speech.tts.TextToSpeech import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.fragment.app.Fragment import com.trilema.doctrinalang.R import com.trilema.doctrinalang.support.Tagarela import com.trilema.doctrinalang.support.Tagarela.tts import java.util.* class TimeFragment : Fragment() { private var textView: TextView? = null private var textTip: TextView? = null private var btnNumbersStart: ImageView? = null private var btnZero: Button? = null private var btnUm: Button? = null private var btnDois: Button? = null private var btnTres: Button? = null private var btnQuatro: Button? = null private var btnCinco: Button? = null private var btnSeis: Button? = null private var btnSete: Button? = null private var btnOito: Button? = null private var btnNove: Button? = null private var btnZeroZero: Button? = null private var btnDoisPontos: Button? = null private var btnVolta: ImageView? = null private var btnRepete: ImageView? = null private var btnHelp: ImageView? = null private var linMinMax: LinearLayout? = null private var magicHour = 0 private var magicMinute = 0 private val rnd = Random() private val filaHour: Queue<Int> = LinkedList() private val filaMinute: Queue<Int> = LinkedList() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater.inflate(R.layout.fragment_home, container, false) textView = root.findViewById(R.id.text_home) textTip = root.findViewById(R.id.txtTip) btnNumbersStart = root.findViewById(R.id.btnNumbersStart) btnZero = root.findViewById(R.id.btnZero) btnUm = root.findViewById(R.id.btnUm) btnDois = root.findViewById(R.id.btnDois) btnTres = root.findViewById(R.id.btnTres) btnQuatro = root.findViewById(R.id.btnQuatro) btnCinco = root.findViewById(R.id.btnCinco) btnSeis = root.findViewById(R.id.btnSeis) btnSete = root.findViewById(R.id.btnSete) btnOito = root.findViewById(R.id.btnOito) btnNove = root.findViewById(R.id.btnNove) btnVolta = root.findViewById(R.id.btnVolta) btnRepete = root.findViewById(R.id.btnRepete) btnHelp = root.findViewById(R.id.btnHelp) btnZeroZero = root.findViewById(R.id.btnZeroZero) btnDoisPontos = root.findViewById(R.id.btnDoisPontos) linMinMax = root.findViewById(R.id.linMinMax) linMinMax?.setVisibility(View.GONE) btnRepete?.setEnabled(false) btnVolta?.setEnabled(false) btnHelp?.setEnabled(false) btnZero?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnUm?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnDois?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnTres?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnQuatro?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnCinco?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnSeis?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnSete?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnOito?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnNove?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnZeroZero?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnDoisPontos?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnVolta?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) textView?.setText("") }) btnRepete?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) Tagarela.sayIt("$magicHour:$magicMinute") }) btnHelp?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) textTip?.setText(String.format("%02d:%02d", magicHour, magicMinute)) tipAnswer() }) btnNumbersStart?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) ligaTudo() newRound() }) fadeBackgroundNumber(btnNumbersStart) return root } override fun onDestroy() { if (tts != null) { tts?.stop() } super.onDestroy() } private fun numberPressed(v: View) { fadeBackgroundNumber(v) val number = v.tag.toString().toInt() if (number == -100) { val base = textView!!.text.toString() textView!!.text = base + "00" } else if (number == -101) { var hora = textView!!.text.toString() val horaInt: Int horaInt = try { hora.toInt() } catch (e: Exception) { 0 } hora = String.format(Locale.ENGLISH, "%02d", horaInt) textView!!.text = "$hora:" } else { val base = textView!!.text.toString() textView!!.text = base + number.toString() } val horaDigitada = textView!!.text.toString() val horaAtual = String.format(Locale.ENGLISH, "%02d:%02d", magicHour, magicMinute) if (horaDigitada == horaAtual) { textView!!.text = "" textTip!!.text = String.format(Locale.ENGLISH, "%02d:%02d", magicHour, magicMinute) correctAnswer() newRound() } } private fun newRound() { if (filaHour.size > 6) filaHour.poll() if (filaMinute.size > 30 ) filaMinute.poll() do { magicHour = rnd.nextInt(24) } while (filaHour.contains(magicHour)) //to avoid repeated hour do { magicMinute = rnd.nextInt(60) } while (filaMinute.contains(magicMinute)) // to avoid repeated minute filaHour.add(magicHour) filaMinute.add(magicMinute) Tagarela.sayTime(magicHour,magicMinute) } private fun correctAnswer() { val colorDrawables = arrayOf(ColorDrawable(Color.GREEN), ColorDrawable(resources.getColor(R.color.fundoPadrao))) fadeBackground(colorDrawables) fadeTextTip() } private fun tipAnswer() { val colorDrawables = arrayOf(ColorDrawable(Color.YELLOW), ColorDrawable(resources.getColor(R.color.fundoPadrao))) fadeBackground(colorDrawables) fadeTextTip() } private fun fadeBackground(colorDrawables: Array<ColorDrawable>) { val transitionDrawable = TransitionDrawable(colorDrawables) textTip!!.background = transitionDrawable transitionDrawable.startTransition(1000) } private fun fadeTextTip() { val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), Color.BLACK, resources.getColor(R.color.fundoPadrao)) colorAnimation.addUpdateListener { animator -> textTip!!.setTextColor((animator.animatedValue as Int)) } colorAnimation.duration = 2000 colorAnimation.start() } private fun fadeBackgroundNumber(v: View?) { val colorDrawables = arrayOf(ColorDrawable(resources.getColor(R.color.fundoForte)), ColorDrawable(resources.getColor(R.color.fundoPadrao))) val transitionDrawable = TransitionDrawable(colorDrawables) v!!.background = transitionDrawable transitionDrawable.startTransition(500) } private fun ligaTudo() { btnZero!!.isEnabled = true btnUm!!.isEnabled = true btnDois!!.isEnabled = true btnTres!!.isEnabled = true btnQuatro!!.isEnabled = true btnCinco!!.isEnabled = true btnSeis!!.isEnabled = true btnSete!!.isEnabled = true btnOito!!.isEnabled = true btnNove!!.isEnabled = true btnZeroZero!!.isEnabled = true btnDoisPontos!!.isEnabled = true btnVolta!!.isEnabled = true btnRepete!!.isEnabled = true btnHelp!!.isEnabled = true } }
1
null
1
1
b93972793ee36e927c21db60e61a185da810f1d2
8,782
DoctrinaLang
Apache License 2.0
app/src/main/java/com/trilema/doctrinalang/ui/time/TimeFragment.kt
jimmycw74
298,804,278
false
null
package com.trilema.doctrinalang.ui.time import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.TransitionDrawable import android.os.Bundle import android.speech.tts.TextToSpeech import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.fragment.app.Fragment import com.trilema.doctrinalang.R import com.trilema.doctrinalang.support.Tagarela import com.trilema.doctrinalang.support.Tagarela.tts import java.util.* class TimeFragment : Fragment() { private var textView: TextView? = null private var textTip: TextView? = null private var btnNumbersStart: ImageView? = null private var btnZero: Button? = null private var btnUm: Button? = null private var btnDois: Button? = null private var btnTres: Button? = null private var btnQuatro: Button? = null private var btnCinco: Button? = null private var btnSeis: Button? = null private var btnSete: Button? = null private var btnOito: Button? = null private var btnNove: Button? = null private var btnZeroZero: Button? = null private var btnDoisPontos: Button? = null private var btnVolta: ImageView? = null private var btnRepete: ImageView? = null private var btnHelp: ImageView? = null private var linMinMax: LinearLayout? = null private var magicHour = 0 private var magicMinute = 0 private val rnd = Random() private val filaHour: Queue<Int> = LinkedList() private val filaMinute: Queue<Int> = LinkedList() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater.inflate(R.layout.fragment_home, container, false) textView = root.findViewById(R.id.text_home) textTip = root.findViewById(R.id.txtTip) btnNumbersStart = root.findViewById(R.id.btnNumbersStart) btnZero = root.findViewById(R.id.btnZero) btnUm = root.findViewById(R.id.btnUm) btnDois = root.findViewById(R.id.btnDois) btnTres = root.findViewById(R.id.btnTres) btnQuatro = root.findViewById(R.id.btnQuatro) btnCinco = root.findViewById(R.id.btnCinco) btnSeis = root.findViewById(R.id.btnSeis) btnSete = root.findViewById(R.id.btnSete) btnOito = root.findViewById(R.id.btnOito) btnNove = root.findViewById(R.id.btnNove) btnVolta = root.findViewById(R.id.btnVolta) btnRepete = root.findViewById(R.id.btnRepete) btnHelp = root.findViewById(R.id.btnHelp) btnZeroZero = root.findViewById(R.id.btnZeroZero) btnDoisPontos = root.findViewById(R.id.btnDoisPontos) linMinMax = root.findViewById(R.id.linMinMax) linMinMax?.setVisibility(View.GONE) btnRepete?.setEnabled(false) btnVolta?.setEnabled(false) btnHelp?.setEnabled(false) btnZero?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnUm?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnDois?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnTres?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnQuatro?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnCinco?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnSeis?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnSete?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnOito?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnNove?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnZeroZero?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnDoisPontos?.setOnClickListener(View.OnClickListener { view -> numberPressed(view) }) btnVolta?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) textView?.setText("") }) btnRepete?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) Tagarela.sayIt("$magicHour:$magicMinute") }) btnHelp?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) textTip?.setText(String.format("%02d:%02d", magicHour, magicMinute)) tipAnswer() }) btnNumbersStart?.setOnClickListener(View.OnClickListener { view -> fadeBackgroundNumber(view) ligaTudo() newRound() }) fadeBackgroundNumber(btnNumbersStart) return root } override fun onDestroy() { if (tts != null) { tts?.stop() } super.onDestroy() } private fun numberPressed(v: View) { fadeBackgroundNumber(v) val number = v.tag.toString().toInt() if (number == -100) { val base = textView!!.text.toString() textView!!.text = base + "00" } else if (number == -101) { var hora = textView!!.text.toString() val horaInt: Int horaInt = try { hora.toInt() } catch (e: Exception) { 0 } hora = String.format(Locale.ENGLISH, "%02d", horaInt) textView!!.text = "$hora:" } else { val base = textView!!.text.toString() textView!!.text = base + number.toString() } val horaDigitada = textView!!.text.toString() val horaAtual = String.format(Locale.ENGLISH, "%02d:%02d", magicHour, magicMinute) if (horaDigitada == horaAtual) { textView!!.text = "" textTip!!.text = String.format(Locale.ENGLISH, "%02d:%02d", magicHour, magicMinute) correctAnswer() newRound() } } private fun newRound() { if (filaHour.size > 6) filaHour.poll() if (filaMinute.size > 30 ) filaMinute.poll() do { magicHour = rnd.nextInt(24) } while (filaHour.contains(magicHour)) //to avoid repeated hour do { magicMinute = rnd.nextInt(60) } while (filaMinute.contains(magicMinute)) // to avoid repeated minute filaHour.add(magicHour) filaMinute.add(magicMinute) Tagarela.sayTime(magicHour,magicMinute) } private fun correctAnswer() { val colorDrawables = arrayOf(ColorDrawable(Color.GREEN), ColorDrawable(resources.getColor(R.color.fundoPadrao))) fadeBackground(colorDrawables) fadeTextTip() } private fun tipAnswer() { val colorDrawables = arrayOf(ColorDrawable(Color.YELLOW), ColorDrawable(resources.getColor(R.color.fundoPadrao))) fadeBackground(colorDrawables) fadeTextTip() } private fun fadeBackground(colorDrawables: Array<ColorDrawable>) { val transitionDrawable = TransitionDrawable(colorDrawables) textTip!!.background = transitionDrawable transitionDrawable.startTransition(1000) } private fun fadeTextTip() { val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), Color.BLACK, resources.getColor(R.color.fundoPadrao)) colorAnimation.addUpdateListener { animator -> textTip!!.setTextColor((animator.animatedValue as Int)) } colorAnimation.duration = 2000 colorAnimation.start() } private fun fadeBackgroundNumber(v: View?) { val colorDrawables = arrayOf(ColorDrawable(resources.getColor(R.color.fundoForte)), ColorDrawable(resources.getColor(R.color.fundoPadrao))) val transitionDrawable = TransitionDrawable(colorDrawables) v!!.background = transitionDrawable transitionDrawable.startTransition(500) } private fun ligaTudo() { btnZero!!.isEnabled = true btnUm!!.isEnabled = true btnDois!!.isEnabled = true btnTres!!.isEnabled = true btnQuatro!!.isEnabled = true btnCinco!!.isEnabled = true btnSeis!!.isEnabled = true btnSete!!.isEnabled = true btnOito!!.isEnabled = true btnNove!!.isEnabled = true btnZeroZero!!.isEnabled = true btnDoisPontos!!.isEnabled = true btnVolta!!.isEnabled = true btnRepete!!.isEnabled = true btnHelp!!.isEnabled = true } }
1
null
1
1
b93972793ee36e927c21db60e61a185da810f1d2
8,782
DoctrinaLang
Apache License 2.0
src/main/kotlin/de/debuglevel/bragi/chapter/AddChapterRequest.kt
debuglevel
282,505,005
false
null
package de.debuglevel.bragi.chapter import de.debuglevel.bragi.entity.AddEntityRequest data class AddChapterRequest( var title: String ) : AddEntityRequest<Chapter> { override fun toEntity(): Chapter { return Chapter( id = null, title = this.title, content = "", summary = "", notes = "" ) } }
13
Kotlin
0
0
7ee6040b8280ea44c780ae6842aedc464b6278bf
383
bragi
The Unlicense
dd-sdk-android/src/test/kotlin/com/datadog/android/log/internal/logger/DatadogLogHandlerTest.kt
nicholas-devlin
237,227,700
true
{"Kotlin": 655359}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-2019 Datadog, Inc. */ package com.datadog.android.log.internal.logger import com.datadog.android.core.internal.data.Writer import com.datadog.android.core.internal.time.TimeProvider import com.datadog.android.log.assertj.LogAssert.Companion.assertThat import com.datadog.android.log.forge.Configurator import com.datadog.android.log.internal.domain.Log import com.datadog.android.log.internal.net.NetworkInfo import com.datadog.android.log.internal.net.NetworkInfoProvider import com.datadog.android.log.internal.user.UserInfo import com.datadog.android.log.internal.user.UserInfoProvider import com.datadog.tools.unit.setFieldValue import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import fr.xgouchet.elmyr.Forge import fr.xgouchet.elmyr.annotation.Forgery import fr.xgouchet.elmyr.junit5.ForgeConfiguration import fr.xgouchet.elmyr.junit5.ForgeExtension import fr.xgouchet.elmyr.jvm.ext.aTimestamp import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.Extensions import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.junit.jupiter.MockitoSettings import org.mockito.quality.Strictness @Extensions( ExtendWith(MockitoExtension::class), ExtendWith(ForgeExtension::class) ) @MockitoSettings(strictness = Strictness.LENIENT) @ForgeConfiguration(Configurator::class) internal class DatadogLogHandlerTest { lateinit var testedHandler: LogHandler lateinit var fakeServiceName: String lateinit var fakeLoggerName: String lateinit var fakeMessage: String lateinit var fakeTags: Set<String> lateinit var fakeAttributes: Map<String, Any?> var fakeServerDate: Long = 0L var fakeLevel: Int = 0 @Forgery lateinit var fakeThrowable: Throwable @Forgery lateinit var fakeNetworkInfo: NetworkInfo @Forgery lateinit var fakeUserInfo: UserInfo @Mock lateinit var mockWriter: Writer<Log> @Mock lateinit var mockNetworkInfoProvider: NetworkInfoProvider @Mock lateinit var mockTimeProvider: TimeProvider @Mock lateinit var mockUserInfoProvider: UserInfoProvider @BeforeEach fun `set up`(forge: Forge) { fakeServiceName = forge.anAlphabeticalString() fakeLoggerName = forge.anAlphabeticalString() fakeMessage = forge.anAlphabeticalString() fakeServerDate = forge.aTimestamp() fakeLevel = forge.anInt(2, 8) fakeAttributes = forge.aMap { anAlphabeticalString() to anInt() } fakeTags = forge.aList { anAlphabeticalString() }.toSet() whenever(mockTimeProvider.getServerTimestamp()) doReturn fakeServerDate whenever(mockNetworkInfoProvider.getLatestNetworkInfo()) doReturn fakeNetworkInfo whenever(mockUserInfoProvider.getUserInfo()) doReturn fakeUserInfo testedHandler = DatadogLogHandler( fakeServiceName, fakeLoggerName, mockWriter, mockNetworkInfoProvider, mockTimeProvider, mockUserInfoProvider ) } @Test fun `forward log to LogWriter`() { testedHandler.handleLog( fakeLevel, fakeMessage, fakeThrowable, fakeAttributes, fakeTags ) argumentCaptor<Log>().apply { verify(mockWriter).write(capture()) assertThat(lastValue) .hasServiceName(fakeServiceName) .hasLoggerName(fakeLoggerName) .hasThreadName(Thread.currentThread().name) .hasLevel(fakeLevel) .hasMessage(fakeMessage) .hasTimestamp(fakeServerDate) .hasNetworkInfo(fakeNetworkInfo) .hasUserInfo(fakeUserInfo) .hasAttributes(fakeAttributes) .hasTags(fakeTags) } } @Test fun `forward log to LogWriter on background thread`(forge: Forge) { val threadName = forge.anAlphabeticalString() val countDownLatch = CountDownLatch(1) val thread = Thread({ testedHandler.handleLog( fakeLevel, fakeMessage, fakeThrowable, fakeAttributes, fakeTags ) countDownLatch.countDown() }, threadName) thread.start() countDownLatch.await(1, TimeUnit.SECONDS) argumentCaptor<Log>().apply { verify(mockWriter).write(capture()) assertThat(lastValue) .hasServiceName(fakeServiceName) .hasLoggerName(fakeLoggerName) .hasThreadName(threadName) .hasLevel(fakeLevel) .hasMessage(fakeMessage) .hasTimestamp(fakeServerDate) .hasNetworkInfo(fakeNetworkInfo) .hasUserInfo(fakeUserInfo) .hasAttributes(fakeAttributes) .hasTags(fakeTags) } } @Test fun `forward log to LogWriter without network info`() { testedHandler.setFieldValue("networkInfoProvider", null as NetworkInfoProvider?) testedHandler.handleLog( fakeLevel, fakeMessage, fakeThrowable, fakeAttributes, fakeTags ) argumentCaptor<Log>().apply { verify(mockWriter).write(capture()) assertThat(lastValue) .hasServiceName(fakeServiceName) .hasLoggerName(fakeLoggerName) .hasThreadName(Thread.currentThread().name) .hasLevel(fakeLevel) .hasMessage(fakeMessage) .hasTimestamp(fakeServerDate) .hasNetworkInfo(null) .hasUserInfo(fakeUserInfo) .hasAttributes(fakeAttributes) .hasTags(fakeTags) } } @Test fun `forward minimal log to LogWriter`() { testedHandler.setFieldValue("networkInfoProvider", null as NetworkInfoProvider?) testedHandler.handleLog( fakeLevel, fakeMessage, null, emptyMap(), emptySet() ) argumentCaptor<Log>().apply { verify(mockWriter).write(capture()) assertThat(lastValue) .hasServiceName(fakeServiceName) .hasLoggerName(fakeLoggerName) .hasThreadName(Thread.currentThread().name) .hasLevel(fakeLevel) .hasMessage(fakeMessage) .hasTimestamp(fakeServerDate) .hasNetworkInfo(null) .hasUserInfo(fakeUserInfo) .hasAttributes(emptyMap()) .hasTags(emptyList()) } } }
0
null
0
0
827e05b864def3e1573a1935fd59bddf22449215
7,271
dd-sdk-android
Apache License 2.0
Matcheap/app/src/main/java/com/sandy/seoul_matcheap/ui/more/bookmark/BookmarkViewModel.kt
SANDY-9
677,761,441
false
{"Kotlin": 220354, "Java": 2279}
package com.sandy.seoul_matcheap.ui.more.bookmark import androidx.lifecycle.* import com.sandy.seoul_matcheap.data.store.dao.BookmarkedStore import com.sandy.seoul_matcheap.data.store.repository.BookmarkRepository import com.sandy.seoul_matcheap.util.constants.ConnectState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject /** * @author SANDY * @email nnal0256@naver.com * @created 2023-05-05 * @desc */ @HiltViewModel class BookmarkViewModel @Inject constructor(private val bookmarkRepository: BookmarkRepository) : ViewModel() { private val _loadingState = MutableLiveData(ConnectState.NONE) val loadingState : LiveData<ConnectState> = _loadingState private fun setLoadingState(state: ConnectState) { _loadingState.postValue(state) } val bookmarkList: LiveData<List<BookmarkedStore>> by lazy { bookmarkRepository.downloadBookmarkList() } private val code = MutableLiveData<String>() val bookmarkCount = code.switchMap { bookmarkRepository.downloadBookmarkCount(it) } fun updateBookmarkCount(code: String) { this.code.value = code } fun updateBookmark(id: String, code: String, bookmarked: Boolean) = CoroutineScope(Dispatchers.IO).launch { setLoadingState(ConnectState.ING) when { bookmarked -> addBookmark(id, code) else -> deleteBookmark(id) } } private suspend fun addBookmark(id: String, code: String) { val result = bookmarkRepository.addBookmark(id, code) setLoadingState(if(result) ConnectState.SUCCESS else ConnectState.FAIL) } private suspend fun deleteBookmark(id: String) { bookmarkRepository.deleteBookmark(id) } }
0
Kotlin
0
0
e3b577e7f17a10b2e21bad163e9336fb354f8e1e
1,843
Project_SeoulMatcheap2.0
Apache License 2.0
app/src/main/java/org/ballistic/dreamjournalai/user_authentication/presentation/signup_screen/SignInScreen.kt
ErickSorto
546,852,272
false
null
package org.ballistic.dreamjournalai.user_authentication.presentation.signup_screen
0
Kotlin
0
2
150b630a9e74ca3b05d021ca0e8624c65cf14e8a
85
Dream-Journal-AI
MIT License
src/test/kotlin/org/incava/rando/RandIntGeneratorTest.kt
jpace
483,382,354
false
{"Kotlin": 259801, "Ruby": 674}
package org.incava.rando import org.incava.ikdk.io.Console import org.incava.rando.DistributionAssert.assertVariance import org.junit.jupiter.api.Test fun MutableMap<Int, Int>.add(number: Int) { this[number] = (this[number] ?: 0) + 1 } class RandIntGeneratorTest { @Test fun multiRandDist() { multiRandDist { it.nextInts() } } @Test fun multiRandDist2() { multiRandDist { it.nextInts2() } } @Test fun multiRandDist3() { multiRandDist { it.nextInts3() } } @Test fun nextInts4Dist() { multiRandDist { it.nextInts4().toList() } } @Test fun nextInts5Dist() { multiRandDist { it.nextInts5().toList() } } private fun multiRandDist(verbose: Boolean = false, blk: (RandIntGenerator) -> List<Int>) { val generated = mutableMapOf<Int, Int>() val gen = RandIntGenerator() repeat(10_000_000) { val nums = blk(gen) nums.forEach { generated.add(it) } } if (verbose) { generated.toSortedMap().forEach { (num, count) -> Console.info("$num", count) } } assertVariance(generated, 100, 1.2) } @Test fun toNumbers() { val gen = RandIntGenerator() repeat(100) { val x = 900_000 + (113 * it) val nums = gen.toNumbersList(x) Console.info("$it $x", nums.toList()) } } }
0
Kotlin
0
0
e3df114f0d3fadf746b78e54f3d3c97cb19b5b7f
1,486
mmonkeys
MIT License
app/src/main/java/com/tegar/eats/ui/components/ListSection.kt
tegar97
714,543,837
false
{"Kotlin": 151922}
package com.tegar.eats.ui.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tegar.eats.ui.theme.ManropeFamiliy @Composable fun ListSection( title: String, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Column(modifier = modifier) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp) ) { SectionText(title) Spacer(modifier = Modifier.weight(1.0f)) Text( text = "See More", style = MaterialTheme.typography.headlineSmall.copy( fontSize = 12.sp, color = Color(0xff8C8C8C) ), ) } Spacer(modifier = Modifier.height(12.dp)) content() } } @Composable fun SectionText( title: String, modifier: Modifier = Modifier ) { Text( text = title, style = MaterialTheme.typography.displayMedium.copy( fontSize = 20.sp, fontFamily = ManropeFamiliy, ), modifier = modifier ) }
0
Kotlin
0
0
b2b191a37d46f64d228f59c31334e9c776aa4f0a
1,746
eats-app
MIT License
intellij-plugin-verifier/verifier-cli/src/main/java/com/jetbrains/pluginverifier/PluginVerifierMain.kt
JetBrains
3,686,654
false
null
/* * Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.pluginverifier import com.jetbrains.plugin.structure.base.utils.createDir import com.jetbrains.plugin.structure.base.utils.forceDeleteIfExists import com.jetbrains.plugin.structure.base.utils.formatDuration import com.jetbrains.pluginverifier.PluginVerifierMain.commandRunners import com.jetbrains.pluginverifier.PluginVerifierMain.main import com.jetbrains.pluginverifier.options.CmdOpts import com.jetbrains.pluginverifier.options.OptionsParser import com.jetbrains.pluginverifier.output.OutputOptions import com.jetbrains.pluginverifier.plugin.PluginDetailsProviderImpl import com.jetbrains.pluginverifier.plugin.PluginFilesBank import com.jetbrains.pluginverifier.plugin.SizeLimitedPluginDetailsCache import com.jetbrains.pluginverifier.reporting.DirectoryBasedPluginVerificationReportage import com.jetbrains.pluginverifier.reporting.LoggingPluginVerificationReportageAggregator import com.jetbrains.pluginverifier.reporting.PluginVerificationReportage import com.jetbrains.pluginverifier.repository.cleanup.DiskSpaceSetting import com.jetbrains.pluginverifier.repository.cleanup.SpaceAmount import com.jetbrains.pluginverifier.repository.cleanup.SpaceUnit import com.jetbrains.pluginverifier.repository.repositories.local.LocalPluginRepositoryFactory import com.jetbrains.pluginverifier.repository.repositories.marketplace.MarketplaceRepository import com.jetbrains.pluginverifier.tasks.CommandRunner import com.jetbrains.pluginverifier.tasks.checkIde.CheckIdeRunner import com.jetbrains.pluginverifier.tasks.checkPlugin.CheckPluginRunner import com.jetbrains.pluginverifier.tasks.checkPluginApi.CheckPluginApiRunner import com.jetbrains.pluginverifier.tasks.checkTrunkApi.CheckTrunkApiRunner import com.jetbrains.pluginverifier.tasks.processAllPlugins.ProcessAllPluginsCommand import com.jetbrains.pluginverifier.tasks.profiling.MeasuredResult import com.jetbrains.pluginverifier.tasks.profiling.measurePluginVerification import com.sampullara.cli.Args import org.apache.commons.io.FileUtils import java.net.URL import java.nio.file.Path import java.nio.file.Paths import kotlin.system.exitProcess /** * The plugin verifier CLI entry point declaring the [main]. * The available commands are [commandRunners]. */ object PluginVerifierMain { private val commandRunners: List<CommandRunner> = listOf( CheckPluginRunner(), CheckIdeRunner(), CheckTrunkApiRunner(), CheckPluginApiRunner(), ProcessAllPluginsCommand() ) private val pluginVerifierVersion: String by lazy { val versionTxtUrl = PluginVerifierMain::class.java.getResource("/META-INF/intellij-plugin-verifier-version.txt") versionTxtUrl ?: return@lazy "<unknown>" versionTxtUrl.readText() } private val verifierHomeDirectory: Path by lazy { val verifierHomeDir = System.getProperty("plugin.verifier.home.dir") if (verifierHomeDir != null) { Paths.get(verifierHomeDir) } else { val userHome = System.getProperty("user.home") if (userHome != null) { Paths.get(userHome, ".pluginVerifier") } else { FileUtils.getTempDirectory().toPath().resolve(".pluginVerifier") } } } private val pluginRepositoryUrl: String by lazy { System.getProperty("plugin.repository.url")?.trimEnd('/') ?: "https://plugins.jetbrains.com" } private val downloadDirectory: Path = verifierHomeDirectory.resolve("loaded-plugins").createDir() private fun getPluginsExtractDirectory(): Path { val extractDirectory = verifierHomeDirectory.resolve("extracted-plugins").createDir() extractDirectory.forceDeleteIfExists() return extractDirectory } private val ideDownloadDirectory: Path = verifierHomeDirectory.resolve("ides").createDir() @JvmStatic fun main(args: Array<String>) { println("Starting the IntelliJ Plugin Verifier $pluginVerifierVersion") val opts = CmdOpts() var freeArgs = Args.parse(opts, args, false) if (freeArgs.isEmpty()) { System.err.println( "The command is not specified. Should be one of: " + commandRunners.joinToString { "'" + it.commandName + "'" } ) Args.usage(System.err, CmdOpts()) exitProcess(1) } val command = freeArgs[0] freeArgs = freeArgs.drop(1) val runner = findTaskRunner(command) val outputOptions = OptionsParser.parseOutputOptions(opts) val pluginRepository = if (opts.offlineMode) { LocalPluginRepositoryFactory.createLocalPluginRepository(downloadDirectory) } else { MarketplaceRepository(URL(pluginRepositoryUrl)) } val pluginDownloadDirDiskSpaceSetting = getDiskSpaceSetting("plugin.verifier.cache.dir.max.space", 5L * 1024) val pluginFilesBank = PluginFilesBank.create(pluginRepository, downloadDirectory, pluginDownloadDirDiskSpaceSetting) val pluginDetailsProvider = PluginDetailsProviderImpl(getPluginsExtractDirectory()) val reportageAggregator = LoggingPluginVerificationReportageAggregator() DirectoryBasedPluginVerificationReportage(reportageAggregator) { outputOptions.getTargetReportDirectory(it) }.use { reportage -> measurePluginVerification { val detailsCacheSize = System.getProperty("plugin.verifier.plugin.details.cache.size")?.toIntOrNull() ?: 32 val taskResult = SizeLimitedPluginDetailsCache(detailsCacheSize, pluginFilesBank, pluginDetailsProvider).use { pluginDetailsCache -> runner.getParametersBuilder( pluginRepository, pluginDetailsCache, reportage ).build(opts, freeArgs).use { parameters -> reportage.logVerificationStage("Task ${runner.commandName} parameters:\n${parameters.presentableText}") parameters .createTask() .execute(reportage, pluginDetailsCache) } } taskResult }.run { val taskResultsPrinter = taskResult.createTaskResultsPrinter(pluginRepository) taskResultsPrinter.printResults(taskResult, outputOptions) reportage.reportDownloadStatistics(outputOptions, pluginFilesBank) reportageAggregator.handleAggregatedReportage() reportage.reportVerificationDuration(this) } } } private fun PluginVerificationReportage.reportDownloadStatistics(outputOptions: OutputOptions, pluginFilesBank: PluginFilesBank) { val downloadStatistics = pluginFilesBank.downloadStatistics val totalSpaceUsed = pluginFilesBank.getAvailablePluginFiles().fold(SpaceAmount.ZERO_SPACE) { acc, availableFile -> acc + availableFile.resourceInfo.weight.spaceAmount } val totalDownloadedAmount = downloadStatistics.getTotalDownloadedAmount() val totalDownloadDuration = downloadStatistics.getTotalAstronomicalDownloadDuration() logVerificationStage("Total time spent downloading plugins and their dependencies: ${totalDownloadDuration.formatDuration()}") logVerificationStage("Total amount of plugins and dependencies downloaded: ${totalDownloadedAmount.presentableAmount()}") logVerificationStage("Total amount of space used for plugins and dependencies: ${totalSpaceUsed.presentableAmount()}") if (outputOptions.teamCityLog != null) { outputOptions.teamCityLog.buildStatisticValue("intellij.plugin.verifier.downloading.time.ms", totalDownloadDuration.toMillis()) outputOptions.teamCityLog.buildStatisticValue("intellij.plugin.verifier.downloading.amount.bytes", totalDownloadedAmount.to(SpaceUnit.BYTE).toLong()) outputOptions.teamCityLog.buildStatisticValue("intellij.plugin.verifier.total.space.used", totalSpaceUsed.to(SpaceUnit.BYTE).toLong()) } } private fun PluginVerificationReportage.reportVerificationDuration(measuredResult: MeasuredResult) { logVerificationStage("Total time spent in plugin verification: ${measuredResult.duration.formatDuration()}") } private fun getDiskSpaceSetting(propertyName: String, defaultAmount: Long): DiskSpaceSetting { val property = System.getProperty(propertyName)?.toLong() ?: defaultAmount val megabytes = SpaceAmount.ofMegabytes(property) return DiskSpaceSetting(megabytes) } private fun findTaskRunner(command: String?) = commandRunners.find { command == it.commandName } ?: throw IllegalArgumentException("Unsupported command: $command. Supported commands: ${commandRunners.map { it.commandName }}") }
4
null
44
178
8be19a2c67854545d719fe56f3677122481b372f
8,519
intellij-plugin-verifier
Apache License 2.0
kotlin-typescript/src/jsMain/generated/typescript/TemplateHead.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Automatically generated - do not modify! package typescript sealed external interface TemplateHead : TemplateLiteralLikeNode, PseudoLiteralToken { override val kind: SyntaxKind.TemplateHead override val parent: TemplateHeadParent }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
245
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/hackathon/data/error/ServerError.kt
pixery-hallucinogen
183,740,920
false
{"Java": 657843, "Kotlin": 79353, "GLSL": 13202}
package com.hackathon.data.error import android.content.Context import com.hackathon.R class ServerError(val message: String) : BaseError() { override fun parseTitleAndMessage(context: Context): Pair<String, String> = Pair(context.getString(R.string.errorOccurred), message) }
1
null
1
1
649ff1e85f284770a33da40e8b9ed28cdde647bc
292
Android
MIT License
idea/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveExtensionPropertyToFile/after/a/main.kt
JakeWharton
99,388,807
true
null
package a import b.test class Test { fun foo() { test test = 0 } }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
93
kotlin
Apache License 2.0
app/src/main/kotlin/com/simplemobiletools/draw/activities/MainActivity.kt
zipzapdat
104,337,136
true
{"Kotlin": 35233}
package com.simplemobiletools.draw.activities import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.PorterDuff import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.FileProvider import android.view.Menu import android.view.MenuItem import android.widget.SeekBar import com.simplemobiletools.commons.dialogs.ColorPickerDialog import com.simplemobiletools.commons.dialogs.FilePickerDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.LICENSE_KOTLIN import com.simplemobiletools.commons.models.Release import com.simplemobiletools.draw.BuildConfig import com.simplemobiletools.draw.MyCanvas import com.simplemobiletools.draw.R import com.simplemobiletools.draw.Svg import com.simplemobiletools.draw.dialogs.SaveImageDialog import com.simplemobiletools.draw.extensions.config import com.simplemobiletools.draw.helpers.JPG import com.simplemobiletools.draw.helpers.PNG import com.simplemobiletools.draw.helpers.SVG import kotlinx.android.synthetic.main.activity_main.* import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream class MainActivity : SimpleActivity(), MyCanvas.PathsChangedListener { private val FOLDER_NAME = "images" private val FILE_NAME = "simple-draw.png" private val SAVE_IMAGE = 1 private val OPEN_FILE = 2 private val OPEN_FILE_INTENT = 3 private var curPath = "" private var color = 0 private var strokeWidth = 0f private var suggestedFileExtension = PNG private var openFileIntentPath = "" private var isEraserOn = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) my_canvas.setListener(this) stroke_width_bar.setOnSeekBarChangeListener(onStrokeWidthBarChangeListener) setBackgroundColor(config.canvasBackgroundColor) setColor(config.brushColor) strokeWidth = config.brushSize my_canvas.setStrokeWidth(strokeWidth) stroke_width_bar.progress = strokeWidth.toInt() color_picker.setOnClickListener { pickColor() } undo.setOnClickListener { my_canvas.undo() } eraser.setOnClickListener { eraserClicked() } storeStoragePaths() if (intent?.action == Intent.ACTION_VIEW && intent.data != null) { val path = intent.data!!.path if (hasWriteStoragePermission()) { openPath(path) } else { openFileIntentPath = path ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), OPEN_FILE_INTENT) } } checkWhatsNewDialog() } override fun onResume() { super.onResume() val isStrokeWidthBarEnabled = config.showBrushSize stroke_width_bar.beVisibleIf(isStrokeWidthBarEnabled) my_canvas.setIsStrokeWidthBarEnabled(isStrokeWidthBarEnabled) updateTextColors(main_holder) } override fun onPause() { super.onPause() config.brushColor = color config.brushSize = strokeWidth } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_save -> trySaveImage() R.id.menu_share -> shareImage() R.id.clear -> clearCanvas() R.id.open_file -> tryOpenFile() R.id.change_background -> changeBackgroundClicked() R.id.settings -> launchSettings() R.id.about -> launchAbout() else -> return super.onOptionsItemSelected(item) } return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { when (requestCode) { SAVE_IMAGE -> saveImage() OPEN_FILE -> openFile() OPEN_FILE_INTENT -> openPath(openFileIntentPath) } } else { toast(R.string.no_storage_permissions) } } private fun launchSettings() { startActivity(Intent(applicationContext, SettingsActivity::class.java)) } private fun launchAbout() { startAboutActivity(R.string.app_name, LICENSE_KOTLIN, BuildConfig.VERSION_NAME) } private fun tryOpenFile() { if (hasWriteStoragePermission()) { openFile() } else { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), OPEN_FILE) } } private fun openFile() { FilePickerDialog(this, curPath) { openPath(it) } } private fun openPath(path: String) { when { path.endsWith(".svg") -> { my_canvas.mBackgroundBitmap = null Svg.loadSvg(this, File(path), my_canvas) suggestedFileExtension = SVG } File(path).isImageSlow() -> { my_canvas.drawBitmap(this, path) suggestedFileExtension = JPG } else -> toast(R.string.invalid_file_format) } } private fun eraserClicked() { isEraserOn = !isEraserOn updateEraserState() } private fun updateEraserState() { eraser.setImageDrawable(resources.getDrawable(if (isEraserOn) R.drawable.ic_eraser_on else R.drawable.ic_eraser_off)) my_canvas.toggleEraser(isEraserOn) } private fun changeBackgroundClicked() { val oldColor = (my_canvas.background as ColorDrawable).color ColorPickerDialog(this, oldColor) { setBackgroundColor(it) config.canvasBackgroundColor = it } } private fun trySaveImage() { if (hasWriteStoragePermission()) { saveImage() } else { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), SAVE_IMAGE) } } private fun saveImage() { SaveImageDialog(this, suggestedFileExtension, curPath, my_canvas) { curPath = it } } private fun shareImage() { val shareTitle = resources.getString(R.string.share_via) val uri = getImageUri(my_canvas.getBitmap()) ?: return Intent().apply { action = Intent.ACTION_SEND addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) setDataAndType(uri, contentResolver.getType(uri)) putExtra(Intent.EXTRA_STREAM, uri) type = "image/*" startActivity(Intent.createChooser(this, shareTitle)) } } private fun getImageUri(bitmap: Bitmap): Uri? { val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 0, bytes) val folder = File(cacheDir, FOLDER_NAME) if (!folder.exists()) { if (!folder.mkdir()) return null } val file = File(folder, FILE_NAME) var fileOutputStream: FileOutputStream? = null try { fileOutputStream = FileOutputStream(file) fileOutputStream.write(bytes.toByteArray()) } catch (e: Exception) { } finally { fileOutputStream?.close() } return FileProvider.getUriForFile(this, "com.simplemobiletools.draw.fileprovider", file) } private fun clearCanvas() { my_canvas.clearCanvas() suggestedFileExtension = PNG } private fun pickColor() { ColorPickerDialog(this, color) { setColor(it) } } fun setBackgroundColor(pickedColor: Int) { undo.setColorFilter(pickedColor.getContrastColor(), PorterDuff.Mode.SRC_IN) eraser.setColorFilter(pickedColor.getContrastColor(), PorterDuff.Mode.SRC_IN) my_canvas.updateBackgroundColor(pickedColor) suggestedFileExtension = PNG } private fun setColor(pickedColor: Int) { color = pickedColor color_picker.setBackgroundColor(color) my_canvas.setColor(color) isEraserOn = false updateEraserState() } override fun pathsChanged(cnt: Int) { undo.beVisibleIf(cnt > 0) } private var onStrokeWidthBarChangeListener: SeekBar.OnSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { my_canvas.setStrokeWidth(progress.toFloat()) strokeWidth = progress.toFloat() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} } private fun checkWhatsNewDialog() { arrayListOf<Release>().apply { add(Release(18, R.string.release_18)) add(Release(20, R.string.release_20)) checkWhatsNew(this, BuildConfig.VERSION_CODE) } } }
0
Kotlin
0
0
b7c1da1f704a245f33226c9a21a2907e707f6b10
9,439
Simple-Draw
Apache License 2.0
app/src/main/java/eu/buney/ui/testdatabasetransaction/coroutines/CoroutineDispatchersModule.kt
yankeppey
527,255,812
false
null
package eu.buney.ui.testdatabasetransaction.coroutines import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton /** * @author <NAME> */ @InstallIn(SingletonComponent::class) @Module interface CoroutineDispatchersModule { @Binds @Singleton fun bindCoroutineDispatchers(coroutineDispatchers: AppCoroutineDispatchersImpl): AppCoroutineDispatchers }
0
Kotlin
0
1
d7a3761c2ce49277255ea3374ea93e4a93e4ba31
455
cautious-chainsaw
MIT License
ktor-server/ktor-server-netty/src/io/ktor/server/netty/http1/NettyHttp1ApplicationRequest.kt
Ekito
112,228,070
false
null
package io.ktor.server.netty.http1 import io.ktor.application.* import io.ktor.http.* import io.ktor.server.netty.* import io.netty.channel.* import io.netty.handler.codec.http.* import io.netty.handler.codec.http.multipart.* import kotlinx.coroutines.experimental.io.* internal class NettyHttp1ApplicationRequest(call: ApplicationCall, context: ChannelHandlerContext, val httpRequest: HttpRequest, requestBodyChannel: ByteReadChannel) : NettyApplicationRequest(call, context, requestBodyChannel, httpRequest.uri(), HttpUtil.isKeepAlive(httpRequest)) { override val local = NettyConnectionPoint(httpRequest, context) override val headers: Headers = NettyApplicationRequestHeaders(httpRequest) override fun newDecoder(): HttpPostMultipartRequestDecoder { return HttpPostMultipartRequestDecoder(httpRequest) } }
0
null
0
1
6b0fadcc30d3942a9d0ae8f2758c267ab557f8d5
971
ktor
Apache License 2.0
android/libraries/libMatches/src/main/java/nl/entreco/giddyapp/libmatches/delete/DeleteMatchRequest.kt
Entreco
164,009,012
false
null
package nl.entreco.giddyapp.libmatches.delete data class DeleteMatchRequest(val uuid: String, val horseId: String)
23
null
1
1
59960640ecd182c502df2d52fa17ed619d415c91
115
GiddyApp
Apache License 2.0
lint/src/main/java/com/adyen/checkout/lint/LintIssueRegistry.kt
Adyen
91,104,663
false
{"Kotlin": 4786289, "Shell": 4700}
/* * Copyright (c) 2024 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by oscars on 13/8/2024. */ package com.adyen.checkout.lint import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.detector.api.CURRENT_API import com.android.tools.lint.detector.api.Issue @Suppress("unused") internal class LintIssueRegistry : IssueRegistry() { override val api: Int = CURRENT_API override val issues: List<Issue> = listOf( CONTEXT_GET_STRING_ISSUE, NOT_ADYEN_LOG_ISSUE, OBJECT_IN_PUBLIC_SEALED_CLASS_ISSUE, TEXT_IN_LAYOUT_XML_ISSUE, ) }
23
Kotlin
66
126
5b728181dbf41af37c5f9d436b4c65cb30a23e41
685
adyen-android
MIT License
app/src/main/java/com/mengsoftstudio/android/footballmobile/contracts/SearchMatchContract.kt
fajaragungpramana
180,994,708
false
{"Kotlin": 118062}
package com.mengsoftstudio.android.footballmobile.contracts import com.mengsoftstudio.android.footballmobile.models.Match interface SearchMatchContract { interface View { fun onShowLoading() fun onSuccessFetchData(matchList: List<Match>) fun onFailureFetchData() fun onHideLoading() } interface Presenter { fun getSearchMatch(query: String) fun onDestroyPresenter() } }
0
Kotlin
0
5
8f3142f1a0d9102c507e82b63f253f4778e02e82
442
android.football
Apache License 2.0
app/src/main/java/de/dertyp7214/rboardthememanager/core/Fragment.kt
DerTyp7214
372,557,655
false
null
package de.dertyp7214.rboardthememanager.core import androidx.fragment.app.Fragment import com.google.android.material.transition.MaterialSharedAxis fun Fragment.applyTransitions() { enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) } fun Fragment.applyTransitionsViewCreated() { view?.setBackgroundResource(android.R.color.transparent) }
0
Kotlin
9
96
18deb69aad3100b9f2d73256eea221a4f7b6f6ef
575
RboardThemeManagerV3
MIT License
src/main/kotlin/frc/team3324/robot/shooter/commands/RunShooter.kt
frc3324
329,937,526
false
null
package frc.team3324.robot.shooter.commands import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard import edu.wpi.first.wpilibj2.command.CommandBase import frc.team3324.robot.Robot import frc.team3324.robot.shooter.Shooter import frc.team3324.robot.util.FrontCamera import kotlin.math.pow class RunShooter(val shooter: Shooter, private val frontCamera: FrontCamera, val trench: Boolean) : CommandBase() { init { Robot.light.set(true) addRequirements(shooter) } override fun execute() { val area = frontCamera.contourArea() var rpm = 4845 + -1.4*area + 0.000558*area.pow(2) - 100 val dashRPM = SmartDashboard.getNumber("Input RPM", 0.0) shooter.RPM = rpm SmartDashboard.putNumber("Goal RPM from shoot", rpm) Robot.robotContainer.rumbleController(1.0) } override fun end(interrupted: Boolean) { Robot.robotContainer.rumbleController(0.0) shooter.RPM = 0.0 } }
1
Kotlin
3
0
854e197b5cc5ce2412c1b315513a7e6764957aa2
972
Metrobots2021Robot
MIT License
app/src/main/java/com/gzaber/keepnote/data/repository/model/ModelMappingExt.kt
gzaber
690,170,857
false
{"Kotlin": 133592}
package com.gzaber.keepnote.data.repository.model import com.gzaber.keepnote.data.repository.model.Folder import com.gzaber.keepnote.data.repository.model.Note import com.gzaber.keepnote.data.source.room.FolderEntity import com.gzaber.keepnote.data.source.room.NoteEntity fun Note.toEntity() = NoteEntity( id, folderId, title, content, color, date ) fun NoteEntity.toModel() = Note( id, folderId, title, content, color, date ) fun Folder.toEntity() = FolderEntity( id, name, color, date ) fun FolderEntity.toModel() = Folder( id, name, color, date )
0
Kotlin
0
0
edbb170c29b26c8f881fc06412d517ca5171196c
570
KeepNote
MIT License
app/src/main/java/com/blissvine/dagerhiltdemo/repository/UserRepo.kt
abhii2002
616,537,609
false
null
package com.blissvine.dagerhiltdemo.repository import com.blissvine.dagerhiltdemo.data.UserDao import com.blissvine.dagerhiltdemo.model.User import kotlinx.coroutines.flow.Flow import javax.inject.Inject class UserRepo @Inject constructor(private val userDao: UserDao) { //insert user details to room suspend fun createUserRecords(user: User) : Long { return userDao.insertToRoomDatabase(user) } //get single user details e.g with id 1 val getUserDetails: Flow<List<User>> get() = userDao.getUsersDetails() //delete single user record suspend fun deleteSingleUserRecord() { userDao.deleteSingleUserDetails(1) } }
0
Kotlin
0
0
97b2070d11d19f95835deb863d6ac8bdb29a411a
666
DaggerHiltDemo
MIT License
core/src/main/kotlin/co/anitrend/arch/core/model/IStateLayoutConfig.kt
AniTrend
155,243,365
false
{"Kotlin": 385489}
/** * Copyright 2021 AniTrend * * 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 co.anitrend.arch.core.model import androidx.annotation.AnimRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes /** * Contract for state layout configuration * * @property loadingDrawable drawable for loading state, set this to null if you wish to hide the element * @property errorDrawable drawable for error state, set this to null if you wish to hide the element * @property loadingMessage label for loading message, set this to null if you wish to hide the element * @property defaultMessage label for success state, set this to null if you wish to hide the element * @property retryAction label for retry action, set this to null if you wish to hide the element * @property inAnimation optional animations to use for switching in views * @property outAnimation optional animations to use for switching out views * * @since v1.3.0 */ interface IStateLayoutConfig { @get:DrawableRes val loadingDrawable: Int? @get:DrawableRes val errorDrawable: Int? @get:StringRes val loadingMessage: Int? @get:StringRes val defaultMessage: Int? @get:StringRes val retryAction: Int? @get:AnimRes val inAnimation: Int @get:AnimRes val outAnimation: Int }
8
Kotlin
1
7
de2a3b77f1fe84c8742fb18ff10f61cb8b3a1660
1,846
support-arch
Apache License 2.0
app/src/main/java/com/example/meteorcrusher/GameViewModel.kt
ayowee
791,502,537
false
{"Kotlin": 9314}
package com.example.meteorcrusher import androidx.lifecycle.ViewModel class GameViewModel : ViewModel() { var score = 0 var speed = 1 var myShipPosition = 0 }
0
Kotlin
1
2
a6fb8b3e0c66a18a836bb1daefe517489d6aa380
173
MeteorEscape
MIT License
src/main/kotlin/spritz/error/interpreting/ReturnTypeMismatchError.kt
SpritzLanguage
606,570,819
false
null
package spritz.error.interpreting import spritz.interpreter.context.Context import spritz.lexer.position.Position /** * @author surge * @since 02/03/2023 */ class MutabilityAssignationError(details: String, start: Position, end: Position, context: Context) : RuntimeError("MutabilityAssignationError", details, start, end, context)
0
Kotlin
0
23
f50d81fa2d5aa7784ac4c76717603eea079c8db2
336
Spritz
The Unlicense
presentation/src/main/java/com/hamza/clean/ui/moviedetails/MovieDetailsPlaceholderFragment.kt
hmz9
612,902,426
false
null
package com.hamza.clean.ui.moviedetails import androidx.fragment.app.Fragment import com.hamza.clean.R /** * @author by <NAME> on 03/09/2023 */ class MovieDetailsPlaceholderFragment : Fragment(R.layout.fragment_movie_details_placeholder)
0
Kotlin
0
0
a6b10845b07b3bc5a651c77503ab0e50b79ba7ba
242
movie-android-clean-mvvm
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/prisonperson/PrisonPersonMigrationService.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2526024, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.prisonperson import com.microsoft.applicationinsights.TelemetryClient import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.core.ParameterizedTypeReference import org.springframework.data.domain.PageImpl import org.springframework.data.domain.Pageable import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.data.MigrationContext import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.helpers.trackEvent import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.CreateMappingResult import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.DuplicateErrorResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.listeners.MigrationMessageType import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.PrisonPersonMigrationMappingRequest import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.PrisonPersonMigrationMappingRequest.MigrationType.PHYSICAL_ATTRIBUTES import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PhysicalAttributesResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PrisonerId import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PrisonerPhysicalAttributesResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.prisonperson.model.PhysicalAttributesMigrationRequest import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.AuditService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationHistoryService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationQueueService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationType import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.NomisApiService import java.time.LocalDateTime @Service class PrisonPersonMigrationService( queueService: MigrationQueueService, private val prisonPersonNomisApiService: PrisonPersonNomisApiService, private val nomisService: NomisApiService, private val prisonPersonMappingService: PrisonPersonMappingApiService, private val prisonPersonDpsService: PrisonPersonDpsApiService, migrationHistoryService: MigrationHistoryService, telemetryClient: TelemetryClient, auditService: AuditService, @Value("\${page.size:1000}") pageSize: Long, @Value("\${complete-check.delay-seconds}") completeCheckDelaySeconds: Int, @Value("\${complete-check.count}") completeCheckCount: Int, ) : MigrationService<PrisonPersonMigrationFilter, PrisonerId, PrisonerPhysicalAttributesResponse, PrisonPersonMigrationMappingRequest>( queueService = queueService, auditService = auditService, migrationHistoryService = migrationHistoryService, mappingService = prisonPersonMappingService, telemetryClient = telemetryClient, migrationType = MigrationType.PRISONPERSON, pageSize = pageSize, completeCheckDelaySeconds = completeCheckDelaySeconds, completeCheckCount = completeCheckCount, ) { override suspend fun getIds( migrationFilter: PrisonPersonMigrationFilter, pageSize: Long, pageNumber: Long, ): PageImpl<PrisonerId> = if (migrationFilter.prisonerNumber.isNullOrEmpty()) { nomisService.getPrisonerIds( pageNumber = pageNumber, pageSize = pageSize, ) } else { // If a single prisoner migration is requested then we must be testing. Pretend that we called nomis-prisoner-api which found a single prisoner. PageImpl<PrisonerId>(mutableListOf(PrisonerId(migrationFilter.prisonerNumber)), Pageable.ofSize(1), 1) } override suspend fun migrateNomisEntity(context: MigrationContext<PrisonerId>) { log.info("attempting to migrate ${context.body}") val offenderNo = context.body.offenderNo val telemetry = mutableMapOf( "offenderNo" to offenderNo, "migrationId" to context.migrationId, "migrationType" to PHYSICAL_ATTRIBUTES, ) try { val dpsIds = prisonPersonNomisApiService.getPhysicalAttributes(offenderNo) .toDpsMigrationRequest() .migrate(offenderNo) telemetry["dpsIds"] = dpsIds.toString() PrisonPersonMigrationMappingRequest( nomisPrisonerNumber = offenderNo, migrationType = PHYSICAL_ATTRIBUTES, label = context.migrationId, dpsIds = dpsIds, ).createActivityMapping(context) telemetryClient.trackEvent("prisonperson-migration-entity-migrated", telemetry) } catch (e: Exception) { telemetry["error"] = e.message ?: "unknown error" telemetryClient.trackEvent("prisonperson-migration-entity-failed", telemetry) throw e } } private suspend fun PrisonerPhysicalAttributesResponse.toDpsMigrationRequest() = bookings.flatMap { booking -> booking.physicalAttributes.map { pa -> val (lastModifiedAt, lastModifiedBy) = pa.lastModified() prisonPersonDpsService.migratePhysicalAttributesRequest( heightCentimetres = pa.heightCentimetres, weightKilograms = pa.weightKilograms, appliesFrom = booking.startDateTime.toLocalDateTime(), appliesTo = booking.endDateTime?.toLocalDateTime(), createdAt = lastModifiedAt, createdBy = lastModifiedBy, ) } } private suspend fun List<PhysicalAttributesMigrationRequest>.migrate( offenderNo: String, ) = prisonPersonDpsService.migratePhysicalAttributes(offenderNo, this).fieldHistoryInserted private suspend fun PrisonPersonMigrationMappingRequest.createActivityMapping(context: MigrationContext<*>) = try { prisonPersonMappingService.createMapping(this, object : ParameterizedTypeReference<DuplicateErrorResponse<PrisonPersonMigrationMappingRequest>>() {}) .also { it.handleError(context) } } catch (e: Exception) { log.error( "Failed to create activity mapping for nomisPrisonerNumber: $nomisPrisonerNumber, dpsIds $dpsIds for migration ${this.label}", e, ) queueService.sendMessage( MigrationMessageType.RETRY_MIGRATION_MAPPING, MigrationContext( context = context, body = this, ), ) } private suspend fun CreateMappingResult<PrisonPersonMigrationMappingRequest>.handleError(context: MigrationContext<*>) = takeIf { it.isError } ?.let { it.errorResponse?.moreInfo } ?.also { telemetryClient.trackEvent( "prisonperson-nomis-migration-duplicate", mapOf( "migrationId" to context.migrationId, "duplicateNomisPrisonerNumber" to it.duplicate.nomisPrisonerNumber, "duplicateDpsIds" to it.duplicate.dpsIds.toString(), "existingNomisPrisonerNumber" to it.existing.nomisPrisonerNumber, "existingDpsIds" to it.existing.dpsIds.toString(), ), null, ) } private fun PhysicalAttributesResponse.lastModified(): Pair<LocalDateTime, String> = (modifiedDateTime ?: createDateTime).toLocalDateTime() to (modifiedBy ?: createdBy) private fun String.toLocalDateTime() = LocalDateTime.parse(this) private companion object { val log: Logger = LoggerFactory.getLogger(this::class.java) } }
1
Kotlin
1
2
c2246f3388fdbd46f6dba28c26940048607f9704
7,518
hmpps-prisoner-from-nomis-migration
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/prisonperson/PrisonPersonMigrationService.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2526024, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.prisonperson import com.microsoft.applicationinsights.TelemetryClient import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.core.ParameterizedTypeReference import org.springframework.data.domain.PageImpl import org.springframework.data.domain.Pageable import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.data.MigrationContext import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.helpers.trackEvent import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.CreateMappingResult import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.DuplicateErrorResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.listeners.MigrationMessageType import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.PrisonPersonMigrationMappingRequest import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.PrisonPersonMigrationMappingRequest.MigrationType.PHYSICAL_ATTRIBUTES import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PhysicalAttributesResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PrisonerId import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PrisonerPhysicalAttributesResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.prisonperson.model.PhysicalAttributesMigrationRequest import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.AuditService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationHistoryService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationQueueService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationService import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.MigrationType import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.service.NomisApiService import java.time.LocalDateTime @Service class PrisonPersonMigrationService( queueService: MigrationQueueService, private val prisonPersonNomisApiService: PrisonPersonNomisApiService, private val nomisService: NomisApiService, private val prisonPersonMappingService: PrisonPersonMappingApiService, private val prisonPersonDpsService: PrisonPersonDpsApiService, migrationHistoryService: MigrationHistoryService, telemetryClient: TelemetryClient, auditService: AuditService, @Value("\${page.size:1000}") pageSize: Long, @Value("\${complete-check.delay-seconds}") completeCheckDelaySeconds: Int, @Value("\${complete-check.count}") completeCheckCount: Int, ) : MigrationService<PrisonPersonMigrationFilter, PrisonerId, PrisonerPhysicalAttributesResponse, PrisonPersonMigrationMappingRequest>( queueService = queueService, auditService = auditService, migrationHistoryService = migrationHistoryService, mappingService = prisonPersonMappingService, telemetryClient = telemetryClient, migrationType = MigrationType.PRISONPERSON, pageSize = pageSize, completeCheckDelaySeconds = completeCheckDelaySeconds, completeCheckCount = completeCheckCount, ) { override suspend fun getIds( migrationFilter: PrisonPersonMigrationFilter, pageSize: Long, pageNumber: Long, ): PageImpl<PrisonerId> = if (migrationFilter.prisonerNumber.isNullOrEmpty()) { nomisService.getPrisonerIds( pageNumber = pageNumber, pageSize = pageSize, ) } else { // If a single prisoner migration is requested then we must be testing. Pretend that we called nomis-prisoner-api which found a single prisoner. PageImpl<PrisonerId>(mutableListOf(PrisonerId(migrationFilter.prisonerNumber)), Pageable.ofSize(1), 1) } override suspend fun migrateNomisEntity(context: MigrationContext<PrisonerId>) { log.info("attempting to migrate ${context.body}") val offenderNo = context.body.offenderNo val telemetry = mutableMapOf( "offenderNo" to offenderNo, "migrationId" to context.migrationId, "migrationType" to PHYSICAL_ATTRIBUTES, ) try { val dpsIds = prisonPersonNomisApiService.getPhysicalAttributes(offenderNo) .toDpsMigrationRequest() .migrate(offenderNo) telemetry["dpsIds"] = dpsIds.toString() PrisonPersonMigrationMappingRequest( nomisPrisonerNumber = offenderNo, migrationType = PHYSICAL_ATTRIBUTES, label = context.migrationId, dpsIds = dpsIds, ).createActivityMapping(context) telemetryClient.trackEvent("prisonperson-migration-entity-migrated", telemetry) } catch (e: Exception) { telemetry["error"] = e.message ?: "unknown error" telemetryClient.trackEvent("prisonperson-migration-entity-failed", telemetry) throw e } } private suspend fun PrisonerPhysicalAttributesResponse.toDpsMigrationRequest() = bookings.flatMap { booking -> booking.physicalAttributes.map { pa -> val (lastModifiedAt, lastModifiedBy) = pa.lastModified() prisonPersonDpsService.migratePhysicalAttributesRequest( heightCentimetres = pa.heightCentimetres, weightKilograms = pa.weightKilograms, appliesFrom = booking.startDateTime.toLocalDateTime(), appliesTo = booking.endDateTime?.toLocalDateTime(), createdAt = lastModifiedAt, createdBy = lastModifiedBy, ) } } private suspend fun List<PhysicalAttributesMigrationRequest>.migrate( offenderNo: String, ) = prisonPersonDpsService.migratePhysicalAttributes(offenderNo, this).fieldHistoryInserted private suspend fun PrisonPersonMigrationMappingRequest.createActivityMapping(context: MigrationContext<*>) = try { prisonPersonMappingService.createMapping(this, object : ParameterizedTypeReference<DuplicateErrorResponse<PrisonPersonMigrationMappingRequest>>() {}) .also { it.handleError(context) } } catch (e: Exception) { log.error( "Failed to create activity mapping for nomisPrisonerNumber: $nomisPrisonerNumber, dpsIds $dpsIds for migration ${this.label}", e, ) queueService.sendMessage( MigrationMessageType.RETRY_MIGRATION_MAPPING, MigrationContext( context = context, body = this, ), ) } private suspend fun CreateMappingResult<PrisonPersonMigrationMappingRequest>.handleError(context: MigrationContext<*>) = takeIf { it.isError } ?.let { it.errorResponse?.moreInfo } ?.also { telemetryClient.trackEvent( "prisonperson-nomis-migration-duplicate", mapOf( "migrationId" to context.migrationId, "duplicateNomisPrisonerNumber" to it.duplicate.nomisPrisonerNumber, "duplicateDpsIds" to it.duplicate.dpsIds.toString(), "existingNomisPrisonerNumber" to it.existing.nomisPrisonerNumber, "existingDpsIds" to it.existing.dpsIds.toString(), ), null, ) } private fun PhysicalAttributesResponse.lastModified(): Pair<LocalDateTime, String> = (modifiedDateTime ?: createDateTime).toLocalDateTime() to (modifiedBy ?: createdBy) private fun String.toLocalDateTime() = LocalDateTime.parse(this) private companion object { val log: Logger = LoggerFactory.getLogger(this::class.java) } }
1
Kotlin
1
2
c2246f3388fdbd46f6dba28c26940048607f9704
7,518
hmpps-prisoner-from-nomis-migration
MIT License
uicorektest/src/main/java/com/mozhimen/uicorektest/recyclerk/RecyclerKLifecycleActivity.kt
mozhimen
353,952,154
false
{"Kotlin": 2595996, "Java": 371518, "AIDL": 1012}
package com.mozhimen.uicorektest.recyclerk import android.os.Bundle import android.widget.LinearLayout import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.mozhimen.basick.elemk.androidx.appcompat.bases.databinding.BaseActivityVB import com.mozhimen.basick.elemk.mos.MKey import com.mozhimen.basick.lintk.optin.OptInApiCall_BindLifecycle import com.mozhimen.basick.utilk.android.widget.showToast import com.mozhimen.uicorek.adapterk.item.AdapterKItemRecyclerVB import com.mozhimen.uicorektest.R import com.mozhimen.uicorektest.BR import com.mozhimen.uicorektest.databinding.ActivityRecyclerkLifecycleBinding import com.mozhimen.uicorektest.databinding.ItemRecyclerkLifecycleBinding class RecyclerKLifecycleActivity : BaseActivityVB<ActivityRecyclerkLifecycleBinding>() { @OptIn(OptInApiCall_BindLifecycle::class) override fun initView(savedInstanceState: Bundle?) { val list = mutableListOf(MKey("1", "1"), MKey("2", "2")) vb.recyclerkLifecycle.bindLifecycle(this) vb.recyclerkLifecycle.layoutManager = LinearLayoutManager(this) vb.recyclerkLifecycle.addItemDecoration(DividerItemDecoration(this, LinearLayout.VERTICAL)) vb.recyclerkLifecycle.adapter = AdapterKItemRecyclerVB<MKey, ItemRecyclerkLifecycleBinding>(list, R.layout.item_recyclerk_lifecycle, BR.item_recyclerk_lifecycle) { holder, _, position, _ -> holder.vb.itemRecyclerkLifecycleBox.setOnClickListener { position.toString().showToast() } }.apply { onDataSelected(0) } } }
0
Kotlin
7
114
d74563aa5722b01ceb0e7d24c9001050b577db5d
1,666
SwiftKit
Apache License 2.0
app/src/main/java/com/igorvd/githubrepo/dependency_injection/domain/GitHubRepoModule.kt
igorvilela28
106,742,458
true
{"Gradle": 3, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 47, "XML": 18, "Java": 2}
package com.igorvd.githubrepo.dependency_injection.domain import com.igorvd.githubrepo.data.repository.impl.GitHubRepoNetworkRepository import com.igorvd.githubrepo.data.repository.GitHubRepoRepository import com.igorvd.githubrepo.domain.LoadGitHubReposInteractor import dagger.Module import dagger.Provides import javax.inject.Named /** * @author <NAME> * @since 14/10/17 */ @Module class GitHubRepoModule { @Named("network") @Provides fun providesGitHubNetworkRepository(gitHubRepoRepository: GitHubRepoNetworkRepository) : GitHubRepoRepository { return gitHubRepoRepository } @Named("network") @Provides fun providesInteractor(@Named("network") gitHubRepoRepository : GitHubRepoRepository) : LoadGitHubReposInteractor { return LoadGitHubReposInteractor(gitHubRepoRepository) } }
0
Kotlin
0
5
d484622a1c05ff2baf87dde2c163afbdb239b45f
861
Github-Popular-Repos
Apache License 2.0
mastodonk-core/src/commonMain/kotlin/fr/outadoc/mastodonk/serializer/TimestampToInstantSerializer.kt
outadoc
361,237,514
false
null
package fr.outadoc.mastodonk.serializer import kotlinx.datetime.Instant import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder internal class TimestampToInstantSerializer : KSerializer<Instant> { override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor("TimestampToInstantSerializer", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): Instant { return Instant.fromEpochSeconds(decoder.decodeLong()) } override fun serialize(encoder: Encoder, value: Instant) { encoder.encodeLong(value.epochSeconds) } }
1
Kotlin
0
3
0dff922e6077184f4d9fcefb9f5204fac6b3bdfd
845
mastodonk
Apache License 2.0
src/main/kotlin/io/hirasawa/server/chat/ChatChannel.kt
cg0
256,633,551
false
{"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Kotlin": 304, "Java": 2, "YAML": 2, "XML": 10}
package io.hirasawa.server.chat import io.hirasawa.server.Hirasawa import io.hirasawa.server.chat.message.GlobalChatMessage import io.hirasawa.server.bancho.packets.BanchoPacket import io.hirasawa.server.bancho.packets.ChannelAvailablePacket import io.hirasawa.server.bancho.packets.SendMessagePacket import io.hirasawa.server.bancho.user.BanchoUser import io.hirasawa.server.bancho.user.User import io.hirasawa.server.chat.enums.ChatChannelVisibility import io.hirasawa.server.irc.clientcommands.* import io.hirasawa.server.irc.objects.IrcUser import io.hirasawa.server.objects.UserMap abstract class ChatChannel(val metadata: ChatChannelMetadata, connectedUsers: UserMap<out User> = UserMap(), val visibility: ChatChannelVisibility = ChatChannelVisibility.PRIVATE) { val connectedUsers: UserMap<User> = UserMap() private val addBindId: Int private val removeBindId: Int init { connectedUsers.values.forEach { this.connectedUsers.add(it) } addBindId = connectedUsers.bind(UserMap.BindType.ADD) { addUser(it ?: return@bind) } removeBindId = connectedUsers.bind(UserMap.BindType.REMOVE) { addUser(it ?: return@bind) } connectedUsers.bind(UserMap.BindType.CLOSE) { this.close() } } val size get() = connectedUsers.size.toShort() /** * Send BanchoPacket to all BanchoUsers connected to this ChatChannel * * @param banchoPacket The packet to send */ fun sendBanchoPacketToAll(banchoPacket: BanchoPacket) { for (user in connectedUsers) { if (user is BanchoUser) { user.sendPacket(banchoPacket) } } } private fun sendPacketToAllExcluding(banchoPacket: BanchoPacket, exclude: User) { for (user in connectedUsers) { if (user == exclude) continue if (user is BanchoUser) { user.sendPacket(banchoPacket) } } } private fun sendIrcReplyToAll(ircProtocolReply: IrcProtocolReply) { for (user in connectedUsers) { if (user is IrcUser) { user.sendReply(ircProtocolReply) } } } /** * Add user to ChatChannel, this will register them for all messages and inform other connected users that they * joined * * @param user The user to add */ fun addUser(user: User) { connectedUsers.add(user) sendIrcReplyToAll(Join(this, user)) update() if (visibility == ChatChannelVisibility.PRIVATE) { Hirasawa.chatEngine.addUserToPrivateChannel(user, this) } } /** * Removes a user from this ChatChannel, this will unregister them for all messages and inform other connected users * that they have left * * @param user The user to remove */ fun removeUser(user: User) { if (user in connectedUsers) { sendIrcReplyToAll(Part(this, user)) connectedUsers.remove(user) if (visibility == ChatChannelVisibility.PRIVATE) { user.revokeChatChannel(this) } update() if (visibility == ChatChannelVisibility.PRIVATE) { Hirasawa.chatEngine.removeUserFromPrivateChannel(user, this) } } } /** * Queues a message to all connected clients in the ChatChannel other than the message source * * @param chatMessage The chat message to queue */ open fun sendMessage(chatMessage: GlobalChatMessage) { for (user in connectedUsers) { if (chatMessage.source == user) continue when (user) { is BanchoUser -> { user.sendPacket(SendMessagePacket(chatMessage)) } is IrcUser -> { user.sendReply(Privmsg(chatMessage)) } } } } fun close() { connectedUsers.unbind(UserMap.BindType.ADD, addBindId) connectedUsers.unbind(UserMap.BindType.REMOVE, removeBindId) Hirasawa.chatEngine.removeChannel(this) } private fun update() { when (visibility) { ChatChannelVisibility.PRIVATE -> { sendBanchoPacketToAll(ChannelAvailablePacket(this)) } ChatChannelVisibility.PUBLIC -> { Hirasawa.sendBanchoPacketToAll(ChannelAvailablePacket(this)) } } } }
38
Kotlin
0
6
ce416d649095bbaee105fcbaa88e9a3c7cf745ac
4,578
Hirasawa-Project
MIT License
espresso-server/app/src/androidTest/java/io/appium/espressoserver/lib/model/DataMatcherJson.kt
o-x-y-g-e-n
225,694,846
true
{"Kotlin": 390193, "Java": 267137, "JavaScript": 112892, "Shell": 897}
package io.appium.espressoserver.lib.model import androidx.test.espresso.DataInteraction import androidx.test.espresso.Espresso.onData import com.google.gson.* import com.google.gson.annotations.JsonAdapter import io.appium.espressoserver.lib.handlers.exceptions.AppiumException import io.appium.espressoserver.lib.handlers.exceptions.InvalidSelectorException import org.hamcrest.Matcher import java.lang.reflect.Type @JsonAdapter(DataMatcherJsonDeserializer::class) data class DataMatcherJson( val matcher:Matcher<*> ) : AppiumParams() { fun invoke(): DataInteraction { return onData(matcher); } companion object { fun fromJson(selector:String): DataMatcherJson { try { return Gson().fromJson(selector, DataMatcherJson::class.java) } catch (e: AppiumException) { throw InvalidSelectorException(String.format("Not a valid selector '%s'. Reason: '%s'", selector, e.cause)) } catch (e: JsonParseException) { throw InvalidSelectorException(String.format("Could not parse selector '%s'. Reason: '%s'", selector, e.cause)) } } } } class DataMatcherJsonDeserializer : JsonDeserializer<DataMatcherJson> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, paramType: Type?, paramJsonDeserializationContext: JsonDeserializationContext?): DataMatcherJson { if (!json.isJsonObject) { throw JsonParseException("Data matcher must be an object. Found '${json}'") } val matcher = HamcrestMatcher.HamcrestMatcherDeserializer() .deserialize(json, null, null) .invoke(); return DataMatcherJson(matcher) } }
0
Kotlin
0
0
a3e44b30671c5fa84c2d1a40c9d3d3812f071613
1,781
appium-espresso-driver
Apache License 2.0
app/src/main/java/com/karthek/android/s/gallery/state/db/SMedia.kt
karthek-git
601,273,989
false
null
package com.karthek.android.s.gallery.state.db import android.content.ContentUris import android.net.Uri import android.provider.MediaStore import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Ignore import androidx.room.PrimaryKey @Entity data class SMedia( @PrimaryKey var id: Int = 0, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "path") var path: String, @ColumnInfo(name = "lm") var date: Long, @ColumnInfo(name = "isVideo") var isVideo: Boolean = false, @ColumnInfo(name = "cat") var cat: String?, @ColumnInfo(typeAffinity = ColumnInfo.BLOB) var faceEmbeddings: List<FloatArray>? = null, ) { @Ignore var uri: Uri = makeSMediaUri(id, isVideo) @Ignore var origPos = 0 @Ignore var isHeader = -1 constructor( id: Int, uri: Uri, path: String, name: String, date: Long, isVideo: Boolean, orig_pos: Int, ) : this(id, name, path, date, isVideo, null) { this.uri = uri this.origPos = orig_pos } constructor( id: Int, path: String, name: String, date: Long, isVideo: Boolean, orig_pos: Int, ) : this(id, name, path, date, isVideo, null) { this.origPos = orig_pos } constructor( uri: Uri, path: String, isVideo: Boolean, ) : this(0, "", path, 0, isVideo, null) { this.uri = uri } constructor(isHeader: Int, date: Long) : this(0, "_", "_", date, false, null) { this.isHeader = isHeader } } fun makeSMediaUri(id: Int, isVideo: Boolean): Uri { val mediaTableUri = if (isVideo) videosUri else imagesUri return ContentUris.withAppendedId(mediaTableUri, id.toLong()) } val imagesUri: Uri = MediaStore.Images.Media.getContentUri("external") val videosUri: Uri = MediaStore.Video.Media.getContentUri("external")
0
Kotlin
0
0
52a0d3933ae3b2bd22a91a03bc043820dc2e4fdc
1,715
Gallery
Apache License 2.0
ProShaped/app/src/main/java/com/example/proshapedapp/workoutScreenPackage/DisplayViewModel.kt
Capybara-Dev-Team
505,395,940
false
null
package com.example.proshapedapp.workoutScreenPackage import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.proshapedapp.workoutScreenPackage.database.Graph import com.example.proshapedapp.workoutScreenPackage.database.WorkoutItem import com.example.proshapedapp.workoutScreenPackage.database.WorkoutRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch class DisplayViewModel(private val workoutRepository: WorkoutRepository = Graph.workoutRepo): ViewModel() { private val _state = MutableStateFlow(DisplayViewState()) val state: StateFlow<DisplayViewState> get() = _state val workoutList = workoutRepository.selectAll val selected = MutableStateFlow(_state.value.selected) init { viewModelScope.launch { combine(workoutList, selected){ workoutList: List<WorkoutItem>, selected: Boolean -> DisplayViewState(workoutList, selected) }.collect { _state.value = it } } } fun updateWorkout(selected: Boolean, id: Long) = viewModelScope.launch { workoutRepository.updateWorkout(selected, id) } fun deleteWorkout(workoutItem: WorkoutItem) = viewModelScope.launch { workoutRepository.deleteWorkout(workoutItem) } } data class DisplayViewState( val workoutList: List<WorkoutItem> = emptyList(), val selected: Boolean = false )
0
Kotlin
2
2
c1ab400ef04e04b0424878750a1f3cdc74930a23
1,580
ProShaped-app
Apache License 2.0
src/main/kotlin/dev/zacsweers/ReadMeTemplate.kt
ZacSweers
288,008,412
false
null
package dev.zacsweers fun createReadMe( githubActivity: List<ActivityItem>, blogActivity: List<ActivityItem> ): String { return """ Currently working on [Slack](https://slack.com/). Read [my blog](https://zacsweers.dev/) or follow me on [Twitter](https://twitter.com/ZacSweers)/[Mastodon](https://hachyderm.io/@ZacSweers). <table><tr><td valign="top" width="60%"> ## GitHub Activity <!-- githubActivity starts --> ${githubActivity.joinToString("\n\n") { " $it" }} <!-- githubActivity ends --> </td><td valign="top" width="40%"> ## On My Blog <!-- blog starts --> ${blogActivity.joinToString("\n\n") { " $it" }} <!-- blog ends --> _More on [zacsweers.dev](https://zacsweers.dev/)_ </td></tr></table> <sub><a href="https://simonwillison.net/2020/Jul/10/self-updating-profile-readme/">Inspired by <NAME>'s auto-updating profile README.</a></sub> """.trimIndent() }
4
Kotlin
1
15
fab8139be563d2301749d596dd687bfca945ec48
932
ZacSweers
Apache License 2.0
ksoup/src/com/fleeksoft/ksoup/ported/io/BufferedReader.kt
fleeksoft
719,100,459
false
null
package com.fleeksoft.io import com.fleeksoft.io.exception.IOException import com.fleeksoft.io.internal.ObjHelper import kotlin.math.min /** * Creates a buffering character-input stream that uses an input buffer of * the specified size. * * @param reader A Reader * @param sz Input-buffer size * * @throws IllegalArgumentException If `sz <= 0` */ class BufferedReader(reader: Reader, sz: Int = DEFAULT_CHAR_BUFFER_SIZE) : Reader() { companion object { private const val INVALIDATED: Int = -2 private const val UNMARKED: Int = -1 private const val DEFAULT_EXPECTED_LINE_LENGTH: Int = 80 } private var reader: Reader? = reader private var cb: CharArray? = null private var nChars = 0 private var nextChar: Int = 0 private var markedChar = UNMARKED private var readAheadLimit = 0 /* Valid only when markedChar > 0 */ /** If the next character is a line feed, skip it */ private var skipLF = false /** The skipLF flag when the mark was set */ private var markedSkipLF = false init { require(sz > 0) { "Buffer size <= 0" } cb = CharArray(sz) nChars = 0 nextChar = nChars } /** Checks to make sure that the stream has not been closed */ private fun ensureOpen() { if (reader == null) throw IOException("Stream closed") } /** * Fills the input buffer, taking the mark into account if it is valid. */ private fun fill() { val dst: Int if (markedChar <= UNMARKED) {/* No mark */ dst = 0 } else {/* Marked */ val delta = nextChar - markedChar if (delta >= readAheadLimit) {/* Gone past read-ahead limit: Invalidate mark */ markedChar = INVALIDATED readAheadLimit = 0 dst = 0 } else { if (readAheadLimit <= cb!!.size) {/* Shuffle in the current buffer */ // todo://test it cb!!.copyInto(destination = cb!!, destinationOffset = 0, startIndex = markedChar, endIndex = delta + markedChar) markedChar = 0 dst = delta } else {/* Reallocate buffer to accommodate read-ahead limit */ val ncb = CharArray(readAheadLimit) cb!!.copyInto(destination = ncb, destinationOffset = 0, startIndex = markedChar, endIndex = delta + markedChar) cb = ncb markedChar = 0 dst = delta } nChars = delta nextChar = nChars } } var n: Int do { n = reader!!.read(cb!!, dst, cb!!.size - dst) } while (n == 0) if (n > 0) { nChars = dst + n nextChar = dst } } /** * Reads a single character. * * @return The character read, as an integer in the range * 0 to 65535 (`0x00-0xffff`), or -1 if the * end of the stream has been reached * @throws IOException If an I/O error occurs */ override fun read(): Int { return implRead() } private fun implRead(): Int { ensureOpen() while (true) { if (nextChar >= nChars) { fill() if (nextChar >= nChars) return -1 } if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ continue } } return cb!![nextChar++].code } } /** * Reads characters into a portion of an array, reading from the underlying * stream if necessary. */ private fun read1(cbuf: CharArray, off: Int, len: Int): Int { if (nextChar >= nChars) {/* If the requested length is at least as large as the buffer, and if there is no mark/reset activity, and if line feeds are not being skipped, do not bother to copy the characters into the local buffer. In this way buffered streams will cascade harmlessly. */ if (len >= cb!!.size && markedChar <= UNMARKED && !skipLF) { return reader!!.read(cbuf, off, len) } fill() } if (nextChar >= nChars) return -1 if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ if (nextChar >= nChars) fill() if (nextChar >= nChars) return -1 } } val n = min(len.toDouble(), (nChars - nextChar).toDouble()).toInt() cb!!.copyInto(destination = cbuf, destinationOffset = off, startIndex = nextChar, endIndex = n + nextChar) nextChar += n return n } /** * Reads characters into a portion of an array. * * <p> This method implements the general contract of the corresponding * {@link Reader#read(char[], int, int) read} method of the * {@link Reader} class. As an additional convenience, it * attempts to read as many characters as possible by repeatedly invoking * the {@code read} method of the underlying stream. This iterated * {@code read} continues until one of the following conditions becomes * true: * <ul> * * <li> The specified number of characters have been read, * * <li> The {@code read} method of the underlying stream returns * {@code -1}, indicating end-of-file, or * * <li> The {@code ready} method of the underlying stream * returns {@code false}, indicating that further input requests * would block. * * </ul> * If the first {@code read} on the underlying stream returns * {@code -1} to indicate end-of-file then this method returns * {@code -1}. Otherwise this method returns the number of characters * actually read. * * <p> Subclasses of this class are encouraged, but not required, to * attempt to read as many characters as possible in the same fashion. * * <p> Ordinarily this method takes characters from this stream's character * buffer, filling it from the underlying stream as necessary. If, * however, the buffer is empty, the mark is not valid, and the requested * length is at least as large as the buffer, then this method will read * characters directly from the underlying stream into the given array. * Thus redundant {@code BufferedReader}s will not copy data * unnecessarily. * * @param cbuf {@inheritDoc} * @param offset {@inheritDoc} * @param length {@inheritDoc} * * @return {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IOException {@inheritDoc} */ override fun read(cbuf: CharArray, offset: Int, length: Int): Int { return implRead(cbuf, offset, length) } private fun implRead(cbuf: CharArray, off: Int, len: Int): Int { // println("lockedRead: offset: $off, length: $len, cbuf: ${cbuf.slice(0..10)}, size: ${cbuf.size}") ensureOpen() ObjHelper.checkFromIndexSize(off, len, cbuf.size) if (len == 0) { return 0 } var n = read1(cbuf, off, len) if (n <= 0) return n while ((n < len) && reader!!.ready()) { val n1 = read1(cbuf, off + n, len - n) if (n1 <= 0) break n += n1 } return n } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), a carriage return * followed immediately by a line feed, or by reaching the end-of-file * (EOF). * * @param ignoreLF If true, the next '\n' will be skipped * @param term Output: Whether a line terminator was encountered * while reading the line; may be `null`. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached without reading any characters * * @see LineNumberReader.readLine * @throws IOException If an I/O error occurs */ private fun readLine(ignoreLF: Boolean, term: BooleanArray?): String? { return implReadLine(ignoreLF, term) } private fun implReadLine(ignoreLF: Boolean, term: BooleanArray?): String? { var s: StringBuilder? = null var startChar: Int ensureOpen() var omitLF = ignoreLF || skipLF if (term != null) term[0] = false bufferLoop@ while (true) { if (nextChar >= nChars) fill() if (nextChar >= nChars) { /* EOF */ return if (s != null && s.isNotEmpty()) s.toString() else null } var eol = false var c = 0.toChar() /* Skip a leftover '\n', if necessary */ if (omitLF && (cb!![nextChar] == '\n')) nextChar++ skipLF = false omitLF = false var i = nextChar charLoop@ while (i < nChars) { c = cb!![i] if ((c == '\n') || (c == '\r')) { if (term != null) term[0] = true eol = true break@charLoop } i++ } startChar = nextChar nextChar = i if (eol) { val str: String if (s == null) { str = cb!!.concatToString(startChar, startChar + (i - startChar)) } else { s.appendRange(cb!!, startChar, startChar + (i - startChar)) str = s.toString() } nextChar++ if (c == '\r') { skipLF = true } return str } if (s == null) s = StringBuilder(DEFAULT_EXPECTED_LINE_LENGTH) s.appendRange(cb!!, startChar, startChar + (i - startChar)) } } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), a carriage return * followed immediately by a line feed, or by reaching the end-of-file * (EOF). * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached without reading any characters * * @throws IOException If an I/O error occurs * * @see Files.readAllLines */ fun readLine(): String? { return readLine(false, null) } /** * {@inheritDoc} */ override fun skip(n: Long): Long { require(n >= 0L) { "skip value is negative" } return implSkip(n) } private fun implSkip(n: Long): Long { ensureOpen() var r = n while (r > 0) { if (nextChar >= nChars) fill() if (nextChar >= nChars) /* EOF */ break if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ } } val d = (nChars - nextChar).toLong() if (r <= d) { nextChar += r.toInt() r = 0 break } else { r -= d nextChar = nChars } } return n - r } /** * Tells whether this stream is ready to be read. A buffered character * stream is ready if the buffer is not empty, or if the underlying * character stream is ready. * * @throws IOException If an I/O error occurs */ override fun ready(): Boolean { return implReady(); } private fun implReady(): Boolean { ensureOpen() /* * If newline needs to be skipped and the next char to be read * is a newline character, then just skip it right away. */ if (skipLF) {/* Note that in.ready() will return true if and only if the next * read on the stream will not block. */ if (nextChar >= nChars && reader!!.ready()) { fill() } if (nextChar < nChars) { if (cb!![nextChar] == '\n') nextChar++ skipLF = false } } return (nextChar < nChars) || reader!!.ready() } /** * Tells whether this stream supports the mark() operation, which it does. */ override fun markSupported(): Boolean { return true } /** * Marks the present position in the stream. Subsequent calls to reset() * will attempt to reposition the stream to this point. * * @param readAheadLimit Limit on the number of characters that may be * read while still preserving the mark. An attempt * to reset the stream after reading characters * up to this limit or beyond may fail. * A limit value larger than the size of the input * buffer will cause a new buffer to be allocated * whose size is no smaller than limit. * Therefore large values should be used with care. * * @throws IllegalArgumentException If `readAheadLimit < 0` * @throws IOException If an I/O error occurs */ override fun mark(readAheadLimit: Int) { require(readAheadLimit >= 0) { "Read-ahead limit < 0" } implMark(readAheadLimit) } private fun implMark(readAheadLimit: Int) { ensureOpen() this.readAheadLimit = readAheadLimit markedChar = nextChar markedSkipLF = skipLF } /** * Resets the stream to the most recent mark. * * @throws IOException If the stream has never been marked, * or if the mark has been invalidated */ override fun reset() { implReset() } private fun implReset() { ensureOpen() if (markedChar < 0) throw IOException( if ((markedChar == INVALIDATED)) "Mark invalid" else "Stream not marked" ) nextChar = markedChar skipLF = markedSkipLF } override fun close() { implClose() } private fun implClose() { try { reader?.close() } finally { reader = null cb = null } } }
7
null
11
281
4fd2972a008ee39df42c5ee8cb06ff54860d3e7b
14,703
ksoup
Apache License 2.0
ksoup/src/com/fleeksoft/ksoup/ported/io/BufferedReader.kt
fleeksoft
719,100,459
false
null
package com.fleeksoft.io import com.fleeksoft.io.exception.IOException import com.fleeksoft.io.internal.ObjHelper import kotlin.math.min /** * Creates a buffering character-input stream that uses an input buffer of * the specified size. * * @param reader A Reader * @param sz Input-buffer size * * @throws IllegalArgumentException If `sz <= 0` */ class BufferedReader(reader: Reader, sz: Int = DEFAULT_CHAR_BUFFER_SIZE) : Reader() { companion object { private const val INVALIDATED: Int = -2 private const val UNMARKED: Int = -1 private const val DEFAULT_EXPECTED_LINE_LENGTH: Int = 80 } private var reader: Reader? = reader private var cb: CharArray? = null private var nChars = 0 private var nextChar: Int = 0 private var markedChar = UNMARKED private var readAheadLimit = 0 /* Valid only when markedChar > 0 */ /** If the next character is a line feed, skip it */ private var skipLF = false /** The skipLF flag when the mark was set */ private var markedSkipLF = false init { require(sz > 0) { "Buffer size <= 0" } cb = CharArray(sz) nChars = 0 nextChar = nChars } /** Checks to make sure that the stream has not been closed */ private fun ensureOpen() { if (reader == null) throw IOException("Stream closed") } /** * Fills the input buffer, taking the mark into account if it is valid. */ private fun fill() { val dst: Int if (markedChar <= UNMARKED) {/* No mark */ dst = 0 } else {/* Marked */ val delta = nextChar - markedChar if (delta >= readAheadLimit) {/* Gone past read-ahead limit: Invalidate mark */ markedChar = INVALIDATED readAheadLimit = 0 dst = 0 } else { if (readAheadLimit <= cb!!.size) {/* Shuffle in the current buffer */ // todo://test it cb!!.copyInto(destination = cb!!, destinationOffset = 0, startIndex = markedChar, endIndex = delta + markedChar) markedChar = 0 dst = delta } else {/* Reallocate buffer to accommodate read-ahead limit */ val ncb = CharArray(readAheadLimit) cb!!.copyInto(destination = ncb, destinationOffset = 0, startIndex = markedChar, endIndex = delta + markedChar) cb = ncb markedChar = 0 dst = delta } nChars = delta nextChar = nChars } } var n: Int do { n = reader!!.read(cb!!, dst, cb!!.size - dst) } while (n == 0) if (n > 0) { nChars = dst + n nextChar = dst } } /** * Reads a single character. * * @return The character read, as an integer in the range * 0 to 65535 (`0x00-0xffff`), or -1 if the * end of the stream has been reached * @throws IOException If an I/O error occurs */ override fun read(): Int { return implRead() } private fun implRead(): Int { ensureOpen() while (true) { if (nextChar >= nChars) { fill() if (nextChar >= nChars) return -1 } if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ continue } } return cb!![nextChar++].code } } /** * Reads characters into a portion of an array, reading from the underlying * stream if necessary. */ private fun read1(cbuf: CharArray, off: Int, len: Int): Int { if (nextChar >= nChars) {/* If the requested length is at least as large as the buffer, and if there is no mark/reset activity, and if line feeds are not being skipped, do not bother to copy the characters into the local buffer. In this way buffered streams will cascade harmlessly. */ if (len >= cb!!.size && markedChar <= UNMARKED && !skipLF) { return reader!!.read(cbuf, off, len) } fill() } if (nextChar >= nChars) return -1 if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ if (nextChar >= nChars) fill() if (nextChar >= nChars) return -1 } } val n = min(len.toDouble(), (nChars - nextChar).toDouble()).toInt() cb!!.copyInto(destination = cbuf, destinationOffset = off, startIndex = nextChar, endIndex = n + nextChar) nextChar += n return n } /** * Reads characters into a portion of an array. * * <p> This method implements the general contract of the corresponding * {@link Reader#read(char[], int, int) read} method of the * {@link Reader} class. As an additional convenience, it * attempts to read as many characters as possible by repeatedly invoking * the {@code read} method of the underlying stream. This iterated * {@code read} continues until one of the following conditions becomes * true: * <ul> * * <li> The specified number of characters have been read, * * <li> The {@code read} method of the underlying stream returns * {@code -1}, indicating end-of-file, or * * <li> The {@code ready} method of the underlying stream * returns {@code false}, indicating that further input requests * would block. * * </ul> * If the first {@code read} on the underlying stream returns * {@code -1} to indicate end-of-file then this method returns * {@code -1}. Otherwise this method returns the number of characters * actually read. * * <p> Subclasses of this class are encouraged, but not required, to * attempt to read as many characters as possible in the same fashion. * * <p> Ordinarily this method takes characters from this stream's character * buffer, filling it from the underlying stream as necessary. If, * however, the buffer is empty, the mark is not valid, and the requested * length is at least as large as the buffer, then this method will read * characters directly from the underlying stream into the given array. * Thus redundant {@code BufferedReader}s will not copy data * unnecessarily. * * @param cbuf {@inheritDoc} * @param offset {@inheritDoc} * @param length {@inheritDoc} * * @return {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IOException {@inheritDoc} */ override fun read(cbuf: CharArray, offset: Int, length: Int): Int { return implRead(cbuf, offset, length) } private fun implRead(cbuf: CharArray, off: Int, len: Int): Int { // println("lockedRead: offset: $off, length: $len, cbuf: ${cbuf.slice(0..10)}, size: ${cbuf.size}") ensureOpen() ObjHelper.checkFromIndexSize(off, len, cbuf.size) if (len == 0) { return 0 } var n = read1(cbuf, off, len) if (n <= 0) return n while ((n < len) && reader!!.ready()) { val n1 = read1(cbuf, off + n, len - n) if (n1 <= 0) break n += n1 } return n } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), a carriage return * followed immediately by a line feed, or by reaching the end-of-file * (EOF). * * @param ignoreLF If true, the next '\n' will be skipped * @param term Output: Whether a line terminator was encountered * while reading the line; may be `null`. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached without reading any characters * * @see LineNumberReader.readLine * @throws IOException If an I/O error occurs */ private fun readLine(ignoreLF: Boolean, term: BooleanArray?): String? { return implReadLine(ignoreLF, term) } private fun implReadLine(ignoreLF: Boolean, term: BooleanArray?): String? { var s: StringBuilder? = null var startChar: Int ensureOpen() var omitLF = ignoreLF || skipLF if (term != null) term[0] = false bufferLoop@ while (true) { if (nextChar >= nChars) fill() if (nextChar >= nChars) { /* EOF */ return if (s != null && s.isNotEmpty()) s.toString() else null } var eol = false var c = 0.toChar() /* Skip a leftover '\n', if necessary */ if (omitLF && (cb!![nextChar] == '\n')) nextChar++ skipLF = false omitLF = false var i = nextChar charLoop@ while (i < nChars) { c = cb!![i] if ((c == '\n') || (c == '\r')) { if (term != null) term[0] = true eol = true break@charLoop } i++ } startChar = nextChar nextChar = i if (eol) { val str: String if (s == null) { str = cb!!.concatToString(startChar, startChar + (i - startChar)) } else { s.appendRange(cb!!, startChar, startChar + (i - startChar)) str = s.toString() } nextChar++ if (c == '\r') { skipLF = true } return str } if (s == null) s = StringBuilder(DEFAULT_EXPECTED_LINE_LENGTH) s.appendRange(cb!!, startChar, startChar + (i - startChar)) } } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), a carriage return * followed immediately by a line feed, or by reaching the end-of-file * (EOF). * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached without reading any characters * * @throws IOException If an I/O error occurs * * @see Files.readAllLines */ fun readLine(): String? { return readLine(false, null) } /** * {@inheritDoc} */ override fun skip(n: Long): Long { require(n >= 0L) { "skip value is negative" } return implSkip(n) } private fun implSkip(n: Long): Long { ensureOpen() var r = n while (r > 0) { if (nextChar >= nChars) fill() if (nextChar >= nChars) /* EOF */ break if (skipLF) { skipLF = false if (cb!![nextChar] == '\n') { nextChar++ } } val d = (nChars - nextChar).toLong() if (r <= d) { nextChar += r.toInt() r = 0 break } else { r -= d nextChar = nChars } } return n - r } /** * Tells whether this stream is ready to be read. A buffered character * stream is ready if the buffer is not empty, or if the underlying * character stream is ready. * * @throws IOException If an I/O error occurs */ override fun ready(): Boolean { return implReady(); } private fun implReady(): Boolean { ensureOpen() /* * If newline needs to be skipped and the next char to be read * is a newline character, then just skip it right away. */ if (skipLF) {/* Note that in.ready() will return true if and only if the next * read on the stream will not block. */ if (nextChar >= nChars && reader!!.ready()) { fill() } if (nextChar < nChars) { if (cb!![nextChar] == '\n') nextChar++ skipLF = false } } return (nextChar < nChars) || reader!!.ready() } /** * Tells whether this stream supports the mark() operation, which it does. */ override fun markSupported(): Boolean { return true } /** * Marks the present position in the stream. Subsequent calls to reset() * will attempt to reposition the stream to this point. * * @param readAheadLimit Limit on the number of characters that may be * read while still preserving the mark. An attempt * to reset the stream after reading characters * up to this limit or beyond may fail. * A limit value larger than the size of the input * buffer will cause a new buffer to be allocated * whose size is no smaller than limit. * Therefore large values should be used with care. * * @throws IllegalArgumentException If `readAheadLimit < 0` * @throws IOException If an I/O error occurs */ override fun mark(readAheadLimit: Int) { require(readAheadLimit >= 0) { "Read-ahead limit < 0" } implMark(readAheadLimit) } private fun implMark(readAheadLimit: Int) { ensureOpen() this.readAheadLimit = readAheadLimit markedChar = nextChar markedSkipLF = skipLF } /** * Resets the stream to the most recent mark. * * @throws IOException If the stream has never been marked, * or if the mark has been invalidated */ override fun reset() { implReset() } private fun implReset() { ensureOpen() if (markedChar < 0) throw IOException( if ((markedChar == INVALIDATED)) "Mark invalid" else "Stream not marked" ) nextChar = markedChar skipLF = markedSkipLF } override fun close() { implClose() } private fun implClose() { try { reader?.close() } finally { reader = null cb = null } } }
7
null
11
281
4fd2972a008ee39df42c5ee8cb06ff54860d3e7b
14,703
ksoup
Apache License 2.0
mbprotokit/src/main/java/com/daimler/mbprotokit/dto/car/vehicledata/FilterParticleState.kt
Daimler
199,815,262
false
null
package com.daimler.mbprotokit.dto.car.vehicledata enum class FilterParticleState(val id: Int) { HIGH(0), MEDIUM(1), LOW(2); companion object { fun map(id: Int?) = values().find { id == it.id } fun map(): (Int?) -> FilterParticleState? = { map(it) } } }
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
313
MBSDK-Mobile-Android
MIT License
app/src/main/java/com/anytypeio/anytype/ui/sets/modals/SetObjectSetRecordNameFragment.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.ui.sets.modals import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_FLAG_AUTO_CORRECT import android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES import android.view.LayoutInflater import android.view.ViewGroup import android.widget.EditText import androidx.appcompat.widget.AppCompatImageButton import androidx.core.os.bundleOf import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.anytypeio.anytype.R import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.primitives.SpaceId import com.anytypeio.anytype.core_utils.ext.argString import com.anytypeio.anytype.databinding.FragmentSetObjectSetRecordNameBinding import com.anytypeio.anytype.di.common.componentManager import com.anytypeio.anytype.di.feature.DefaultComponentParam import com.anytypeio.anytype.presentation.sets.ObjectSetRecordViewModel import com.anytypeio.anytype.presentation.sets.ObjectSetRecordViewModel.Command import com.anytypeio.anytype.ui.editor.EditorFragment import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class SetObjectSetRecordNameFragment : SetObjectCreateRecordFragmentBase<FragmentSetObjectSetRecordNameBinding>() { override val textInputType: Int = TYPE_CLASS_TEXT or TYPE_TEXT_FLAG_CAP_SENTENCES or TYPE_TEXT_FLAG_AUTO_CORRECT override val textInputField: EditText get() = binding.textInputField override val button: AppCompatImageButton get() = binding.icExpand @Inject lateinit var factory: ObjectSetRecordViewModel.Factory override val vm: ObjectSetRecordViewModel by viewModels { factory } private val target: String get() = argString(TARGET_KEY) override fun onStart(scope: CoroutineScope) { super.onStart(scope) scope.launch { subscribeCommands() } } private suspend fun subscribeCommands() { vm.commands.collect { command -> when (command) { is Command.OpenObject -> { findNavController().navigate( R.id.objectNavigation, EditorFragment.args( ctx = command.ctx, space = command.space ) ) } } } } override fun onButtonClicked() { vm.onButtonClicked( target = target, input = textInputField.text.toString(), space = space ) } override fun onKeyboardActionDone() { vm.onActionDone( target = target, input = textInputField.text.toString(), space = space ) } override fun inflateBinding( inflater: LayoutInflater, container: ViewGroup? ): FragmentSetObjectSetRecordNameBinding = FragmentSetObjectSetRecordNameBinding.inflate( inflater, container, false ) override fun injectDependencies() { componentManager() .objectSetRecordComponent.get( DefaultComponentParam( ctx = ctx, space = SpaceId(space) ) ) .inject(this) } override fun releaseDependencies() { componentManager().objectSetRecordComponent.release() } companion object { private const val ARG_CTX_KEY = "arg.set-object-record-name.ctx" private const val ARG_SPACE_KEY = "arg.set-object-record-name.space" fun args( ctx: Id, space: Id ) = bundleOf( ARG_CTX_KEY to ctx, ARG_SPACE_KEY to space ) } }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
3,759
anytype-kotlin
RSA Message-Digest License
src/main/kotlin/no/nav/hm/grunndata/db/indexer/AgreementIndexer.kt
navikt
555,213,385
false
null
package no.nav.hm.grunndata.db.indexer import io.micronaut.context.annotation.Value import jakarta.inject.Singleton import org.opensearch.action.bulk.BulkResponse import org.slf4j.LoggerFactory @Singleton class AgreementIndexer(private val indexer: Indexer, @Value("\${AGREEMENT_ALIASNAME:agreement}") private val aliasName: String, @Value("\${AGREEMENT_INDEXNAME:agreement_202302}") private val indexName: String ) { companion object { private val LOG = LoggerFactory.getLogger(AgreementIndexer::class.java) } init { try { indexer.initIndex(indexName) indexer.initAlias(aliasName,indexName) } catch (e: Exception) { LOG.error("OpenSearch might not be ready ${e.message}, will wait 10s and retry") Thread.sleep(10000) indexer.initIndex(indexName) indexer.initAlias(aliasName,indexName) } } fun index(docs: List<AgreementDoc>): BulkResponse { return indexer.index(docs, indexName) } fun index(doc: AgreementDoc): BulkResponse { return indexer.index(listOf(doc), indexName) } fun index(doc: AgreementDoc, indexName: String): BulkResponse { return indexer.index(listOf(doc), indexName) } fun index(docs: List<AgreementDoc>, indexName: String): BulkResponse { return indexer.index(docs,indexName) } fun createIndex(indexName: String): Boolean = indexer.createIndex(indexName) fun updateAlias(indexName: String): Boolean = indexer.updateAlias(indexName,aliasName) fun indexExists(indexName: String): Boolean = indexer.indexExists(indexName) }
0
Kotlin
0
1
72d24067e6263f57ed34f8a85bcdf1ac6cab4c93
1,687
hm-grunndata-db
MIT License