content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.io
// used in Go
fun oioClientBootstrap() = com.intellij.util.io.oioClientBootstrap() | platform/platform-impl/src/org/jetbrains/io/netty.kt | 3153748786 |
// WITH_RUNTIME
import java.io.File
import java.io.FileFilter
fun foo(filter: FileFilter) {}
fun bar() {
foo(<caret>object: FileFilter {
override fun accept(file: File) = file.name.startsWith("a")
})
}
| plugins/kotlin/idea/tests/testData/intentions/objectLiteralToLambda/ExpressionBody.kt | 1944979452 |
/*
* Copyright (c) 2016-2018 ayatk.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ayatk.biblio.data.remote
import com.ayatk.biblio.data.remote.entity.NarouEpisode
import com.ayatk.biblio.data.remote.entity.NarouIndex
import com.ayatk.biblio.data.remote.entity.NarouNovel
import com.ayatk.biblio.data.remote.entity.NarouRanking
import com.ayatk.biblio.data.remote.service.NarouApiService
import com.ayatk.biblio.data.remote.service.NarouService
import com.ayatk.biblio.data.remote.util.HtmlParser
import com.ayatk.biblio.data.remote.util.QueryTime
import com.ayatk.biblio.di.scope.Narou
import com.ayatk.biblio.infrastructure.database.entity.enums.RankingType
import io.reactivex.Flowable
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NarouDataStoreImpl @Inject constructor(
private val htmlParser: HtmlParser,
private val narouApiService: NarouApiService,
@Narou private val narouService: NarouService
) : NarouDataStore {
override fun getNovel(query: Map<String, String>): Flowable<List<NarouNovel>> =
narouApiService.getNovel(query)
// 0番目にall nullの要素が入ってしまってるのでdrop(1)しないと落ちる
.map { novels -> novels.drop(1) }
override fun getIndex(code: String): Flowable<List<NarouIndex>> =
narouService.getTableOfContents(code.toLowerCase())
.map { htmlParser.parseTableOfContents(code, it) }
override fun getEpisode(code: String, page: Int): Flowable<NarouEpisode> =
narouService.getPage(code, page)
.map { htmlParser.parsePage(code, it, page) }
override fun getShortStory(code: String): Flowable<NarouEpisode> =
narouService.getSSPage(code)
.map { htmlParser.parsePage(code, it, 1) }
override fun getRanking(rankingType: RankingType, date: Date): Flowable<List<NarouRanking>> {
var dateStr = ""
when (rankingType) {
RankingType.DAILY -> dateStr = QueryTime.day2String(date)
RankingType.WEEKLY -> dateStr = QueryTime.day2Tuesday(date)
RankingType.MONTHLY -> dateStr = QueryTime.day2MonthOne(date)
RankingType.QUARTET -> dateStr = QueryTime.day2MonthOne(date)
RankingType.ALL -> IllegalArgumentException("Not arrowed ALL type request")
}
return narouApiService.getRanking(dateStr + rankingType.type)
}
}
| app/src/main/kotlin/com/ayatk/biblio/data/remote/NarouDataStoreImpl.kt | 435282115 |
// "Surround with null check" "false"
// ACTION: Add non-null asserted (!!) call
// ACTION: Convert to run
// ACTION: Convert to with
// ACTION: Do not show return expression hints
// ACTION: Introduce local variable
// ACTION: Replace with safe (?.) call
// ERROR: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?
class My(var x: Int?) {
fun foo() {
x<caret>.hashCode()
}
} | plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/unstableValue.kt | 1044709932 |
package com.bijoysingh.quicknote.scarlet
import com.bijoysingh.quicknote.Scarlet.Companion.gDrive
import com.bijoysingh.quicknote.Scarlet.Companion.remoteDatabaseStateController
import com.maubis.scarlet.base.core.folder.MaterialFolderActor
import com.maubis.scarlet.base.database.room.folder.Folder
class ScarletFolderActor(folder: Folder) : MaterialFolderActor(folder) {
private val notifyChange: () -> Unit = {
gDrive?.notifyChange()
}
override fun onlineSave() {
super.onlineSave()
remoteDatabaseStateController?.notifyInsert(folder, notifyChange)
}
override fun delete() {
super.delete()
when {
gDrive?.isValid() == true -> remoteDatabaseStateController?.notifyRemove(folder, notifyChange)
else -> remoteDatabaseStateController?.stopTrackingItem(folder, notifyChange)
}
}
} | scarlet/src/main/java/com/bijoysingh/quicknote/scarlet/ScarletFolderActor.kt | 342895350 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.blockingCallsDetection.BlockingMethodInNonBlockingContextInspection
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.MavenDependencyUtil
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.kotlin.idea.base.test.TestRoot
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
private val ktProjectDescriptor = object : KotlinWithJdkAndRuntimeLightProjectDescriptor(
listOf(TestKotlinArtifacts.kotlinStdlib), listOf(TestKotlinArtifacts.kotlinStdlibSources)
) {
override fun configureModule(module: Module, model: ModifiableRootModel) {
super.configureModule(module, model)
MavenDependencyUtil.addFromMaven(model, "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2")
MavenDependencyUtil.addFromMaven(model, "org.jetbrains:annotations:23.0.0")
}
}
@TestRoot("idea/tests")
@TestMetadata("testData/inspections/blockingCallsDetection")
@RunWith(JUnit38ClassRunner::class)
class CoroutineNonBlockingContextDetectionTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = ktProjectDescriptor
override fun setUp() {
super.setUp()
myFixture.enableInspections(BlockingMethodInNonBlockingContextInspection(false))
}
fun testSimpleCoroutineScope() {
doTest("InsideCoroutine.kt")
}
fun testCoroutineContextCheck() {
doTest("ContextCheck.kt")
}
fun testLambdaReceiverType() {
doTest("LambdaReceiverTypeCheck.kt")
}
fun testDispatchersTypeDetection() {
doTest("DispatchersTypeCheck.kt")
}
private fun doTest(fileName: String) {
myFixture.configureByFile(fileName)
myFixture.testHighlighting(true, false, false, fileName)
}
fun testLambdaInSuspendDeclaration() {
myFixture.configureByFile("LambdaAssignmentCheck.kt")
myFixture.testHighlighting(true, false, false, "LambdaAssignmentCheck.kt")
}
fun testFlowOn() {
myFixture.configureByFile("FlowOn.kt")
myFixture.testHighlighting(true, false, false, "FlowOn.kt")
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/inspections/CoroutineNonBlockingontextDetectionTest.kt | 343809140 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.embedding
import android.util.LayoutDirection.LOCALE
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import androidx.core.util.Preconditions.checkArgument
import androidx.core.util.Preconditions.checkArgumentNonnegative
/**
* Split configuration rules for activity pairs. Define when activities that were launched on top of
* each other should be shown side-by-side, and the visual properties of such splits. Can be set
* either statically via [SplitController.Companion.initialize] or at runtime via
* [SplitController.registerRule]. The rules can only be applied to activities that
* belong to the same application and are running in the same process. The rules are always
* applied only to activities that will be started after the rules were set.
*/
class SplitPairRule : SplitRule {
/**
* Filters used to choose when to apply this rule. The rule may be used if any one of the
* provided filters matches.
*/
val filters: Set<SplitPairFilter>
/**
* Determines what happens with the primary container when all activities are finished in the
* associated secondary container.
* @see SplitRule.SplitFinishBehavior
*/
@SplitFinishBehavior
val finishPrimaryWithSecondary: Int
/**
* Determines what happens with the secondary container when all activities are finished in the
* associated primary container.
* @see SplitRule.SplitFinishBehavior
*/
@SplitFinishBehavior
val finishSecondaryWithPrimary: Int
/**
* If there is an existing split with the same primary container, indicates whether the
* existing secondary container on top and all activities in it should be destroyed when a new
* split is created using this rule. Otherwise the new secondary will appear on top by default.
*/
val clearTop: Boolean
internal constructor(
filters: Set<SplitPairFilter>,
@SplitFinishBehavior finishPrimaryWithSecondary: Int = FINISH_NEVER,
@SplitFinishBehavior finishSecondaryWithPrimary: Int = FINISH_ALWAYS,
clearTop: Boolean = false,
@IntRange(from = 0) minWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP,
@IntRange(from = 0) minSmallestWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP,
@FloatRange(from = 0.0, to = 1.0) splitRatio: Float = 0.5f,
@LayoutDirection layoutDirection: Int = LOCALE
) : super(minWidthDp, minSmallestWidthDp, splitRatio, layoutDirection) {
checkArgumentNonnegative(minWidthDp, "minWidthDp must be non-negative")
checkArgumentNonnegative(minSmallestWidthDp, "minSmallestWidthDp must be non-negative")
checkArgument(splitRatio in 0.0..1.0, "splitRatio must be in 0.0..1.0 range")
this.filters = filters.toSet()
this.clearTop = clearTop
this.finishPrimaryWithSecondary = finishPrimaryWithSecondary
this.finishSecondaryWithPrimary = finishSecondaryWithPrimary
}
/**
* Builder for [SplitPairRule].
*
* @param filters See [SplitPairRule.filters].
*/
class Builder(
private val filters: Set<SplitPairFilter>,
) {
@IntRange(from = 0)
private var minWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP
@IntRange(from = 0)
private var minSmallestWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP
@SplitFinishBehavior
private var finishPrimaryWithSecondary: Int = FINISH_NEVER
@SplitFinishBehavior
private var finishSecondaryWithPrimary: Int = FINISH_ALWAYS
private var clearTop: Boolean = false
@FloatRange(from = 0.0, to = 1.0)
private var splitRatio: Float = 0.5f
@LayoutDirection
private var layoutDirection: Int = LOCALE
/**
* @see SplitPairRule.minWidthDp
*/
fun setMinWidthDp(@IntRange(from = 0) minWidthDp: Int): Builder =
apply { this.minWidthDp = minWidthDp }
/**
* @see SplitPairRule.minSmallestWidthDp
*/
fun setMinSmallestWidthDp(@IntRange(from = 0) minSmallestWidthDp: Int): Builder =
apply { this.minSmallestWidthDp = minSmallestWidthDp }
/**
* @see SplitPairRule.finishPrimaryWithSecondary
*/
fun setFinishPrimaryWithSecondary(
@SplitFinishBehavior finishPrimaryWithSecondary: Int
): Builder =
apply { this.finishPrimaryWithSecondary = finishPrimaryWithSecondary }
/**
* @see SplitPairRule.finishSecondaryWithPrimary
*/
fun setFinishSecondaryWithPrimary(
@SplitFinishBehavior finishSecondaryWithPrimary: Int
): Builder =
apply { this.finishSecondaryWithPrimary = finishSecondaryWithPrimary }
/**
* @see SplitPairRule.clearTop
*/
@SuppressWarnings("MissingGetterMatchingBuilder")
fun setClearTop(clearTop: Boolean): Builder =
apply { this.clearTop = clearTop }
/**
* @see SplitPairRule.splitRatio
*/
fun setSplitRatio(@FloatRange(from = 0.0, to = 1.0) splitRatio: Float): Builder =
apply { this.splitRatio = splitRatio }
/**
* @see SplitPairRule.layoutDirection
*/
fun setLayoutDirection(@LayoutDirection layoutDirection: Int): Builder =
apply { this.layoutDirection = layoutDirection }
fun build() = SplitPairRule(filters, finishPrimaryWithSecondary, finishSecondaryWithPrimary,
clearTop, minWidthDp, minSmallestWidthDp, splitRatio, layoutDirection)
}
/**
* Creates a new immutable instance by adding a filter to the set.
* @see filters
*/
internal operator fun plus(filter: SplitPairFilter): SplitPairRule {
val newSet = mutableSetOf<SplitPairFilter>()
newSet.addAll(filters)
newSet.add(filter)
return Builder(newSet.toSet())
.setMinWidthDp(minWidthDp)
.setMinSmallestWidthDp(minSmallestWidthDp)
.setFinishPrimaryWithSecondary(finishPrimaryWithSecondary)
.setFinishSecondaryWithPrimary(finishSecondaryWithPrimary)
.setClearTop(clearTop)
.setSplitRatio(splitRatio)
.setLayoutDirection(layoutDirection)
.build()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SplitPairRule) return false
if (!super.equals(other)) return false
if (filters != other.filters) return false
if (finishPrimaryWithSecondary != other.finishPrimaryWithSecondary) return false
if (finishSecondaryWithPrimary != other.finishSecondaryWithPrimary) return false
if (clearTop != other.clearTop) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + filters.hashCode()
result = 31 * result + finishPrimaryWithSecondary.hashCode()
result = 31 * result + finishSecondaryWithPrimary.hashCode()
result = 31 * result + clearTop.hashCode()
return result
}
} | window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt | 3892183027 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.viewpager2.integration.testapp
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
private const val KEY_ITEM_TEXT = "androidx.viewpager2.integration.testapp.KEY_ITEM_TEXT"
private const val KEY_CLICK_COUNT = "androidx.viewpager2.integration.testapp.KEY_CLICK_COUNT"
/**
* Shows how to use [FragmentStateAdapter.notifyDataSetChanged] with [ViewPager2]. Here [ViewPager2]
* represents pages as [Fragment]s.
*/
class MutableCollectionFragmentActivity : MutableCollectionBaseActivity() {
override fun createViewPagerAdapter(): RecyclerView.Adapter<*> {
val items = items // avoids resolving the ViewModel multiple times
return object : FragmentStateAdapter(this) {
override fun createFragment(position: Int): PageFragment {
val itemId = items.itemId(position)
val itemText = items.getItemById(itemId)
return PageFragment.create(itemText)
}
override fun getItemCount(): Int = items.size
override fun getItemId(position: Int): Long = items.itemId(position)
override fun containsItem(itemId: Long): Boolean = items.contains(itemId)
}
}
}
class PageFragment : Fragment() {
private lateinit var textViewItemText: TextView
private lateinit var textViewCount: TextView
private lateinit var buttonCountIncrease: Button
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.item_mutable_collection, container, false)
textViewItemText = view.findViewById(R.id.textViewItemText)
textViewCount = view.findViewById(R.id.textViewCount)
buttonCountIncrease = view.findViewById(R.id.buttonCountIncrease)
textViewItemText.text = arguments?.getString(KEY_ITEM_TEXT) ?: throw IllegalStateException()
fun updateCountText(count: Int) {
textViewCount.text = "$count"
}
updateCountText(savedInstanceState?.getInt(KEY_CLICK_COUNT) ?: 0)
buttonCountIncrease.setOnClickListener {
updateCountText(clickCount() + 1)
}
return view
}
/**
* [FragmentStateAdapter] minimizes the number of [Fragment]s kept in memory by saving state of
[Fragment]s that are no longer near the viewport. Here we demonstrate this behavior by relying
on it to persist click counts through configuration changes (rotation) and data-set changes
(when items are added or removed).
*/
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(KEY_CLICK_COUNT, clickCount())
}
private fun clickCount(): Int {
return "${textViewCount.text}".toInt()
}
companion object {
fun create(itemText: String) =
PageFragment().apply {
arguments = Bundle(1).apply {
putString(KEY_ITEM_TEXT, itemText)
}
}
}
}
| viewpager2/integration-tests/testapp/src/main/java/androidx/viewpager2/integration/testapp/MutableCollectionFragmentActivity.kt | 1093906800 |
package taiwan.no1.app.ssfm.features.chart
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.View
import com.devrapid.kotlinknifer.glideListener
import com.devrapid.kotlinknifer.palette
import com.devrapid.kotlinknifer.toTimeString
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.trello.rxlifecycle2.LifecycleProvider
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.features.base.BaseViewModel
import taiwan.no1.app.ssfm.misc.constants.RxBusTag
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_CLICK
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_LONG_CLICK
import taiwan.no1.app.ssfm.misc.extension.changeState
import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor
import taiwan.no1.app.ssfm.misc.extension.gColor
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.MusicPlayerHelper
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playMusic
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import weian.cheng.mediaplayerwithexoplayer.MusicPlayerState
/**
* @author jieyi
* @since 11/24/17
*/
class RecyclerViewRankChartDetailViewModel(private val addPlaylistItemCase: AddPlaylistItemCase,
private var item: PlaylistItemEntity,
private var index: Int) : BaseViewModel() {
val trackName by lazy { ObservableField<String>() }
val trackDuration by lazy { ObservableField<String>() }
val trackIndex by lazy { ObservableField<String>() }
val artistName by lazy { ObservableField<String>() }
val trackCover by lazy { ObservableField<String>() }
val isPlaying by lazy { ObservableBoolean(false) }
val layoutBackground by lazy { ObservableField<Drawable>() }
val imageCallback = glideListener<Bitmap> {
onResourceReady = { resource, _, _, _, _ ->
resource.palette(24).let {
val start = gAlphaIntColor(it.vibrantSwatch?.rgb ?: gColor(R.color.colorSimilarPrimaryDark), 0.65f)
val darkColor = gAlphaIntColor(it.darkVibrantSwatch?.rgb ?: gColor(R.color.colorPrimaryDark), 0.65f)
val background = GradientDrawable(GradientDrawable.Orientation.TL_BR, intArrayOf(start, darkColor))
layoutBackground.set(background)
}
false
}
}
private var clickedIndex = -1
init {
refreshView()
}
//region Lifecycle
override fun <E> onAttach(lifecycleProvider: LifecycleProvider<E>) {
super.onAttach(lifecycleProvider)
RxBus.get().register(this)
}
override fun onDetach() {
super.onDetach()
RxBus.get().unregister(this)
}
//endregion
fun setMusicItem(item: PlaylistItemEntity, index: Int) {
this.item = item
this.index = index
refreshView()
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartRankChartDetailFragment.addToPlaylist]
*/
fun trackOnClick(view: View) {
lifecycleProvider.playMusic(addPlaylistItemCase, item, index)
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.openBottomSheet]
*/
fun trackOnLongClick(view: View): Boolean {
RxBus.get().post(VIEWMODEL_TRACK_LONG_CLICK, item)
return true
}
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun changeToStopIcon(uri: String) {
isPlaying.set(uri == item.trackUri)
}
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun notifyClickIndex(index: Integer) {
clickedIndex = index.toInt()
}
/**
* @param state
*
* @event_from [MusicPlayerHelper.setPlayerListener]
*/
@Subscribe(tags = [(Tag(RxBusTag.MUSICPLAYER_STATE_CHANGED))])
fun playerStateChanged(state: MusicPlayerState) = isPlaying.changeState(state, index, clickedIndex)
private fun refreshView() {
item.let {
isPlaying.set(playerHelper.isCurrentUri(it.trackUri) && playerHelper.isPlaying)
trackName.set(it.trackName)
trackDuration.set(it.duration.toTimeString())
trackIndex.set(index.toString())
artistName.set(it.artistName)
trackCover.set(it.coverUrl)
}
}
} | app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/RecyclerViewRankChartDetailViewModel.kt | 2412441036 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.navigation
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.Navigator
import androidx.navigation.createGraph
import androidx.navigation.compose.LocalOwnersProvider
import androidx.navigation.get
import androidx.wear.compose.material.SwipeToDismissValue
import androidx.wear.compose.material.SwipeToDismissBox
import androidx.wear.compose.material.SwipeToDismissBoxState
import androidx.wear.compose.material.SwipeToDismissKeys
import androidx.wear.compose.material.edgeSwipeToDismiss
import androidx.wear.compose.material.rememberSwipeToDismissBoxState
/**
* Provides a place in the Compose hierarchy for self-contained navigation to occur,
* with backwards navigation provided by a swipe gesture.
*
* Once this is called, any Composable within the given [NavGraphBuilder] can be navigated to from
* the provided [navController].
*
* The builder passed into this method is [remember]ed. This means that for this NavHost, the
* contents of the builder cannot be changed.
*
* Content is displayed within a [SwipeToDismissBox], showing the current navigation level.
* During a swipe-to-dismiss gesture, the previous navigation level (if any) is shown in
* the background.
*
* Example of a [SwipeDismissableNavHost] alternating between 2 screens:
* @sample androidx.wear.compose.navigation.samples.SimpleNavHost
*
* Example of a [SwipeDismissableNavHost] for which a destination has a named argument:
* @sample androidx.wear.compose.navigation.samples.NavHostWithNamedArgument
*
* @param navController The navController for this host
* @param startDestination The route for the start destination
* @param modifier The modifier to be applied to the layout
* @param state State containing information about ongoing swipe and animation.
* @param route The route for the graph
* @param builder The builder used to construct the graph
*/
@Composable
public fun SwipeDismissableNavHost(
navController: NavHostController,
startDestination: String,
modifier: Modifier = Modifier,
state: SwipeDismissableNavHostState = rememberSwipeDismissableNavHostState(),
route: String? = null,
builder: NavGraphBuilder.() -> Unit
) =
SwipeDismissableNavHost(
navController,
remember(route, startDestination, builder) {
navController.createGraph(startDestination, route, builder)
},
modifier,
state = state,
)
/**
* Provides a place in the Compose hierarchy for self-contained navigation to occur,
* with backwards navigation provided by a swipe gesture.
*
* Once this is called, any Composable within the given [NavGraphBuilder] can be navigated to from
* the provided [navController].
*
* The builder passed into this method is [remember]ed. This means that for this NavHost, the
* contents of the builder cannot be changed.
*
* Content is displayed within a [SwipeToDismissBox], showing the current navigation level.
* During a swipe-to-dismiss gesture, the previous navigation level (if any) is shown in
* the background.
*
* Example of a [SwipeDismissableNavHost] alternating between 2 screens:
* @sample androidx.wear.compose.navigation.samples.SimpleNavHost
*
* Example of a [SwipeDismissableNavHost] for which a destination has a named argument:
* @sample androidx.wear.compose.navigation.samples.NavHostWithNamedArgument
*
* @param navController [NavHostController] for this host
* @param graph Graph for this host
* @param modifier [Modifier] to be applied to the layout
* @param state State containing information about ongoing swipe and animation.
*
* @throws IllegalArgumentException if no WearNavigation.Destination is on the navigation backstack.
*/
@Composable
public fun SwipeDismissableNavHost(
navController: NavHostController,
graph: NavGraph,
modifier: Modifier = Modifier,
state: SwipeDismissableNavHostState = rememberSwipeDismissableNavHostState(),
) {
val lifecycleOwner = LocalLifecycleOwner.current
val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"SwipeDismissableNavHost requires a ViewModelStoreOwner to be provided " +
"via LocalViewModelStoreOwner"
}
val onBackPressedDispatcherOwner = LocalOnBackPressedDispatcherOwner.current
val onBackPressedDispatcher = onBackPressedDispatcherOwner?.onBackPressedDispatcher
// Setup the navController with proper owners
navController.setLifecycleOwner(lifecycleOwner)
navController.setViewModelStore(viewModelStoreOwner.viewModelStore)
if (onBackPressedDispatcher != null) {
navController.setOnBackPressedDispatcher(onBackPressedDispatcher)
}
// Ensure that the NavController only receives back events while
// the NavHost is in composition
DisposableEffect(navController) {
navController.enableOnBackPressed(true)
onDispose {
navController.enableOnBackPressed(false)
}
}
// Then set the graph
navController.graph = graph
val stateHolder = rememberSaveableStateHolder()
// Find the WearNavigator, returning early if it isn't found
// (such as is the case when using TestNavHostController).
val wearNavigator = navController.navigatorProvider.get<Navigator<out NavDestination>>(
WearNavigator.NAME
) as? WearNavigator ?: return
val backStack by wearNavigator.backStack.collectAsState()
val transitionsInProgress by wearNavigator.transitionsInProgress.collectAsState()
var initialContent by remember { mutableStateOf(true) }
val previous = if (backStack.size <= 1) null else backStack[backStack.lastIndex - 1]
// Get the current navigation backstack entry. If the backstack is empty, it could be because
// no WearNavigator.Destinations were added to the navigation backstack (be sure to build
// the NavGraph using androidx.wear.compose.navigation.composable) or because the last entry
// was popped prior to navigating (instead, use navigate with popUpTo).
val current = if (backStack.isNotEmpty()) backStack.last() else throw IllegalArgumentException(
"The WearNavigator backstack is empty, there is no navigation destination to display."
)
val swipeState = state.swipeToDismissBoxState
LaunchedEffect(swipeState.currentValue) {
// This effect operates when the swipe gesture is complete:
// 1) Resets the screen offset (otherwise, the next destination is draw off-screen)
// 2) Pops the navigation back stack to return to the previous level
if (swipeState.currentValue == SwipeToDismissValue.Dismissed) {
swipeState.snapTo(SwipeToDismissValue.Default)
navController.popBackStack()
}
}
LaunchedEffect(swipeState.isAnimationRunning) {
// This effect marks the transitions completed when swipe animations finish,
// so that the navigation backstack entries can go to Lifecycle.State.RESUMED.
if (swipeState.isAnimationRunning == false) {
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
}
}
SwipeToDismissBox(
state = swipeState,
modifier = Modifier,
hasBackground = previous != null,
backgroundKey = previous?.id ?: SwipeToDismissKeys.Background,
contentKey = current.id,
content = { isBackground ->
BoxedStackEntryContent(if (isBackground) previous else current, stateHolder, modifier)
}
)
DisposableEffect(previous, current) {
if (initialContent) {
// There are no animations for showing the initial content, so mark transitions complete,
// allowing the navigation backstack entry to go to Lifecycle.State.RESUMED.
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
initialContent = false
}
onDispose {
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
}
}
}
/**
* State for [SwipeDismissableNavHost]
*
* @param swipeToDismissBoxState State for [SwipeToDismissBox], which is used to support the
* swipe-to-dismiss gesture in [SwipeDismissableNavHost] and can also be used to support
* edge-swiping, using [edgeSwipeToDismiss].
*/
public class SwipeDismissableNavHostState(
internal val swipeToDismissBoxState: SwipeToDismissBoxState
)
/**
* Create a [SwipeToDismissBoxState] and remember it.
*
* @param swipeToDismissBoxState State for [SwipeToDismissBox], which is used to support the
* swipe-to-dismiss gesture in [SwipeDismissableNavHost] and can also be used to support
* edge-swiping, using [edgeSwipeToDismiss].
*/
@Composable
public fun rememberSwipeDismissableNavHostState(
swipeToDismissBoxState: SwipeToDismissBoxState = rememberSwipeToDismissBoxState(),
): SwipeDismissableNavHostState {
return remember(swipeToDismissBoxState) {
SwipeDismissableNavHostState(swipeToDismissBoxState)
}
}
@Composable
private fun BoxedStackEntryContent(
entry: NavBackStackEntry?,
saveableStateHolder: SaveableStateHolder,
modifier: Modifier = Modifier,
) {
if (entry != null) {
var lifecycleState by remember {
mutableStateOf(entry.lifecycle.currentState)
}
DisposableEffect(entry.lifecycle) {
val observer = LifecycleEventObserver { _, event ->
lifecycleState = event.targetState
}
entry.lifecycle.addObserver(observer)
onDispose {
entry.lifecycle.removeObserver(observer)
}
}
if (lifecycleState.isAtLeast(Lifecycle.State.CREATED)) {
Box(modifier, propagateMinConstraints = true) {
val destination = entry.destination as WearNavigator.Destination
entry.LocalOwnersProvider(saveableStateHolder) {
destination.content(entry)
}
}
}
}
}
| wear/compose/compose-navigation/src/main/java/androidx/wear/compose/navigation/SwipeDismissableNavHost.kt | 552337745 |
fun f(c: JavaClassInvoke) {
c()
}
fun foo(o: JavaClassInvoke.OtherJavaClass) {
o()
JavaClassInvoke.OtherJavaClass.OJC()
}
fun foo() {
JavaClassInvoke.INSTANCE()
JavaClassInvoke.AnotherOther.INSTANCE()
JavaClassInvoke.JavaOther.INSTANCE()
JavaClassInvoke.AnotherOther::class.java
}
| plugins/kotlin/idea/tests/testData/findUsages/java/findJavaMethodUsages/javaInvoke.0.kt | 262718856 |
// "Replace with safe (?.) call" "false"
// WITH_STDLIB
// ACTION: Add non-null asserted (!!) call
// ACTION: Replace overloaded operator with function call
// ACTION: Replace with ordinary assignment
// ERROR: Operator call corresponds to a dot-qualified call 'map[3].plusAssign(5)' which is not allowed on a nullable receiver 'map[3]'.
fun test(map: MutableMap<Int, Int>) {
map[3] +=<caret> 5
}
| plugins/kotlin/idea/tests/testData/quickfix/replaceInfixOrOperatorCall/plusAssignOnMutableMap.kt | 2143047168 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest
enum class GHPullRequestMergeableState {
CONFLICTING, MERGEABLE, UNKNOWN
} | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestMergeableState.kt | 1900964023 |
package com.onyx.persistence.query
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
import com.onyx.network.connection.Connection
import com.onyx.network.push.PushSubscriber
import com.onyx.network.push.PushPublisher
import com.onyx.network.push.PushConsumer
import com.onyx.exception.BufferingException
import java.nio.channels.ByteChannel
import java.util.Objects
/**
* Created by Tim Osborn on 3/27/17.
*
* This is a 3 for one. It contains the push subscriber information, consumer for the client, and a
* base query listener.
*
*/
class RemoteQueryListener<in T>(private val baseListener: QueryListener<T>? = null) : BufferStreamable, QueryListener<T>, PushSubscriber, PushConsumer {
// Transfer information
override var pushObjectId: Long = 0
override var packet: Any? = null
override var subscribeEvent: Byte = 1
// Publisher information
@Transient
override var connection: Connection? = null
@Transient
override var channel: ByteChannel? = null
@Transient
private var pushPublisher: PushPublisher? = null
/**
* Read from buffer stream
* @param buffer Buffer Stream to read from
*/
@Throws(BufferingException::class)
override fun read(buffer: BufferStream) {
pushObjectId = buffer.long
packet = buffer.value
subscribeEvent = buffer.byte
}
/**
* Write to buffer stream
* @param buffer Buffer IO Stream to write to
*/
@Throws(BufferingException::class)
override fun write(buffer: BufferStream) {
buffer.putLong(pushObjectId)
buffer.putObject(packet)
buffer.putByte(subscribeEvent)
}
/**
* Server publisher for push notifications
* @param peer Publisher to send messages with
*/
override fun setPushPublisher(peer: PushPublisher) {
this.pushPublisher = peer
}
override fun setSubscriberEvent(event: Byte) {
this.subscribeEvent = event
}
/**
* Item has been modified. This occurs when an entity met the original criteria
* when querying the database and was updated. The updated values still match the criteria
*
* @param item Entity updated via the persistence manager
*
* @since 1.3.0
*/
override fun onItemUpdated(item: T) {
val event = QueryEvent(QueryListenerEvent.UPDATE, item)
this.pushPublisher!!.push(this, event)
}
/**
* Item has been inserted. This occurs when an entity was saved and it meets the query criteria.
*
* @param item Entity inserted via the persistence manager
*
* @since 1.3.0
*/
override fun onItemAdded(item: T) {
val event = QueryEvent(QueryListenerEvent.INSERT, item)
this.pushPublisher!!.push(this, event)
}
/**
* Item has been deleted or no longer meets the criteria of the query.
*
* @param item Entity persisted via the persistence manager
*
* @since 1.3.0
*/
override fun onItemRemoved(item: T) {
val event = QueryEvent(QueryListenerEvent.DELETE, item)
this.pushPublisher!!.push(this, event)
}
/**
* Helped to uniquely identify a subscriber
* @return Hash code of listener and socket channel
*/
override fun hashCode(): Int = Objects.hash(pushObjectId)
/**
* Comparator to see if the listener is uniquely identified. This compares exact identity.
* @param other Object to compare
* @return Whether objects are equal
*/
override fun equals(other: Any?): Boolean = other is RemoteQueryListener<*> && other.pushObjectId == this.pushObjectId
/**
* Accept query events
* @param o packet sent from server
*/
override fun accept(o: Any?) {
@Suppress("UNCHECKED_CAST")
val event = o as QueryEvent<T>
when (event.type){
QueryListenerEvent.INSERT -> baseListener!!.onItemAdded(event.entity!!)
QueryListenerEvent.UPDATE -> baseListener!!.onItemUpdated(event.entity!!)
QueryListenerEvent.DELETE -> baseListener!!.onItemRemoved(event.entity!!)
else -> { }
}
}
}
| onyx-remote-driver/src/main/kotlin/com/onyx/persistence/query/RemoteQueryListener.kt | 1624130033 |
// PROBLEM: none
fun main(args: Array<String>, flag: Boolean): <caret>String {} | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/mainFunctionReturnUnit/topLevel/withMultipleArguments.kt | 1955012393 |
// INTENTION_TEXT: "Put parameters on one line"
// SET_TRUE: ALLOW_TRAILING_COMMA
// SET_INT: RIGHT_MARGIN = 100
// WITH_STDLIB
// AFTER-WARNING: Parameter 'longParameterOne' is never used
// AFTER-WARNING: Parameter 'longParameterTwo' is never used
// AFTER-WARNING: Parameter 'longParameterThree' is never used
fun myFun(
longParameterOne : List < Pair<String, List<Int>> >,
longParameterTwo : List < Pair<String, List<Int>> >,<caret>
longParameterThree : List < Pair<String, List<Int>> >,
) {
}
| plugins/kotlin/idea/tests/testData/intentions/joinParameterList/longParameters2.kt | 564331397 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.java.codeInsight.daemon.inlays
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.java.codeInsight.completion.CompletionHintsTest
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class ExcludeListMethodIntentionTest : LightJavaCodeInsightFixtureTestCase() {
private val default = ParameterNameHintsSettings()
override fun tearDown() {
try {
ParameterNameHintsSettings.getInstance().loadState(default.state)
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
fun `test add to blacklist by alt enter`() {
myFixture.configureByText("a.java", """
class Test {
void test() {
check(<caret>100);
}
void check(int isShow) {}
}
""")
assertHintExistsAndDisappearsAfterIntention()
}
fun `test add elements which has inlays`() {
myFixture.configureByText("a.java", """
class ParamHintsTest {
public static void main(String[] args) {
Mvl(
<caret>Math.abs(1) * 100, 32, 32
);
}
public static double Mvl(double first, double x, double c) {
return Double.NaN;
}
}
""")
assertHintExistsAndDisappearsAfterIntention()
}
private fun assertHintExistsAndDisappearsAfterIntention() {
myFixture.doHighlighting()
val caretOffset = editor.caretModel.offset
val before = editor.inlayModel.getInlineElementsInRange(caretOffset, caretOffset)
assertThat(before).isNotEmpty
val intention = myFixture.getAvailableIntention("Do not show hints for current method")
myFixture.launchAction(intention!!)
myFixture.doHighlighting()
CompletionHintsTest.waitTillAnimationCompletes(editor)
val after = editor.inlayModel.getInlineElementsInRange(caretOffset, caretOffset)
assertThat(after).isEmpty()
}
} | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/inlays/IntentionTest.kt | 1532588872 |
class A() {<caret>} | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyBraces/ClassWithConstructor.kt | 2548274162 |
package org.schabi.newpipe.player.gesture
enum class DisplayPortion {
LEFT, MIDDLE, RIGHT, LEFT_HALF, RIGHT_HALF
}
| app/src/main/java/org/schabi/newpipe/player/gesture/DisplayPortion.kt | 3504711548 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion
import com.intellij.codeInsight.completion.CompletionParameters
import org.jetbrains.kotlin.idea.completion.implCommon.stringTemplates.StringTemplateCompletion
internal object KotlinFirCompletionParametersProvider {
fun provide(parameters: CompletionParameters): KotlinFirCompletionParameters {
val (corrected, type) = correctParameters(parameters) ?: return KotlinFirCompletionParameters.Original(parameters)
return KotlinFirCompletionParameters.Corrected(corrected, parameters, type)
}
private fun correctParameters(parameters: CompletionParameters): Pair<CompletionParameters, KotlinFirCompletionParameters.CorrectionType>? {
val correctParametersForInStringTemplateCompletion =
StringTemplateCompletion.correctParametersForInStringTemplateCompletion(parameters)
?: return null
return correctParametersForInStringTemplateCompletion to KotlinFirCompletionParameters.CorrectionType.BRACES_FOR_STRING_TEMPLATE
}
}
internal sealed class KotlinFirCompletionParameters {
abstract val ijParameters: CompletionParameters
abstract val type: CorrectionType?
internal class Original(
override val ijParameters: CompletionParameters,
) : KotlinFirCompletionParameters() {
override val type: CorrectionType? get() = null
}
internal class Corrected(
override val ijParameters: CompletionParameters,
val original: CompletionParameters,
override val type: CorrectionType,
) : KotlinFirCompletionParameters()
enum class CorrectionType {
BRACES_FOR_STRING_TEMPLATE
}
}
| plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/KotlinFirCompletionParameters.kt | 1818395851 |
// "Wrap with '?.let { ... }' call" "true"
// WITH_STDLIB
interface Str {
val foo: (() -> Unit)?
}
object Str2 {
val foo2: (Str.() -> Unit)? = null
fun bar(s: Str) {
s.<caret>foo()
}
}
| plugins/kotlin/idea/tests/testData/quickfix/wrapWithSafeLetCall/refactorNullableFunctionTypeProperty1.kt | 3406635563 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.test.runner
import org.jetbrains.plugins.gradle.importing.TestGradleBuildScriptBuilder.Companion.buildscript
import org.jetbrains.plugins.gradle.settings.TestRunner
import org.junit.Test
class TestMethodGradleConfigurationProducerTest : GradleConfigurationProducerTestCase() {
@Test
@Throws(Exception::class)
fun `test junit parameterized tests`() {
createProjectSubFile("src/test/java/package1/T1Test.java", """
package package1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class T1Test {
@org.junit.runners.Parameterized.Parameter()
public String param;
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{"param1"}, {"param2"}});
}
@Test
public void testFoo() {
}
}
""".trimIndent())
createProjectSubFile("src/test/java/package1/T2Test.java", """
package package1;
import org.junit.Test;
public class T2Test extends T1Test {
@Test
public void testFoo2() {
}
}
""".trimIndent())
createProjectSubFile("settings.gradle", "")
importProject(buildscript {
withJavaPlugin()
addTestImplementationDependency("junit:junit:4.11")
})
assertModules("project", "project.main", "project.test")
currentExternalProjectSettings.testRunner = TestRunner.GRADLE
assertTestFilter("package1.T1Test", null, ":test --tests \"package1.T1Test\"")
assertTestFilter("package1.T1Test", "testFoo", ":test --tests \"package1.T1Test.testFoo[*]\"")
assertParameterizedLocationTestFilter("package1.T1Test", "testFoo", "param1", ":test --tests \"package1.T1Test.testFoo[*param1*]\"")
assertParameterizedLocationTestFilter("package1.T1Test", "testFoo", "param2", ":test --tests \"package1.T1Test.testFoo[*param2*]\"")
assertTestFilter("package1.T2Test", null, ":test --tests \"package1.T2Test\"")
assertTestFilter("package1.T2Test", "testFoo2", ":test --tests \"package1.T2Test.testFoo2[*]\"")
assertParameterizedLocationTestFilter("package1.T2Test", "testFoo2", "param1", ":test --tests \"package1.T2Test.testFoo2[*param1*]\"")
assertParameterizedLocationTestFilter("package1.T2Test", "testFoo2", "param2", ":test --tests \"package1.T2Test.testFoo2[*param2*]\"")
}
} | plugins/gradle/java/testSources/execution/test/runner/TestMethodGradleConfigurationProducerTest.kt | 2979811593 |
fun main(args: Array<String>) {
val elem<caret>ent = listOf(0.4, null).asSequence().elementAt(2)
} | plugins/kotlin/jvm-debugger/test/testData/sequence/psi/sequence/positive/types/NullableDouble.kt | 2297468504 |
fun kotlinClassWrite() {
Kotlin().field = "aw"
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/members/javaField/KotlinClassWrite.kt | 4120362254 |
// 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.
@file:JvmName("JavaResolutionUtils")
package org.jetbrains.kotlin.idea.caches.resolve.util
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.lightClasses.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.structure.impl.*
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.scopes.MemberScope
fun PsiMethod.getJavaMethodDescriptor(): FunctionDescriptor? = javaResolutionFacade()?.let { getJavaMethodDescriptor(it) }
private fun PsiMethod.getJavaMethodDescriptor(resolutionFacade: ResolutionFacade): FunctionDescriptor? {
val method = originalElement as? PsiMethod ?: return null
if (method.containingClass == null || !Name.isValidIdentifier(method.name)) return null
val resolver = method.getJavaDescriptorResolver(resolutionFacade)
return when {
method.isConstructor -> resolver?.resolveConstructor(JavaConstructorImpl(method))
else -> resolver?.resolveMethod(JavaMethodImpl(method))
}
}
fun PsiClass.getJavaClassDescriptor() = javaResolutionFacade()?.let { getJavaClassDescriptor(it) }
fun PsiClass.getJavaClassDescriptor(resolutionFacade: ResolutionFacade): ClassDescriptor? {
val psiClass = originalElement as? PsiClass ?: return null
return psiClass.getJavaDescriptorResolver(resolutionFacade)?.resolveClass(JavaClassImpl(psiClass))
}
private fun PsiField.getJavaFieldDescriptor(resolutionFacade: ResolutionFacade): PropertyDescriptor? {
val field = originalElement as? PsiField ?: return null
return field.getJavaDescriptorResolver(resolutionFacade)?.resolveField(JavaFieldImpl(field))
}
fun PsiMember.getJavaMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? {
return when (this) {
is PsiClass -> getJavaClassDescriptor(resolutionFacade)
is PsiMethod -> getJavaMethodDescriptor(resolutionFacade)
is PsiField -> getJavaFieldDescriptor(resolutionFacade)
else -> null
}
}
fun PsiMember.getJavaMemberDescriptor(): DeclarationDescriptor? = javaResolutionFacade()?.let { getJavaMemberDescriptor(it) }
fun PsiMember.getJavaOrKotlinMemberDescriptor(): DeclarationDescriptor? =
javaResolutionFacade()?.let { getJavaOrKotlinMemberDescriptor(it) }
fun PsiMember.getJavaOrKotlinMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? {
val callable = unwrapped
return when (callable) {
is PsiMember -> getJavaMemberDescriptor(resolutionFacade)
is KtDeclaration -> {
val descriptor = resolutionFacade.resolveToDescriptor(callable)
if (descriptor is ClassDescriptor && this is PsiMethod) descriptor.unsubstitutedPrimaryConstructor else descriptor
}
else -> null
}
}
fun PsiParameter.getParameterDescriptor(): ValueParameterDescriptor? = javaResolutionFacade()?.let {
getParameterDescriptor(it)
}
fun PsiParameter.getParameterDescriptor(resolutionFacade: ResolutionFacade): ValueParameterDescriptor? {
val method = declarationScope as? PsiMethod ?: return null
val methodDescriptor = method.getJavaMethodDescriptor(resolutionFacade) ?: return null
return methodDescriptor.valueParameters[parameterIndex()]
}
fun PsiClass.resolveToDescriptor(
resolutionFacade: ResolutionFacade,
declarationTranslator: (KtClassOrObject) -> KtClassOrObject? = { it }
): ClassDescriptor? {
return if (this is KtLightClass && this !is KtLightClassForDecompiledDeclaration) {
val origin = this.kotlinOrigin ?: return null
val declaration = declarationTranslator(origin) ?: return null
resolutionFacade.resolveToDescriptor(declaration)
} else {
getJavaClassDescriptor(resolutionFacade)
} as? ClassDescriptor
}
@OptIn(FrontendInternals::class)
private fun PsiElement.getJavaDescriptorResolver(resolutionFacade: ResolutionFacade): JavaDescriptorResolver? {
return resolutionFacade.tryGetFrontendService(this, JavaDescriptorResolver::class.java)
}
private fun JavaDescriptorResolver.resolveMethod(method: JavaMethod): FunctionDescriptor? {
return getContainingScope(method)?.getContributedFunctions(method.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(method)
}
private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstructor): ConstructorDescriptor? {
return resolveClass(constructor.containingClass)?.constructors?.findByJavaElement(constructor)
}
private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? {
return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field)
}
private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? {
val containingClass = resolveClass(member.containingClass)
return if (member.isStatic)
containingClass?.staticScope
else
containingClass?.defaultType?.memberScope
}
private fun <T : DeclarationDescriptorWithSource> Collection<T>.findByJavaElement(javaElement: JavaElement): T? {
return firstOrNull { member ->
val memberJavaElement = (member.original.source as? JavaSourceElement)?.javaElement
when {
memberJavaElement == javaElement ->
true
memberJavaElement is JavaElementImpl<*> && javaElement is JavaElementImpl<*> ->
memberJavaElement.psi.isEquivalentTo(javaElement.psi)
else ->
false
}
}
}
fun PsiElement.hasJavaResolutionFacade(): Boolean = this.originalElement.containingFile != null
fun PsiElement.javaResolutionFacade() =
KotlinCacheService.getInstance(project).getResolutionFacadeByFile(
this.originalElement.containingFile ?: reportCouldNotCreateJavaFacade(),
JvmPlatforms.unspecifiedJvmPlatform
)
private fun PsiElement.reportCouldNotCreateJavaFacade(): Nothing =
runReadAction {
error(
"Could not get javaResolutionFacade for element:\n" +
"same as originalElement = ${this === this.originalElement}" +
"class = ${javaClass.name}, text = $text, containingFile = ${containingFile?.name}\n" +
"originalElement.class = ${originalElement.javaClass.name}, originalElement.text = ${originalElement.text}), " +
"originalElement.containingFile = ${originalElement.containingFile?.name}"
)
}
| plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/JavaResolveExtension.kt | 2400250931 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod
@Suppress("RemoveExplicitTypeArguments")
fun Collection<PsiElement>.collapseReflectedMethods(): Collection<PsiElement> {
return mapTo(mutableSetOf<PsiElement>()) {
(it as? GrReflectedMethod)?.baseMethod ?: it
}
}
fun Collection<PsiElement>.collapseAccessors(): Collection<PsiElement> {
val fields = filterIsInstance<GrField>()
return filter { it !is GrAccessorMethod || it.property !in fields }
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/collapsing.kt | 2108548297 |
fun foo(p1: String, vararg p2: String){}
fun bar(p: String){
foo(<caret>)
}
// ELEMENT: p
| plugins/kotlin/completion/tests/testData/handlers/smart/Comma11.kt | 643507888 |
class KOne : MyJavaClass() {
override fun meth(i: Int, s: String) = Unit
} | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ChangeJavaMethodWithPrimitiveTypeAfter.1.kt | 3738728242 |
package streams.sequence.terminal
fun main(args: Array<String>) {
//Breakpoint!
sequenceOf(1, 2, 3, 2).last { it == 2 }
} | plugins/kotlin/jvm-debugger/test/testData/sequence/streams/sequence/terminal/Last.kt | 1147882792 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiMember
import com.intellij.refactoring.classMembers.MemberDependencyGraph
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.util.classMembers.InterfaceMemberDependencyGraph
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
class KotlinInterfaceMemberDependencyGraph<T : KtNamedDeclaration, M : MemberInfoBase<T>>(
klass: KtClassOrObject
) : MemberDependencyGraph<T, M> {
private val delegateGraph = InterfaceMemberDependencyGraph<PsiMember, MemberInfoBase<PsiMember>>(klass.toLightClass())
override fun memberChanged(memberInfo: M) {
delegateGraph.memberChanged(memberInfo.toJavaMemberInfo() ?: return)
}
@Suppress("UNCHECKED_CAST")
override fun getDependent() = delegateGraph.dependent
.asSequence()
.mapNotNull { it.unwrapped }
.filterIsInstanceTo(LinkedHashSet<KtNamedDeclaration>()) as Set<T>
@Suppress("UNCHECKED_CAST")
override fun getDependenciesOf(member: T): Set<T> {
val psiMember = lightElementForMemberInfo(member) ?: return emptySet()
val psiMemberDependencies = delegateGraph.getDependenciesOf(psiMember) ?: return emptySet()
return psiMemberDependencies
.asSequence()
.mapNotNull { it.unwrapped }
.filterIsInstanceTo(LinkedHashSet<KtNamedDeclaration>()) as Set<T>
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceMemberDependencyGraph.kt | 3055095638 |
package org.jtrim2.build
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.ArrayDeque
import java.util.Deque
object PackageUtils {
fun collectPackageListFromSourceRoot(sourceRoot: Path, result: MutableSet<String>) {
if (!Files.isDirectory(sourceRoot)) {
return
}
val rootCounter = FileCounter()
Files.walkFileTree(sourceRoot, object : FileVisitor<Path> {
private val counters: Deque<FileCounter> = ArrayDeque()
private var topCounter = rootCounter
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
counters.push(topCounter)
topCounter = FileCounter()
return FileVisitResult.CONTINUE
}
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
topCounter.fileCount++
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException?): FileVisitResult {
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (topCounter.fileCount > 0) {
result.add(toPackageName(sourceRoot.relativize(dir)))
}
topCounter = counters.pop()
return FileVisitResult.CONTINUE
}
})
}
private fun toPackageName(relPath: Path): String {
val packageName = StringBuilder()
for (name in relPath) {
if (packageName.isNotEmpty()) {
packageName.append('.')
}
packageName.append(name.toString())
}
return packageName.toString()
}
}
private class FileCounter {
var fileCount = 0
}
| buildSrc/src/main/kotlin/org/jtrim2/build/PackageUtils.kt | 2890959828 |
package sample
fun sampleImplementation() {
val hello = Hello()
hello.method()
} | kotlin/kdoc/samples/method-sample.kt | 1260979763 |
/*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano
import com.charlatano.game.CSGO
import com.charlatano.overlay.Overlay
import com.charlatano.scripts.aim.flatAim
import com.charlatano.scripts.aim.pathAim
import com.charlatano.scripts.bombTimer
import com.charlatano.scripts.boneTrigger
import com.charlatano.scripts.bunnyHop
import com.charlatano.scripts.esp.esp
import com.charlatano.scripts.rcs
import com.charlatano.settings.*
import com.sun.jna.platform.win32.WinNT
import java.io.File
import java.util.*
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory
import kotlin.system.exitProcess
object Charlatano {
const val SETTINGS_DIRECTORY = "settings"
@JvmStatic
fun main(args: Array<String>) {
System.setProperty("jna.nosys", "true")
System.setProperty("idea.io.use.fallback", "true")
System.setProperty("idea.use.native.fs.for.win", "false")
loadSettings()
if (FLICKER_FREE_GLOW) {
PROCESS_ACCESS_FLAGS = PROCESS_ACCESS_FLAGS or
//required by FLICKER_FREE_GLOW
WinNT.PROCESS_VM_OPERATION
}
if (LEAGUE_MODE) {
GLOW_ESP = false
BOX_ESP = false
SKELETON_ESP = false
ENABLE_ESP = false
ENABLE_BOMB_TIMER = false
ENABLE_FLAT_AIM = false
SERVER_TICK_RATE = 128 // most leagues are 128-tick
CACHE_EXPIRE_MILLIS = 4
PROCESS_ACCESS_FLAGS = WinNT.PROCESS_QUERY_INFORMATION or WinNT.PROCESS_VM_READ // all we need
GARBAGE_COLLECT_ON_MAP_START = true // get rid of traces
}
CSGO.initialize()
bunnyHop()
rcs()
esp()
flatAim()
pathAim()
boneTrigger()
bombTimer()
val scanner = Scanner(System.`in`)
while (!Thread.interrupted()) {
when (scanner.nextLine()) {
"exit", "quit" -> exitProcess(0)
"reload" -> loadSettings()
}
}
}
private fun loadSettings() {
val ef = KotlinJsr223DefaultScriptEngineFactory()
val se = ef.scriptEngine
val strings = File(SETTINGS_DIRECTORY).listFiles()!!.map { file -> file.readText() }
for (string in strings) se.eval(string)
val needsOverlay = ENABLE_BOMB_TIMER or (ENABLE_ESP and (SKELETON_ESP or BOX_ESP))
if (!Overlay.opened && needsOverlay) Overlay.open()
}
} | src/main/kotlin/com/charlatano/Charlatano.kt | 4231232105 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable
import org.jetbrains.plugins.groovy.lang.resolve.ElementGroovyResult
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
class LocalVariableProcessor(name: String) : ProcessorWithHints(), GrResolverProcessor<GroovyResolveResult> {
init {
hint(NameHint.KEY, NameHint { name })
hint(ElementClassHint.KEY, ElementClassHint { false })
hint(GroovyResolveKind.HINT_KEY, GroovyResolveKind.Hint { it === GroovyResolveKind.VARIABLE })
}
private var resolveResult: GroovyResolveResult? = null
override val results: List<GroovyResolveResult> get() = resolveResult?.let { listOf(it) } ?: emptyList()
override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (element !is GrVariable || element is GrField) return true
assert(element !is GrBindingVariable)
resolveResult = ElementGroovyResult(element)
return false
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/LocalVariableProcessor.kt | 1298934296 |
package ch.rmy.android.http_shortcuts.utils
import android.content.Context
import android.location.Location
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailabilityLight
import com.google.android.gms.location.CurrentLocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.CancellationTokenSource
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.time.Duration.Companion.seconds
class PlayServicesUtilImpl(
private val context: Context,
) : PlayServicesUtil {
override fun isPlayServicesAvailable(): Boolean =
GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
override suspend fun getLocation(): PlayServicesUtil.Location? =
suspendCancellableCoroutine { continuation ->
val cancellationTokenSource = CancellationTokenSource()
LocationServices.getFusedLocationProviderClient(context)
.getCurrentLocation(
CurrentLocationRequest.Builder()
.setDurationMillis(MAX_LOOKUP_TIME.inWholeMilliseconds)
.build(),
cancellationTokenSource.token,
)
.addOnSuccessListener { location: Location? ->
continuation.resume(location?.toDataObject())
}
.addOnFailureListener { error ->
continuation.resumeWithException(error)
}
continuation.invokeOnCancellation {
cancellationTokenSource.cancel()
}
}
companion object {
private val MAX_LOOKUP_TIME = 20.seconds
private fun Location.toDataObject() =
PlayServicesUtil.Location(
latitude = latitude,
longitude = longitude,
accuracy = if (hasAccuracy()) accuracy else null,
)
}
}
| HTTPShortcuts/app/src/withGoogleServices/kotlin/ch/rmy/android/http_shortcuts/utils/PlayServicesUtilImpl.kt | 89618390 |
package xyz.nulldev.ts.api.v3.models.tracking
data class WTrack(
val displayScore: String?,
val lastChapterRead: Int,
val score: Int?,
val service: Int,
val status: Int,
val totalChapters: Int,
val trackingUrl: String?
) | TachiServer/src/main/java/xyz/nulldev/ts/api/v3/models/tracking/WTrack.kt | 1614528488 |
package pt.joaomneto.titancompanion.adventure.impl.fragments.votv
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.fragment_38votv_adventure_equipment.*
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.impl.VOTVAdventure
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureEquipmentFragment
class VOTVAdventureEquipmentFragment : AdventureEquipmentFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
return inflater.inflate(
R.layout.fragment_38votv_adventure_equipment, container, false
)
}
val adventure
get() = this.activity as VOTVAdventure
override fun onViewCreated(rootView: View, savedInstanceState: Bundle?) {
super.onViewCreated(rootView, savedInstanceState)
spellList.adapter = ArrayAdapter(
adventure,
android.R.layout.simple_list_item_1,
android.R.id.text1,
adventure.spells
)
buttonAddSpell.setOnClickListener(adventure.addSpellListener(spellList))
spellList.setOnItemLongClickListener(adventure.removeSpellListener(spellList))
}
}
| src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/votv/VOTVAdventureEquipmentFragment.kt | 207282711 |
package io.kotest.property
/**
* Given a value, T, this function returns reduced values to be used as candidates
* for shrinking.
*
* A smaller value is defined per Shrinker. For a string it may be considered a string with
* less characters, or less duplication/variation in the characters. For an integer it is typically
* considered a smaller value with a positive sign.
*
* Shrinkers can return one or more values in a shrink step. Shrinkers can
* return more than one value if there is no single "best path". For example,
* when shrinking an integer, you probably want to return a single smaller value
* at a time. For strings, you may wish to return a string that is simpler (YZ -> YY),
* as well as smaller (YZ -> Y).
*
* If the value cannot be shrunk further, or the type
* does not support meaningful shrinking, then this function should
* return an empty list.
*
* Note: It is important that you do not return the degenerate case as the first step in a shrinker.
* Otherwise, this could be tested first, it could pass, and no other routes would be explored.
*/
interface Shrinker<A> {
/**
* Returns the "next level" of shrinks for the given value, or empty list if a "base case" has been reached.
* For example, to shrink an int k we may decide to return k/2 and k-1.
*/
fun shrink(value: A): List<A>
}
/**
* Generates an [RTree] of all shrinks from an initial strict value.
*/
fun <A> Shrinker<A>.rtree(value: A): RTree<A> {
val fn = { value }
return rtree(fn)
}
/**
* Generates an [RTree] of all shrinks from an initial lazy value.
*/
fun <A> Shrinker<A>.rtree(value: () -> A): RTree<A> =
RTree(
value,
lazy {
val a = value()
shrink(a).distinct().filter { it != a }.map { rtree(it) }
}
)
data class RTree<out A>(val value: () -> A, val children: Lazy<List<RTree<A>>> = lazy { emptyList<RTree<A>>() })
fun <A, B> RTree<A>.map(f: (A) -> B): RTree<B> {
val b = { f(value()) }
val c = lazy { children.value.map { it.map(f) } }
return RTree(b, c)
}
fun <A> RTree<A>.isEmpty() = this.children.value.isEmpty()
| kotest-property/src/commonMain/kotlin/io/kotest/property/Shrinker.kt | 3472425698 |
package com.mikepenz.materialdrawer.model.interfaces
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import com.mikepenz.materialdrawer.holder.ColorHolder
/**
* Defines a [IDrawerItem] with support for having a different color when selected
*/
interface SelectableColor {
/** The background color of a selectable item */
var selectedColor: ColorHolder?
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectableColor> T.withSelectedColor(@ColorInt selectedColor: Int): T {
this.selectedColor = ColorHolder.fromColor(selectedColor)
return this
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectableColor> T.withSelectedColorRes(@ColorRes selectedColorRes: Int): T {
this.selectedColor = ColorHolder.fromColorRes(selectedColorRes)
return this
}
/** Set the selected color as color resource */
var SelectableColor.selectedColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(@ColorRes value) {
selectedColor = ColorHolder.fromColorRes(value)
}
/** Set the selected color as color int */
var SelectableColor.selectedColorInt: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(@ColorInt value) {
selectedColor = ColorHolder.fromColor(value)
}
| materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/interfaces/SelectableColor.kt | 2311400661 |
package com.alexstyl.specialdates.events.namedays.activity
data class NamedaysViewModel(val name: String)
: NamedayScreenViewModel {
override val viewType: Int
get() = NamedayScreenViewType.NAMEDAY
override val id: Long
get() = hashCode().toLong()
}
| memento/src/main/java/com/alexstyl/specialdates/events/namedays/activity/NamedaysViewModel.kt | 1837405624 |
package com.jtransc.ds
class ListReader<T>(val list: List<T>) {
var position = 0
val size: Int get() = list.size
val eof: Boolean get() = position >= list.size
val hasMore: Boolean get() = position < list.size
fun peek(): T = list[position]
fun skip(count:Int = 1) = this.apply { this.position += count }
fun read(): T = peek().apply { skip(1) }
} | jtransc-utils/src/com/jtransc/ds/ListReader.kt | 3501538805 |
/*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* 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 io.uuddlrlrba.ktalgs.math
import org.junit.Assert
import org.junit.Test
class BinomialTest {
@Test
fun test1() {
Assert.assertEquals(0, binomial(0, 1))
Assert.assertEquals(1, binomial(1, 1))
Assert.assertEquals(2, binomial(2, 1))
Assert.assertEquals(3, binomial(3, 1))
Assert.assertEquals(3, binomial(3, 2))
Assert.assertEquals(4, binomial(4, 1))
Assert.assertEquals(1, binomial(5, 0))
Assert.assertEquals(5, binomial(5, 1))
Assert.assertEquals(10, binomial(5, 2))
Assert.assertEquals(10, binomial(5, 3))
Assert.assertEquals(5, binomial(5, 4))
Assert.assertEquals(1, binomial(5, 5))
Assert.assertEquals(1, binomial(6, 0))
Assert.assertEquals(6, binomial(6, 1))
Assert.assertEquals(15, binomial(6, 2))
Assert.assertEquals(20, binomial(6, 3))
Assert.assertEquals(15, binomial(6, 4))
Assert.assertEquals(6, binomial(6, 5))
Assert.assertEquals(1, binomial(6, 6))
}
}
| src/test/io/uuddlrlrba/ktalgs/math/BinomialTest.kt | 193074265 |
package day1
import fromOneLineInput
import java.lang.Character.getNumericValue
fun solveCaptchaPart1(input: String) = input.foldIndexed(0) { index, sum, char ->
val nextChar = input[(index + 1) % input.length]
if (char == nextChar) getNumericValue(char) + sum
else sum
}
fun solveCaptchaPart2(input: String): Int {
val step = input.length / 2
return input.foldIndexed(0) { index, sum, char ->
val nextChar = input[(index + step) % input.length]
if (char == nextChar) getNumericValue(char) + sum
else sum
}
}
fun main(args: Array<String>) {
val part1Solution = fromOneLineInput(2017, 1, "Captcha.txt", ::solveCaptchaPart1)
println(part1Solution)
val part2Solution = fromOneLineInput(2017, 1, "CaptchaPart2.txt", ::solveCaptchaPart2)
println(part2Solution)
}
| 2017/src/main/kotlin/day1/Captcha.kt | 947705540 |
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins
import com.github.zafarkhaja.semver.Version
import org.pf4j.VersionManager
import org.pf4j.util.StringUtils
import org.slf4j.LoggerFactory
/**
* Since plugins may require multiple services, this class is necessary to ensure we are making the
* constraint check against the correct service.
*/
class SpinnakerServiceVersionManager(
private val serviceName: String
) : VersionManager {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
override fun checkVersionConstraint(version: String, requires: String): Boolean {
if (requires.isEmpty()) {
log.warn("Loading plugin with empty Plugin-Requires attribute!")
return true
}
val requirements =
VersionRequirementsParser
.parseAll(requires)
.find { it.service.equals(serviceName, ignoreCase = true) }
if (requirements != null) {
return StringUtils.isNullOrEmpty(requirements.constraint) || Version.valueOf(version).satisfies(requirements.constraint)
}
return false
}
override fun compareVersions(v1: String, v2: String): Int {
return Version.valueOf(v1).compareTo(Version.valueOf(v2))
}
}
| kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerServiceVersionManager.kt | 2788042036 |
/*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.userjs
import android.os.Parcel
import android.os.Parcelable
import jp.hazuki.yuzubrowser.core.utility.extensions.forEachLine
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import jp.hazuki.yuzubrowser.core.utility.log.Logger
import java.io.BufferedReader
import java.io.IOException
import java.io.StringReader
import java.util.regex.Pattern
class UserScript : Parcelable {
val info: UserScriptInfo
var name: String? = null
var version: String? = null
var author: String? = null
var description: String? = null
val include = ArrayList<Pattern>(0)
val exclude = ArrayList<Pattern>(0)
var isUnwrap: Boolean = false
private set
var runAt: RunAt = RunAt.END
var id: Long
get() = info.id
set(id) {
info.id = id
}
var data: String
get() = info.data
set(data) {
info.data = data
loadHeaderData()
}
val runnable: String
get() = if (isUnwrap) {
info.data
} else {
"(function() {\n${info.data}\n})()"
}
var isEnabled: Boolean
get() = info.isEnabled
set(enabled) {
info.isEnabled = enabled
}
constructor() {
info = UserScriptInfo()
}
constructor(id: Long, data: String, enabled: Boolean) {
info = UserScriptInfo(id, data, enabled)
loadHeaderData()
}
constructor(data: String) {
info = UserScriptInfo(data)
loadHeaderData()
}
constructor(info: UserScriptInfo) {
this.info = info
loadHeaderData()
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(info.id)
dest.writeString(info.data)
dest.writeInt(if (info.isEnabled) 1 else 0)
}
constructor(source: Parcel) {
val id = source.readLong()
val data = source.readString()!!
val enabled = source.readInt() == 1
info = UserScriptInfo(id, data, enabled)
loadHeaderData()
}
private fun loadHeaderData() {
name = null
version = null
description = null
include.clear()
exclude.clear()
try {
val reader = BufferedReader(StringReader(info.data))
if (reader.readLine()?.let { sHeaderStartPattern.matcher(it).matches() } != true) {
Logger.w(TAG, "Header (start) parser error")
return
}
reader.forEachLine { line ->
val matcher = sHeaderMainPattern.matcher(line)
if (!matcher.matches()) {
if (sHeaderEndPattern.matcher(line).matches()) {
return
}
Logger.w(TAG, "Unknown header : $line")
} else {
val field = matcher.group(1)
val value = matcher.group(2)
readData(field, value, line)
}
}
Logger.w(TAG, "Header (end) parser error")
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
}
}
private fun readData(field: String?, value: String?, line: String) {
if ("name".equals(field, ignoreCase = true)) {
name = value
} else if ("version".equals(field, ignoreCase = true)) {
version = value
} else if ("author".equals(field, ignoreCase = true)) {
author = value
} else if ("description".equals(field, ignoreCase = true)) {
description = value
} else if ("include".equals(field, ignoreCase = true)) {
makeUrlPattern(value)?.let {
include.add(it)
}
} else if ("exclude".equals(field, ignoreCase = true)) {
makeUrlPattern(value)?.let {
exclude.add(it)
}
} else if ("unwrap".equals(field, ignoreCase = true)) {
isUnwrap = true
} else if ("run-at".equals(field, ignoreCase = true)) {
runAt = when (value) {
"document-start" -> RunAt.START
"document-idle" -> RunAt.IDLE
else -> RunAt.END
}
} else if ("match".equals(field, ignoreCase = true) && value != null) {
val patternUrl = "^" + value.replace("?", "\\?").replace(".", "\\.")
.replace("*", ".*").replace("+", ".+")
.replace("://.*\\.", "://((?![\\./]).)*\\.").replace("^\\.\\*://".toRegex(), "https?://")
makeUrlPatternParsed(patternUrl)?.let {
include.add(it)
}
} else {
Logger.w(TAG, "Unknown header : $line")
}
}
enum class RunAt {
START,
END,
IDLE
}
companion object {
private const val TAG = "UserScript"
@JvmField
val CREATOR: Parcelable.Creator<UserScript> = object : Parcelable.Creator<UserScript> {
override fun createFromParcel(source: Parcel): UserScript = UserScript(source)
override fun newArray(size: Int): Array<UserScript?> = arrayOfNulls(size)
}
private val sHeaderStartPattern = Pattern.compile("\\s*//\\s*==UserScript==\\s*", Pattern.CASE_INSENSITIVE)
private val sHeaderEndPattern = Pattern.compile("\\s*//\\s*==/UserScript==\\s*", Pattern.CASE_INSENSITIVE)
private val sHeaderMainPattern = Pattern.compile("\\s*//\\s*@(\\S+)(?:\\s+(.*))?", Pattern.CASE_INSENSITIVE)
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/userjs/UserScript.kt | 450956291 |
package com.soywiz.kpspemu.hle.modules
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.hle.*
@Suppress("UNUSED_PARAMETER")
class pspDveManager(emulator: Emulator) :
SceModule(emulator, "pspDveManager", 0x00010011, "pspDveManager.prx", "pspDveManager_Library") {
//STUB_START "pspDveManager",0x40090000,0x00020005
//STUB_FUNC 0x2ACFCB6D,pspDveMgrCheckVideoOut
//STUB_FUNC 0xF9C86C73,pspDveMgrSetVideoOut
//STUB_END
/*
*@return 0 - Cable not connected
*@return 1 - S-Video Cable / AV (composite) cable
*@return 2 - D Terminal Cable / Component Cable
*@return < 0 - Error
*/
fun pspDveMgrCheckVideoOut(): Int {
return 0 // Cable not connected
}
object Cable {
const val D_TERMINAL_CABLE = 0
const val S_VIDEO_CABLE = 2
}
object Mode {
const val PROGRESIVE = 0x1D2
const val INTERLACE = 0x1D1
}
//pspDveMgrSetVideoOut(2, 0x1D2, 720, 503, 1, 15, 0); // S-Video Cable / AV (Composite OUT) / Progressive (480p)
//pspDveMgrSetVideoOut(2, 0x1D1, 720, 503, 1, 15, 0); // S-Video Cable / AV (Composite OUT) / Interlace (480i)
//pspDveMgrSetVideoOut(0, 0x1D2, 720, 480, 1, 15, 0); // D Terminal Cable (Component OUT) / Progressive (480p)
//pspDveMgrSetVideoOut(0, 0x1D1, 720, 503, 1, 15, 0); // D Terminal Cable (Component OUT) / Interlace (480i)
fun pspDveMgrSetVideoOut(cable: Int, mode: Int, width: Int, height: Int, unk2: Int, unk3: Int, unk4: Int): Int {
return 0
}
override fun registerModule() {
registerFunctionInt("pspDveMgrCheckVideoOut", 0x2ACFCB6D, since = 150) { pspDveMgrCheckVideoOut() }
registerFunctionInt("pspDveMgrSetVideoOut", 0xF9C86C73, since = 150) {
pspDveMgrSetVideoOut(
int,
int,
int,
int,
int,
int,
int
)
}
}
}
| src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/pspDveManager.kt | 3758265576 |
package com.foo.rest.examples.spring.openapi.v3.charescaperegex
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
@SpringBootApplication(exclude = [SecurityAutoConfiguration::class])
open class CharEscapeRegexApplication {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(CharEscapeRegexApplication::class.java, *args)
}
}
} | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/charescaperegex/CharEscapeRegexApplication.kt | 670386547 |
package com.github.badoualy.telegram.api
import org.slf4j.LoggerFactory
import org.slf4j.MarkerFactory
import java.util.*
import kotlin.concurrent.schedule
/**
* Util class to cache clients some time before closing them to be able to re-use them if it's likely that
* they'll be used again soon
*/
class TelegramClientPool private constructor(name: String) {
private val marker = MarkerFactory.getMarker(name)
private val DEFAULT_EXPIRATION_DELAY = 5L * 60L * 1000L // 5 minutes
private var timer = Timer("Timer-${TelegramClientPool::class.java.simpleName}-$name")
private val map = HashMap<Long, TelegramClient>()
private val listenerMap = HashMap<Long, OnClientTimeoutListener>()
private val expireMap = HashMap<Long, Long>()
/**
* Cache the given client for a fixed amount of time before closing it if not used during that time
*
* @param id id associated with the client (used in {@link getAndRemove}
* @param client client to keep open
* @param expiresIn time before expiration (in ms)
*/
@JvmOverloads
fun put(id: Long, client: TelegramClient, listener: OnClientTimeoutListener?, expiresIn: Long = DEFAULT_EXPIRATION_DELAY) {
logger.debug(marker, "Adding client with id $id")
synchronized(this) {
// Already have a client with this id, close the new one and reset timer
expireMap.put(id, System.currentTimeMillis() + expiresIn)
if (listener != null)
listenerMap.put(id, listener)
else listenerMap.remove(id)
if (map.containsKey(id) && map[id] != client)
client.close(false)
else {
map.put(id, client)
Unit // Fix warning...
}
}
try {
timer.schedule(expiresIn, { onTimeout(id) })
} catch (e: IllegalStateException) {
timer = Timer("${javaClass.simpleName}")
timer.schedule(expiresIn, { onTimeout(id) })
}
}
/**
* Retrieve a previously cached client associated with the id
* @param id id used to cache the client
* @return cached client, or null if no client cached for the given id
*/
fun peek(id: Long): TelegramClient? {
synchronized(this) {
return map[id]
}
}
/**
* Retrieve a previously cached client associated with the id and remove it from this pool
* @param id id used to cache the client
* @return cached client, or null if no client cached for the given id
*/
fun getAndRemove(id: Long): TelegramClient? {
synchronized(this) {
expireMap.remove(id)
return map.remove(id)
}
}
fun onTimeout(id: Long) {
val timeout =
synchronized(this) {
if (expireMap.getOrDefault(id, 0) <= System.currentTimeMillis()) {
val client = getAndRemove(id)
if (client != null) {
logger.info(marker, "$id client timeout")
client.close(false)
true
} else false
} else false
}
if (timeout)
listenerMap.remove(id)?.onClientTimeout(id)
}
fun shutdown() {
timer.cancel()
}
fun getKeys() = map.keys
fun getClients() = map.values
companion object {
private val logger = LoggerFactory.getLogger(TelegramClientPool::class.java)
@JvmField
val DEFAULT_POOL = TelegramClientPool("DefaultPool")
@JvmField
val DOWNLOADER_POOL = TelegramClientPool("DownloaderPool")
}
}
interface OnClientTimeoutListener {
fun onClientTimeout(id: Long)
} | api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClientPool.kt | 3466878161 |
/*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Authors: AmirHossein Naghshzan <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.CompoundButton
import android.widget.TextView
import cx.ring.R
import cx.ring.databinding.FragAccJamiPasswordBinding
import cx.ring.mvp.BaseSupportFragment
import dagger.hilt.android.AndroidEntryPoint
import net.jami.account.JamiAccountCreationPresenter
import net.jami.account.JamiAccountCreationView
import net.jami.account.JamiAccountCreationView.UsernameAvailabilityStatus
import net.jami.model.AccountCreationModel
@AndroidEntryPoint
class JamiAccountPasswordFragment : BaseSupportFragment<JamiAccountCreationPresenter, JamiAccountCreationView>(),
JamiAccountCreationView {
private var model: AccountCreationModel? = null
private var binding: FragAccJamiPasswordBinding? = null
private var mIsChecked = false
override fun onSaveInstanceState(outState: Bundle) {
if (model != null) outState.putSerializable(KEY_MODEL, model)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (savedInstanceState != null && model == null) {
model = savedInstanceState.getSerializable(KEY_MODEL) as AccountCreationModelImpl?
}
binding = FragAccJamiPasswordBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding!!.createAccount.setOnClickListener { presenter.createAccount() }
binding!!.ringPasswordSwitch.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
mIsChecked = isChecked
if (isChecked) {
binding!!.passwordTxtBox.visibility = View.VISIBLE
binding!!.ringPasswordRepeatTxtBox.visibility = View.VISIBLE
binding!!.placeholder.visibility = View.GONE
val password: CharSequence? = binding!!.ringPassword.text
presenter.passwordChanged(password.toString(), binding!!.ringPasswordRepeat.text!!)
} else {
binding!!.passwordTxtBox.visibility = View.GONE
binding!!.ringPasswordRepeatTxtBox.visibility = View.GONE
binding!!.placeholder.visibility = View.VISIBLE
presenter.passwordUnset()
}
}
binding!!.ringPassword.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
presenter.passwordChanged(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
binding!!.ringPasswordRepeat.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
presenter.passwordConfirmChanged(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
binding!!.ringPasswordRepeat.setOnEditorActionListener { v: TextView?, actionId: Int, event: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
presenter.createAccount()
}
false
}
binding!!.ringPasswordRepeat.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE && binding!!.createAccount.isEnabled) {
val inputMethodManager = v.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(v.windowToken, 0)
presenter.createAccount()
return@setOnEditorActionListener true
}
false
}
presenter.init(model)
}
override fun updateUsernameAvailability(status: UsernameAvailabilityStatus) {}
override fun showInvalidPasswordError(display: Boolean) {
binding!!.passwordTxtBox.error = if (display) getString(R.string.error_password_char_count) else null
}
override fun showNonMatchingPasswordError(display: Boolean) {
binding!!.ringPasswordRepeatTxtBox.error = if (display) getString(R.string.error_passwords_not_equals) else null
}
override fun enableNextButton(enabled: Boolean) {
binding!!.createAccount.isEnabled = if (mIsChecked) enabled else true
}
override fun goToAccountCreation(accountCreationModel: AccountCreationModel) {
val wizardActivity: Activity? = activity
if (wizardActivity is AccountWizardActivity) {
wizardActivity.createAccount(accountCreationModel)
val parent = parentFragment as JamiAccountCreationFragment?
if (parent != null) {
parent.scrollPagerFragment(accountCreationModel)
val imm = wizardActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(binding!!.ringPassword.windowToken, 0)
}
}
}
override fun cancel() {
val wizardActivity: Activity? = activity
wizardActivity?.onBackPressed()
}
fun setUsername(username: String) {
model!!.username = username
}
companion object {
private const val KEY_MODEL = "model"
fun newInstance(ringAccountViewModel: AccountCreationModelImpl): JamiAccountPasswordFragment {
val fragment = JamiAccountPasswordFragment()
fragment.model = ringAccountViewModel
return fragment
}
}
} | ring-android/app/src/main/java/cx/ring/account/JamiAccountPasswordFragment.kt | 3730276657 |
package me.proxer.library.api.notifications
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.notifications.NewsArticle
/**
* Endpoint for retrieving news articles.
*
* @author Ruben Gees
*/
class NewsEndpoint internal constructor(private val internalApi: InternalApi) : PagingLimitEndpoint<List<NewsArticle>> {
private var page: Int? = null
private var limit: Int? = null
private var markAsRead: Boolean? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
/**
* Sets if the news should be marked as read. Defaults to false.
*/
fun markAsRead(markAsRead: Boolean? = true) = this.apply { this.markAsRead = markAsRead }
override fun build(): ProxerCall<List<NewsArticle>> {
return internalApi.news(page, limit, markAsRead)
}
}
| library/src/main/kotlin/me/proxer/library/api/notifications/NewsEndpoint.kt | 2795845352 |
package com.google.firebase.quickstart.firebasestorage
import android.content.Intent
import com.firebase.example.internal.BaseEntryChoiceActivity
import com.firebase.example.internal.Choice
class EntryChoiceActivity : BaseEntryChoiceActivity() {
override fun getChoices(): List<Choice> {
return listOf(
Choice(
"Java",
"Run the Firebase Storage quickstart written in Java.",
Intent(this, com.google.firebase.quickstart.firebasestorage.java.MainActivity::class.java)),
Choice(
"Kotlin",
"Run the Firebase In App Messaging quickstart written in Kotlin.",
Intent(this, com.google.firebase.quickstart.firebasestorage.kotlin.MainActivity::class.java))
)
}
}
| storage/app/src/main/java/com/google/firebase/quickstart/firebasestorage/EntryChoiceActivity.kt | 3800120011 |
/**
* Copyright (c) 2017-present, Team Bucket Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package com.github.luks91.teambucket.main.statistics.load
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import com.github.luks91.teambucket.R
import com.hannesdorfmann.mosby3.mvp.MvpFragment
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
class StatisticsLoadFragment : MvpFragment<StatisticsLoadView, StatisticsLoadPresenter>(), StatisticsLoadView {
@Inject lateinit var statisticsPresenter: StatisticsLoadPresenter
private val intentPullToRefresh = PublishSubject.create<Any>()
private val loadProgressBar: ProgressBar by lazy { view!!.findViewById(R.id.statisticsLoadProgressBar) as ProgressBar }
private val progressText: TextView by lazy { view!!.findViewById(R.id.progressValue) as TextView }
companion object Factory {
fun newInstance() = StatisticsLoadFragment()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
AndroidSupportInjection.inject(this)
}
override fun createPresenter() = statisticsPresenter
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_load_statistics, container, false)
}
override fun intentRefreshData(): Observable<Any> = intentPullToRefresh
private var pullRequestsCount = 0
private var completedPullRequestsCount = 0
override fun onLoadingStarted() {
loadProgressBar.visibility = View.VISIBLE
completedPullRequestsCount = 0
pullRequestsCount = 0
}
override fun onPullRequestDetected() {
if (!isDetached) {
activity.runOnUiThread {
pullRequestsCount++
updateProgress()
}
}
}
private fun updateProgress() {
loadProgressBar.progress = if (pullRequestsCount == 0) 0 else (100.0 * completedPullRequestsCount / pullRequestsCount)
.toInt()
progressText.text = "$completedPullRequestsCount/$pullRequestsCount"
}
override fun onPullRequestProcessed() {
if (!isDetached) {
activity.runOnUiThread {
completedPullRequestsCount++
updateProgress()
}
}
}
override fun onLoadingCompleted() {
}
} | app/src/main/java/com/github/luks91/teambucket/main/statistics/load/StatisticsLoadFragment.kt | 2985725211 |
/**
* Copyright (c) 2017-present, Team Bucket Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package com.github.luks91.teambucket.main.home
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.luks91.teambucket.R
import com.github.luks91.teambucket.main.base.BasePullRequestsFragment
import com.github.luks91.teambucket.model.AvatarLoadRequest
import com.github.luks91.teambucket.model.PullRequest
import com.github.luks91.teambucket.model.ReviewersInformation
import com.jakewharton.rxrelay2.PublishRelay
import com.jakewharton.rxrelay2.Relay
import javax.inject.Inject
class HomeFragment : BasePullRequestsFragment<HomeView, HomePresenter>(), HomeView {
private val imageLoadRequests: Relay<AvatarLoadRequest> = PublishRelay.create()
private val dataAdapter by lazy { HomeAdapter(context, imageLoadRequests) }
private val layoutManager by lazy { LinearLayoutManager(context) }
@Inject lateinit var homePresenter: HomePresenter
companion object Factory {
fun newInstance() : HomeFragment = HomeFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_swipe_recycler_view, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view!!.findViewById(R.id.reviewersRecyclerView) as RecyclerView
recyclerView.layoutManager = layoutManager
recyclerView.adapter = dataAdapter
}
override fun createPresenter() = homePresenter
override fun onReviewersReceived(reviewers: ReviewersInformation) = dataAdapter.onReviewersReceived(reviewers)
override fun intentLoadAvatarImage() = imageLoadRequests
override fun onUserPullRequestsProvided(pullRequests: List<PullRequest>) =
dataAdapter.onUserPullRequestsReceived(pullRequests)
} | app/src/main/java/com/github/luks91/teambucket/main/home/HomeFragment.kt | 1697848628 |
package me.tatarka.silentsupport
import com.android.tools.lint.client.api.JavaParser
import com.android.tools.lint.client.api.LintClient
import com.android.tools.lint.client.api.UastParser
import com.android.tools.lint.client.api.XmlParser
import com.android.tools.lint.detector.api.*
import me.tatarka.assertk.assert
import me.tatarka.assertk.assertions.isGreaterThan
import me.tatarka.silentsupport.lint.ApiLookup
import org.junit.Before
import org.junit.Test
import java.io.File
class SupportMetadataProcessorTest {
lateinit var processor: SupportMetadataProcessor
lateinit var lookup: ApiLookup
val outputDir = File("build/resources/test")
@Before
fun setup() {
processor = SupportMetadataProcessor(
SupportCompat(File("test-libs/support-compat-25.3.0.aar"), "25.3.0"),
outputDir)
}
@Test
fun `can find ContextCompat#getDrawable`() {
val lintClient = object : LintClient() {
override fun getUastParser(p0: Project): UastParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun report(context: Context, issue: Issue, severity: Severity?, location: Location?, message: String?, format: TextFormat?, fix: LintFix?) {
}
override fun log(severity: Severity?, exception: Throwable?, format: String?, vararg args: Any?) {
}
override fun getJavaParser(project: Project?): JavaParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun readFile(file: File?): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getXmlParser(): XmlParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCacheDir(name: String, create: Boolean): File {
return outputDir
}
}
processor.process()
lookup = ApiLookup.create(lintClient, processor.metadataFile, true)
val result = lookup.getCallVersion("android/support/v4/content/ContextCompat", "getDrawable", "(Landroid/content/Context;I)Landroid/graphics/drawable/Drawable;")
assert(result).isGreaterThan(0)
}
}
| silent-support/src/test/kotlin/me/tatarka/silentsupport/SupportMetadataProcessorTest.kt | 618402782 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.memory
import androidx.annotation.VisibleForTesting
import com.facebook.common.internal.Throwables
import com.facebook.common.memory.PooledByteBufferFactory
import com.facebook.common.memory.PooledByteStreams
import com.facebook.common.references.CloseableReference
import java.io.IOException
import java.io.InputStream
import javax.annotation.concurrent.ThreadSafe
/**
* A factory to provide instances of [MemoryPooledByteBuffer] and
* [MemoryPooledByteBufferOutputStream]
*/
@ThreadSafe
class MemoryPooledByteBufferFactory( // memory pool
private val pool: MemoryChunkPool, private val pooledByteStreams: PooledByteStreams) :
PooledByteBufferFactory {
override fun newByteBuffer(size: Int): MemoryPooledByteBuffer {
check(size > 0)
val chunkRef = CloseableReference.of(pool[size], pool)
return try {
MemoryPooledByteBuffer(chunkRef, size)
} finally {
chunkRef.close()
}
}
@Throws(IOException::class)
override fun newByteBuffer(inputStream: InputStream): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool)
return try {
newByteBuf(inputStream, outputStream)
} finally {
outputStream.close()
}
}
override fun newByteBuffer(bytes: ByteArray): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool, bytes.size)
return try {
outputStream.write(bytes, 0, bytes.size)
outputStream.toByteBuffer()
} catch (ioe: IOException) {
throw Throwables.propagate(ioe)
} finally {
outputStream.close()
}
}
@Throws(IOException::class)
override fun newByteBuffer(
inputStream: InputStream,
initialCapacity: Int
): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool, initialCapacity)
return try {
newByteBuf(inputStream, outputStream)
} finally {
outputStream.close()
}
}
/**
* Reads all bytes from inputStream and writes them to outputStream. When all bytes are read
* outputStream.toByteBuffer is called and obtained MemoryPooledByteBuffer is returned
*
* @param inputStream the input stream to read from
* @param outputStream output stream used to transform content of input stream to
* MemoryPooledByteBuffer
* @return an instance of MemoryPooledByteBuffer
* @throws IOException
*/
@VisibleForTesting
@Throws(IOException::class)
fun newByteBuf(
inputStream: InputStream,
outputStream: MemoryPooledByteBufferOutputStream
): MemoryPooledByteBuffer {
pooledByteStreams.copy(inputStream, outputStream)
return outputStream.toByteBuffer()
}
override fun newOutputStream(): MemoryPooledByteBufferOutputStream =
MemoryPooledByteBufferOutputStream(pool)
override fun newOutputStream(initialCapacity: Int): MemoryPooledByteBufferOutputStream =
MemoryPooledByteBufferOutputStream(pool, initialCapacity)
}
| imagepipeline/src/main/java/com/facebook/imagepipeline/memory/MemoryPooledByteBufferFactory.kt | 1104309313 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.request
/**
* Use an instance of this interface to perform post-process operations that must be performed more
* than once.
*/
interface RepeatedPostprocessor : Postprocessor {
/**
* Callback used to pass the postprocessor a reference to the object that will run the
* postprocessor's `PostProcessor#process` method when the client requires.
*
* @param runner
*/
fun setCallback(runner: RepeatedPostprocessorRunner)
}
| imagepipeline/src/main/java/com/facebook/imagepipeline/request/RepeatedPostprocessor.kt | 1944302389 |
package com.fastaccess.data.dao.wiki
import android.os.Parcel
import com.fastaccess.helper.KotlinParcelable
import com.fastaccess.helper.parcelableCreator
/**
* Created by Kosh on 13 Jun 2017, 8:03 PM
*/
data class WikiSideBarModel(val title: String? = null, val link: String? = null) : KotlinParcelable {
companion object {
@JvmField val CREATOR = parcelableCreator(::WikiSideBarModel)
}
constructor(source: Parcel) : this(
source.readString(),
source.readString()
)
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(title)
writeString(link)
}
}
| app/src/main/java/com/fastaccess/data/dao/wiki/WikiSideBarModel.kt | 2961485809 |
package com.codefororlando.orlandowalkingtours.data.entities
/**
* Created by ryan on 10/12/17.
*/
data class Location(val id: String,
val name: String,
val address: String,
val description: String,
val coordinates: Coordinates,
val pictures: List<String>,
val registryDates: RegistryDates) | app/src/main/java/com/codefororlando/orlandowalkingtours/data/entities/Location.kt | 3955241136 |
/*
* Copyright (C) 2017 YangBin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package tech.summerly.quiet.service
import tech.summerly.quiet.extensions.log
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bus.RxBus
import tech.summerly.quiet.module.common.player.BaseMusicPlayer
import tech.summerly.quiet.module.common.player.PlayMode
import java.util.*
import kotlin.collections.ArrayList
/**
* author : yangbin10
* date : 2017/11/21
*/
class SimpleMusicPlayer private constructor() : BaseMusicPlayer() {
companion object {
@JvmStatic
val instance = SimpleMusicPlayer()
}
private val musicList = LinkedList<Music>()
private val shuffleMusicList = ArrayList<Music>()
override fun getNextMusic(current: Music?): Music? {
if (musicList.isEmpty()) {
log { "empty playlist!" }
return null
}
if (current == null) {
return musicList[0]
}
return when (playMode) {
PlayMode.SINGLE -> {
current
}
PlayMode.SEQUENCE -> {
//if can not find ,index will be zero , it will right too
val index = musicList.indexOf(current) + 1
if (index == musicList.size) {
musicList[0]
} else {
musicList[index]
}
}
PlayMode.SHUFFLE -> {
ensureShuffleListGenerate()
//if can not find ,index will be zero , it will right too
val index = shuffleMusicList.indexOf(current)
when (index) {
-1 -> musicList[0]
musicList.size - 1 -> {
generateShuffleList()
shuffleMusicList[0]
}
else -> shuffleMusicList[index + 1]
}
}
}
}
private fun ensureShuffleListGenerate() {
if (shuffleMusicList.size != musicList.size) {
generateShuffleList()
}
}
private fun generateShuffleList() {
val list = ArrayList(musicList)
var position = list.size - 1
while (position > 0) {
//生成一个随机数
val random = (Math.random() * (position + 1)).toInt()
//将random和position两个元素交换
val temp = list[position]
list[position] = list[random]
list[random] = temp
position--
}
shuffleMusicList.clear()
shuffleMusicList.addAll(list)
}
override fun getPreviousMusic(current: Music?): Music? {
if (musicList.isEmpty()) {
log { "try too play next with empty playlist!" }
return null
}
if (current == null) {
return musicList[0]
}
return when (playMode) {
PlayMode.SINGLE -> {
current
}
PlayMode.SEQUENCE -> {
val index = musicList.indexOf(current)
when (index) {
-1 -> musicList[0]
0 -> musicList[musicList.size - 1]
else -> musicList[index - 1]
}
}
PlayMode.SHUFFLE -> {
ensureShuffleListGenerate()
val index = shuffleMusicList.indexOf(current)
when (index) {
-1 -> musicList[0]
0 -> {
generateShuffleList()
shuffleMusicList[shuffleMusicList.size - 1]
}
else -> shuffleMusicList[index - 1]
}
}
}
}
override fun setPlaylist(musics: List<Music>) {
stop()
musicList.clear()
musicList.addAll(musics)
super.setPlaylist(musics)
}
override fun getPlaylist(): List<Music> = musicList
override fun remove(music: Music) {
musicList.remove(music)
}
override fun addToNext(music: Music) {
if (!musicList.contains(music)) {
val index = musicList.indexOf(currentPlaying()) + 1
musicList.add(index, music)
}
}
override fun destroy() {
super.destroy()
RxBus.publish(DestroyEvent())
}
class DestroyEvent
} | app/src/main/java/tech/summerly/quiet/service/SimpleMusicPlayer.kt | 1578846902 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.android.rx
import com.google.android.gms.maps.GoogleMap
import com.google.maps.android.rx.shared.MainThreadObservable
import io.reactivex.rxjava3.android.MainThreadDisposable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
/**
* Creates an [Observable] that emits whenever the my location button is clicked.
*
* The created [Observable] uses [GoogleMap.setOnMyLocationButtonClickListener] to listen to map
* my location button clicks. Since only one listener at a time is allowed, only one Observable at a
* time can be used.
*
* @param consumed Lambda invoked when the my location button is clicked. The return value is the
* value passed to [GoogleMap.OnMyLocationButtonClickListener.onMyLocationButtonClick]. Default
* implementation will always return false
*/
public fun GoogleMap.myLocationButtonClickEvents(
consumed: () -> Boolean = { false }
): Observable<Unit> =
GoogleMapMyLocationButtonClickObservable(this, consumed)
private class GoogleMapMyLocationButtonClickObservable(
private val googleMap: GoogleMap,
private val consumed: () -> Boolean
) : MainThreadObservable<Unit>() {
override fun subscribeMainThread(observer: Observer<in Unit>) {
val listener = MyLocationButtonClickListener(googleMap, consumed, observer)
observer.onSubscribe(listener)
googleMap.setOnMyLocationButtonClickListener(listener)
}
private class MyLocationButtonClickListener(
private val googleMap: GoogleMap,
private val consumed: () -> Boolean,
private val observer: Observer<in Unit>
) : MainThreadDisposable(), GoogleMap.OnMyLocationButtonClickListener {
override fun onDispose() {
googleMap.setOnMyLocationButtonClickListener(null)
}
override fun onMyLocationButtonClick(): Boolean {
if (!isDisposed) {
try {
if (consumed()) {
observer.onNext(Unit)
return true
}
} catch (e: Exception) {
observer.onError(e)
dispose()
}
observer.onNext(Unit)
}
return false
}
}
}
| maps-rx/src/main/java/com/google/maps/android/rx/GoogleMapMyLocationButtonClickObservable.kt | 2202389057 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.neighbourhood
/**
* A rectangular grid of [Block]s, where each block can contain multiple occupants of type T.
* T is often Role.
*/
interface Neighbourhood<T> {
/**
* Resets the Neighbourhood, so that there are no Actors held within it.
* You can use this to reset the Neighbourhood at the beginning of a Scene, however, it is probably easier to create
* a new Neighbourhood within your SceneDirector, that way, you will have a new Neighbourhood for each scene.
*/
fun clear()
/**
* @return The width of the Blocks within this Neighbourhood.
*/
val blockWidth: Double
/**
* @return The height of the Blocks within this Neighbourhood.
*/
val blockHeight: Double
/**
* Looks for a Block within the neighbourhood. If a block at the given coordinates hasn't been
* created yet, then that block is created.
*
*
* Used when adding an Actor to the Neighbourhood.
* @return The block at the given coordinate
* *
* @see .getExistingBlock
*/
fun blockAt(x: Double, y: Double): Block<T>
/**
* Looks for a Block that has already been created.
*
*
* Used when looking for an Actor. If there is no Block, then there is no need to create a new one.
* @return The Block at the given coordinates, or null if there is no Block.
* *
* @see .getBlock
*/
fun existingBlockAt(x: Double, y: Double): Block<T>?
fun blocksAcross(): Int
fun blocksDown(): Int
fun width(): Double = blocksAcross() * blockWidth
fun height(): Double = blocksDown() * blockHeight
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/neighbourhood/Neighbourhood.kt | 3797668749 |
package org.lice.parse
import org.intellij.lang.annotations.Language
import org.junit.Test
class ParserSandbox {
@Test(timeout = 1000)
fun run() {
@Language("Lice")
val srcCode = """
(def fibonacci n
(if (== n 1)
(1)
(if (== n 2)
(1)
(+ (fibonacci (- n 1)) (fibonacci (- n 2))))))
(-> i 1)
(while (< i 20)
(|>
(print (fibonacci i))
(print ("
"))
(-> i (+ i 1))))
"""
val rootNode = Parser.parseTokenStream(Lexer(srcCode))
}
}
| src/test/kotlin/org/lice/parse/ParserSandbox.kt | 1214339083 |
package ru.maxlord.kotlinandroidapp.activity.splash
import android.os.SystemClock
import com.crashlytics.android.Crashlytics
import io.fabric.sdk.android.Fabric
import ru.maxlord.kotlinandroidapp.BuildConfig
import ru.maxlord.kotlinandroidapp.R
import ru.maxlord.kotlinandroidapp.activity.base.SchedulersManager
import ru.maxlord.kotlinandroidapp.activity.main.Main
import ru.maxlord.kotlinandroidapp.app.KotlinAndroidApplication
import ru.maxlord.kotlinandroidapp.base.BaseFragment
import ru.maxlord.kotlinandroidapp.helper.ActivityHelper
import ru.maxlord.kotlinandroidapp.rest.Api
import javax.inject.Inject
/**
* Стартовый экран
*
* @author Lord (Kuleshov M.V.)
* @since 16.03.16
*/
class SplashFragment: BaseFragment() {
companion object {
fun newInstance(): SplashFragment {
val f = SplashFragment()
return f
}
}
@Inject lateinit var application: KotlinAndroidApplication
@Inject lateinit var api: Api
@Inject lateinit var schedulersManager: SchedulersManager
override fun inject() {
getComponent().inject(this)
}
override fun onStart() {
super.onStart()
IntentLauncher().start()
}
override fun getLayoutRes(): Int {
return R.layout.fragment_splash
}
private inner class IntentLauncher : Thread() {
/**
* Sleep for some time and than start new activity.
*/
override fun run() {
// Crashlytics
if (!BuildConfig.DEBUG) {
Fabric.with(activity, Crashlytics())
}
SystemClock.sleep(2000)
startMainActivity()
}
}
private fun startMainActivity() {
// Запускаем главный экран
ActivityHelper.startActivity(activity, Main::class.java, true)
}
}
| app/src/main/kotlin/ru/maxlord/kotlinandroidapp/activity/splash/SplashFragment.kt | 1404328919 |
/**
* Plugin thread's buffer item
* Created by zingmars on 04.10.2015.
*/
package Containers
public class PluginBufferItem(public val id :String, public val userID :String, public val time :String, public val userName :String, public val message :String, public val privilvl :String = "user", public val extradata :String = "") {} | src/Containers/PluginBufferItem.kt | 3312057407 |
package com.jeremiahzucker.pandroid.ui.base
import androidx.appcompat.app.AppCompatActivity
/**
* BaseActivity
*
* Author: Jeremiah Zucker
* Date: 9/4/2017
* Desc: TODO: Complete
*/
abstract class BaseActivity : AppCompatActivity() {
// Converted to xml gradient
// override fun onAttachedToWindow() {
// super.onAttachedToWindow()
// // https://crazygui.wordpress.com/2010/09/05/high-quality-radial-gradient-in-android/
// val displayMetrics = resources.displayMetrics
// val screenHeight = displayMetrics.heightPixels
//
// window.setBackgroundGradient(
// ContextCompat.getColor(this, R.color.theme_dark_blue_gradientColor),
// ContextCompat.getColor(this, R.color.theme_dark_blue_background),
// screenHeight / 2,
// 0.5f,
// 0.5f
// )
// window.setFormat(PixelFormat.RGBA_8888)
// }
}
| app/src/main/java/com/jeremiahzucker/pandroid/ui/base/BaseActivity.kt | 740978854 |
package net.perfectdreams.loritta.morenitta.website.views.subviews.api.config.types
import com.github.salomonbrys.kotson.bool
import com.google.gson.JsonObject
import kotlinx.coroutines.runBlocking
import net.perfectdreams.loritta.morenitta.dao.ServerConfig
import net.dv8tion.jda.api.entities.Guild
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.MiscellaneousConfig
import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession
import org.jetbrains.exposed.sql.transactions.transaction
class MiscellaneousPayload(val loritta: LorittaBot) : ConfigPayloadType("miscellaneous") {
override fun process(payload: JsonObject, userIdentification: LorittaJsonWebSession.UserIdentification, serverConfig: ServerConfig, guild: Guild) {
val enableQuirky = payload["enableQuirky"].bool
val enableBomDiaECia = payload["enableBomDiaECia"].bool
runBlocking {
loritta.pudding.transaction {
val miscellaneousConfig = serverConfig.miscellaneousConfig
val newConfig = miscellaneousConfig ?: MiscellaneousConfig.new {
this.enableQuirky = enableQuirky
this.enableBomDiaECia = enableBomDiaECia
}
newConfig.enableQuirky = enableQuirky
newConfig.enableBomDiaECia = enableBomDiaECia
serverConfig.miscellaneousConfig = newConfig
}
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/subviews/api/config/types/MiscellaneousPayload.kt | 4005702170 |
package net.perfectdreams.loritta.cinnamon.showtime.backend.utils
import kotlinx.serialization.Serializable
@Serializable
data class ImageInfo(
val path: String,
val width: Int,
val height: Int,
val size: Long,
val variations: List<ImageInfo>?
) : java.io.Serializable // Needs to be serializable because if not Gradle complains that it can't serialize | web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/utils/ImageInfo.kt | 3328819826 |
package com.dx.dxloadingbutton.lib
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.DecelerateInterpolator
import kotlin.math.max
import kotlin.math.min
enum class AnimationType{
SUCCESSFUL,
FAILED
}
@Suppress("unused")
class LoadingButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0) : View(context, attrs, defStyle){
companion object {
private const val STATE_BUTTON = 0
private const val STATE_ANIMATION_STEP1 = 1
private const val STATE_ANIMATION_STEP2 = 2
private const val STATE_ANIMATION_LOADING = 3
private const val STATE_STOP_LOADING = 4
private const val STATE_ANIMATION_SUCCESS = 5
private const val STATE_ANIMATION_FAILED = 6
private const val DEFAULT_WIDTH = 88
private const val DEFAULT_HEIGHT = 56
private const val DEFAULT_COLOR = Color.BLUE
private const val DEFAULT_TEXT_COLOR = Color.WHITE
}
private val mDensity = resources.displayMetrics.density
private val defaultMinHeight = 48 * mDensity
var animationEndAction: ((AnimationType) -> Unit)? = null
var rippleEnable = true
set(value) {
invalidate()
field = value
}
var rippleColor = Color.BLACK
set(value){
mRipplePaint.color = value
field = value
}
var textColor
get() = mTextColor
set(value) {
mTextColor = value
invalidate()
}
var typeface: Typeface
get() = mTextPaint.typeface
set(value) {
mTextPaint.typeface = value
invalidate()
}
var text
get() = mText
set(value) {
if (text.isEmpty()) {
return
}
this.mText = value
mTextWidth = mTextPaint.measureText(mText)
mTextHeight = measureTextHeight(mTextPaint)
invalidate()
}
/**
* set button text, dip
*/
var textSize
get() = (mTextPaint.textSize / mDensity).toInt()
set(value) {
mTextPaint.textSize = value * mDensity
mTextWidth = mTextPaint.measureText(mText)
invalidate()
}
var cornerRadius
get() = mButtonCorner
set(value) {
mButtonCorner = value
invalidate()
}
/** while loading data failed, reset view to normal state */
var resetAfterFailed = true
/**
* set button background as shader paint
*/
var backgroundShader: Shader?
get() = mStrokePaint.shader
set(value) {
mPaint.shader = value
mStrokePaint.shader = value
mPathEffectPaint.shader = value
mPathEffectPaint2.shader = value
invalidate()
}
private var mCurrentState = STATE_BUTTON
private var mMinHeight = defaultMinHeight
private var mColorPrimary = DEFAULT_COLOR
private var mDisabledBgColor = Color.LTGRAY
private var mTextColor = Color.WHITE
private var mDisabledTextColor = Color.DKGRAY
private var mRippleAlpha = 0.2f
private var mPadding = 6 * mDensity
private val mPaint = Paint()
private val mRipplePaint = Paint()
private val mStrokePaint = Paint()
private val mTextPaint = Paint()
private val mPathEffectPaint = Paint()
private val mPathEffectPaint2 = Paint()
private var mScaleWidth = 0
private var mScaleHeight = 0
private var mDegree = 0
private var mAngle = 0
private var mEndAngle= 0
private var mButtonCorner = 2 * mDensity
private var mRadius = 0
private var mTextWidth = 0f
private var mTextHeight = 0f
private val mMatrix = Matrix()
private var mPath = Path()
private var mSuccessPath: Path? = null
private var mSuccessPathLength = 0f
private var mSuccessPathIntervals: FloatArray? = null
private var mFailedPath: Path? = null
private var mFailedPath2: Path? = null
private var mFailedPathLength = 0f
private var mFailedPathIntervals: FloatArray? = null
private var mTouchX = 0f
private var mTouchY = 0f
private var mRippleRadius = 0f
private val mButtonRectF = RectF()
private val mArcRectF = RectF()
private var mText: String = ""
private var mLoadingAnimatorSet: AnimatorSet? = null
init {
if (attrs != null) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.LoadingButton, 0, 0)
mColorPrimary = ta.getInt(R.styleable.LoadingButton_lb_btnColor, Color.BLUE)
mDisabledBgColor = ta.getColor(R.styleable.LoadingButton_lb_btnDisabledColor, Color.LTGRAY)
mDisabledTextColor = ta.getColor(R.styleable.LoadingButton_lb_disabledTextColor, Color.DKGRAY)
val text = ta.getString(R.styleable.LoadingButton_lb_btnText)
mText = text ?: ""
mTextColor = ta.getColor(R.styleable.LoadingButton_lb_textColor, Color.WHITE)
resetAfterFailed = ta.getBoolean(R.styleable.LoadingButton_lb_resetAfterFailed, true)
rippleColor = ta.getColor(R.styleable.LoadingButton_lb_btnRippleColor, Color.BLACK)
rippleEnable = ta.getBoolean(R.styleable.LoadingButton_lb_rippleEnable, true)
mRippleAlpha = ta.getFloat(R.styleable.LoadingButton_lb_btnRippleAlpha, 0.3f)
mButtonCorner = ta.getDimension(R.styleable.LoadingButton_lb_cornerRadius, 2 * mDensity)
mMinHeight = ta.getDimension(R.styleable.LoadingButton_lb_min_height, defaultMinHeight)
ta.recycle()
}
mPaint.apply {
setLayerType(LAYER_TYPE_SOFTWARE, this)
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.FILL
setShadowDepth(2 * mDensity)
}
mRipplePaint.apply {
isAntiAlias = true
color = rippleColor
alpha = (mRippleAlpha * 255).toInt()
style = Paint.Style.FILL
}
mStrokePaint.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
mTextPaint.apply {
isAntiAlias = true
color = mTextColor
textSize = 16 * mDensity
isFakeBoldText = true
}
mTextWidth = mTextPaint.measureText(mText)
mTextHeight = measureTextHeight(mTextPaint)
mPathEffectPaint.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
mPathEffectPaint2.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
setLayerType(LAYER_TYPE_SOFTWARE, mPaint)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(
measureDimension((DEFAULT_WIDTH * mDensity).toInt(), widthMeasureSpec),
measureDimension((DEFAULT_HEIGHT * mDensity).toInt(), heightMeasureSpec))
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val viewHeight = max(h, mMinHeight.toInt())
mRadius = (viewHeight - mPadding * 2).toInt() / 2
mButtonRectF.top = mPadding
mButtonRectF.bottom = viewHeight - mPadding
mArcRectF.left = (width / 2 - mRadius).toFloat()
mArcRectF.top = mPadding
mArcRectF.right = (width / 2 + mRadius).toFloat()
mArcRectF.bottom = viewHeight - mPadding
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
if (mCurrentState == STATE_BUTTON) {
updateButtonColor()
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (!isEnabled) {
return true
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mTouchX = event.x
mTouchY = event.y
playTouchDownAnimation()
}
MotionEvent.ACTION_UP -> if (event.x > mButtonRectF.left && event.x < mButtonRectF.right && event.y > mButtonRectF.top && event.y < mButtonRectF.bottom) {
// only register as click if finger is up inside view
playRippleAnimation()
} else {
// if finger is moved outside view and lifted up, reset view
mTouchX = 0f
mTouchY = 0f
mRippleRadius = 0f
mRipplePaint.alpha = (mRippleAlpha * 255).toInt()
mPaint.setShadowDepth(2 * mDensity)
invalidate()
}
}
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val viewHeight = max(height, mMinHeight.toInt())
when (mCurrentState) {
STATE_BUTTON, STATE_ANIMATION_STEP1 -> {
val cornerRadius = (mRadius - mButtonCorner) * (mScaleWidth / (width / 2 - viewHeight / 2).toFloat()) + mButtonCorner
mButtonRectF.left = mScaleWidth.toFloat()
mButtonRectF.right = (width - mScaleWidth).toFloat()
canvas.drawRoundRect(mButtonRectF, cornerRadius, cornerRadius, mPaint)
if (mCurrentState == STATE_BUTTON) {
canvas.drawText(mText, (width - mTextWidth) / 2, (viewHeight - mTextHeight) / 2 + mPadding * 2, mTextPaint)
if ((mTouchX > 0 || mTouchY > 0) && rippleEnable) {
canvas.clipRect(0f, mPadding, width.toFloat(), viewHeight - mPadding)
canvas.drawCircle(mTouchX, mTouchY, mRippleRadius, mRipplePaint)
}
}
}
STATE_ANIMATION_STEP2 -> {
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), (mRadius - mScaleHeight).toFloat(), mPaint)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
STATE_ANIMATION_LOADING -> {
mPath.reset()
mPath.addArc(mArcRectF, (270 + mAngle / 2).toFloat(), (360 - mAngle).toFloat())
if (mAngle != 0) {
mMatrix.setRotate(mDegree.toFloat(), (width / 2).toFloat(), (viewHeight / 2).toFloat())
mPath.transform(mMatrix)
mDegree += 10
}
canvas.drawPath(mPath, mStrokePaint)
}
STATE_STOP_LOADING -> {
mPath.reset()
mPath.addArc(mArcRectF, (270 + mAngle / 2).toFloat(), mEndAngle.toFloat())
if (mEndAngle != 360) {
mMatrix.setRotate(mDegree.toFloat(), (width / 2).toFloat(), (viewHeight / 2).toFloat())
mPath.transform(mMatrix)
mDegree += 10
}
canvas.drawPath(mPath, mStrokePaint)
}
STATE_ANIMATION_SUCCESS -> {
canvas.drawPath(mSuccessPath!!, mPathEffectPaint)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
STATE_ANIMATION_FAILED -> {
canvas.drawPath(mFailedPath!!, mPathEffectPaint)
canvas.drawPath(mFailedPath2!!, mPathEffectPaint2)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
}
}
/**
* start loading,play animation
*/
fun startLoading() {
if (mCurrentState == STATE_ANIMATION_FAILED && !resetAfterFailed) {
scaleFailedPath()
return
}
if (mCurrentState == STATE_BUTTON) {
mCurrentState = STATE_ANIMATION_STEP1
mPaint.clearShadowLayer()
playStartAnimation(false)
}
}
/**
* loading data successful
*/
fun loadingSuccessful() {
if (mLoadingAnimatorSet != null && mLoadingAnimatorSet!!.isStarted) {
mLoadingAnimatorSet!!.end()
mCurrentState = STATE_STOP_LOADING
playSuccessAnimation()
}
}
/**
* loading data failed
*/
fun loadingFailed() {
if (mLoadingAnimatorSet != null && mLoadingAnimatorSet!!.isStarted) {
mLoadingAnimatorSet!!.end()
mCurrentState = STATE_STOP_LOADING
playFailedAnimation()
}
}
fun cancelLoading() {
if (mCurrentState != STATE_ANIMATION_LOADING) {
return
}
cancel()
}
/**
* reset view to Button with animation
*/
fun reset(){
when(mCurrentState){
STATE_ANIMATION_SUCCESS -> scaleSuccessPath()
STATE_ANIMATION_FAILED -> scaleFailedPath()
}
}
private fun measureTextHeight(paint: Paint): Float{
val bounds = Rect()
paint.getTextBounds(mText, 0, mText.length, bounds)
return bounds.height().toFloat()
}
private fun createSuccessPath() {
if (mSuccessPath != null) {
mSuccessPath!!.reset()
} else {
mSuccessPath = Path()
}
val mLineWith = 2 * mDensity
val left = (width / 2 - mRadius).toFloat() + (mRadius / 3).toFloat() + mLineWith
val top = mPadding + (mRadius / 2).toFloat() + mLineWith
val right = (width / 2 + mRadius).toFloat() - mLineWith - (mRadius / 3).toFloat()
val bottom = (mLineWith + mRadius) * 1.5f + mPadding / 2
val xPoint = (width / 2 - mRadius / 6).toFloat()
mSuccessPath = Path().apply {
moveTo(left, mPadding + mRadius.toFloat() + mLineWith)
lineTo(xPoint, bottom)
lineTo(right, top)
}
mSuccessPathLength = PathMeasure(mSuccessPath, false).length
mSuccessPathIntervals = floatArrayOf(mSuccessPathLength, mSuccessPathLength)
}
private fun createFailedPath() {
if (mFailedPath != null) {
mFailedPath!!.reset()
mFailedPath2!!.reset()
} else {
mFailedPath = Path()
mFailedPath2 = Path()
}
val left = (width / 2 - mRadius + mRadius / 2).toFloat()
val top = mRadius / 2 + mPadding
mFailedPath!!.moveTo(left, top)
mFailedPath!!.lineTo(left + mRadius, top + mRadius)
mFailedPath2!!.moveTo((width / 2 + mRadius / 2).toFloat(), top)
mFailedPath2!!.lineTo((width / 2 - mRadius + mRadius / 2).toFloat(), top + mRadius)
mFailedPathLength = PathMeasure(mFailedPath, false).length
mFailedPathIntervals = floatArrayOf(mFailedPathLength, mFailedPathLength)
mPathEffectPaint2.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength)
}
private fun measureDimension(defaultSize: Int, measureSpec: Int) =
when (MeasureSpec.getMode(measureSpec)) {
MeasureSpec.EXACTLY -> MeasureSpec.getSize(measureSpec)
MeasureSpec.AT_MOST -> min(defaultSize, MeasureSpec.getSize(measureSpec))
MeasureSpec.UNSPECIFIED -> defaultSize
else -> defaultSize
}
private fun updateButtonColor() {
mPaint.color = if(isEnabled) mColorPrimary else mDisabledBgColor
mTextPaint.color = if(isEnabled) mTextColor else mDisabledTextColor
if(backgroundShader != null){
if(isEnabled) mPaint.shader = backgroundShader else mPaint.shader = null
}
invalidate()
}
private fun playTouchDownAnimation(){
ValueAnimator.ofFloat(0f, 1f)
.apply {
duration = 240
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val progress = valueAnimator.animatedValue as Float
mPaint.setShadowDepth((2 + 4 * progress) * mDensity)
mRippleRadius = width * progress
//mRipplePaint.alpha = (255 * mRippleAlpha * (1 - progress)).toInt()
invalidate()
}
}
.start()
}
private fun playRippleAnimation() {
ValueAnimator.ofFloat(
1f,
0f)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
val progress = valueAnimator.animatedValue as Float
mRipplePaint.alpha = (255 * mRippleAlpha * progress).toInt()
mPaint.setShadowDepth((2 + 4 * progress) * mDensity)
invalidate()
}
doOnEnd {
doClick()
}
}.start()
}
private fun doClick(){
mTouchX = 0f
mTouchY = 0f
mRipplePaint.alpha = (mRippleAlpha * 255).toInt()
mRippleRadius = 0f
invalidate()
performClick()
}
private fun playStartAnimation(isReverse: Boolean) {
val viewHeight = max(height, mMinHeight.toInt())
val animator = ValueAnimator.ofInt(
if (isReverse) width / 2 - viewHeight / 2 else 0,
if (isReverse) 0 else width / 2 - viewHeight / 2)
.apply {
duration = 400
interpolator = AccelerateDecelerateInterpolator()
startDelay = 100
addUpdateListener { valueAnimator ->
mScaleWidth = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = if (isReverse) STATE_BUTTON else STATE_ANIMATION_STEP2
if (mCurrentState == STATE_BUTTON) {
mPaint.setShadowDepth(2 * mDensity)
invalidate()
}
}
}
val animator2 = ValueAnimator.ofInt(if (isReverse) mRadius else 0, if (isReverse) 0 else mRadius)
.apply {
duration = 240
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
mScaleHeight = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = if (isReverse) STATE_ANIMATION_STEP1 else STATE_ANIMATION_LOADING
if (!isReverse) updateButtonColor()
}
}
val loadingAnimator = ValueAnimator.ofInt(30, 300)
.apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
mAngle = valueAnimator.animatedValue as Int
invalidate()
}
}
mLoadingAnimatorSet?.cancel()
mLoadingAnimatorSet = AnimatorSet()
mLoadingAnimatorSet!!.doOnEnd {
isEnabled = true
updateButtonColor()
}
if (isReverse) {
mLoadingAnimatorSet!!.playSequentially(animator2, animator)
mLoadingAnimatorSet!!.start()
return
}
mLoadingAnimatorSet!!.playSequentially(animator, animator2, loadingAnimator)
mLoadingAnimatorSet!!.start()
}
private fun playSuccessAnimation() {
createSuccessPath()
val animator = ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd { mCurrentState = STATE_ANIMATION_SUCCESS }
}
val successAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 500
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
val pathEffect = DashPathEffect(mSuccessPathIntervals, mSuccessPathLength - mSuccessPathLength * value)
mPathEffectPaint.pathEffect = pathEffect
invalidate()
}
}
AnimatorSet().apply {
playSequentially(animator, successAnimator)
doOnEnd {
animationEndAction?.invoke(AnimationType.SUCCESSFUL)
}
}.start()
}
private fun playFailedAnimation() {
createFailedPath()
val animator = ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd { mCurrentState = STATE_ANIMATION_FAILED }
}
val failedAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
mPathEffectPaint.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength - mFailedPathLength * value)
invalidate()
}
}
val failedAnimator2 = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
mPathEffectPaint2.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength - mFailedPathLength * value)
invalidate()
}
}
AnimatorSet().apply {
playSequentially(animator, failedAnimator, failedAnimator2)
doOnEnd {
if (resetAfterFailed) {
postDelayed({ scaleFailedPath() }, 1000)
}else{
animationEndAction?.invoke(AnimationType.FAILED)
}
}
}.start()
}
private fun cancel() {
mCurrentState = STATE_STOP_LOADING
ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
private fun scaleSuccessPath() {
val scaleMatrix = Matrix()
val viewHeight = max(height, mMinHeight.toInt())
ValueAnimator.ofFloat(1.0f, 0.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
scaleMatrix.setScale(value, value, (width / 2).toFloat(), (viewHeight / 2).toFloat())
mSuccessPath!!.transform(scaleMatrix)
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
private fun scaleFailedPath() {
val scaleMatrix = Matrix()
val viewHeight = max(height, mMinHeight.toInt())
ValueAnimator.ofFloat(1.0f, 0.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
scaleMatrix.setScale(value, value, (width / 2).toFloat(), (viewHeight / 2).toFloat())
mFailedPath!!.transform(scaleMatrix)
mFailedPath2!!.transform(scaleMatrix)
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
}
private fun Animator.doOnEnd(action: (animator: Animator?) -> Unit) {
this.addListener(object : Animator.AnimatorListener{
override fun onAnimationRepeat(animation: Animator?){}
override fun onAnimationEnd(animation: Animator?) = action(animation)
override fun onAnimationCancel(animation: Animator?){}
override fun onAnimationStart(animation: Animator?){}
})
}
private fun Paint.setShadowDepth(depth: Float){
this.setShadowLayer(depth, 0f, 2f, 0x6F000000.toInt())
} | library/src/main/java/com/dx/dxloadingbutton/lib/LoadingButton.kt | 3351609047 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.ios.category
import com.vanniktech.emoji.EmojiCategory
import com.vanniktech.emoji.ios.IosEmoji
internal class TravelAndPlacesCategory : EmojiCategory {
override val categoryNames: Map<String, String>
get() = mapOf(
"en" to "Places",
"de" to "Orte",
)
override val emojis = ALL_EMOJIS
private companion object {
val ALL_EMOJIS: List<IosEmoji> = TravelAndPlacesCategoryChunk0.EMOJIS + TravelAndPlacesCategoryChunk1.EMOJIS
}
}
| emoji-ios/src/commonMain/kotlin/com/vanniktech/emoji/ios/category/TravelAndPlacesCategory.kt | 1001718827 |
package io.polymorphicpanda.kspec.console
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.polymorphicpanda.kspec.context.Context
import io.polymorphicpanda.kspec.engine.execution.ExecutionResult
import io.polymorphicpanda.kspec.launcher.KSpecLauncher
import io.polymorphicpanda.kspec.launcher.reporter.BaseReporter
import org.junit.Test
import java.nio.file.Paths
/**
* @author Ranie Jade Ramiso
*/
class ConsoleRunnerTest {
@Test
fun testRun() {
val launcher = KSpecLauncher()
val reporter = BaseReporter()
launcher.addReporter(reporter)
val runner = ConsoleRunner(launcher)
runner.run(
"-s", Paths.get(this.javaClass.classLoader.getResource("specs_raw").toURI()).toString(),
"-f", "io.polymorphicpanda.kspec.sample.*"
)
assertThat(reporter.totalSuccessCount, !equalTo(0))
assertThat(reporter.totalIgnoredCount, !equalTo(0))
assertThat(reporter.totalFailureCount, !equalTo(0))
}
@Test
fun testPrintVersion() {
val launcher = KSpecLauncher()
val runner = ConsoleRunner(launcher)
runner.run(
"--version"
)
}
@Test
fun testPrintHelp() {
val launcher = KSpecLauncher()
val runner = ConsoleRunner(launcher)
runner.run(
"--help"
)
}
@Test
fun testRunWithCompile() {
val launcher = KSpecLauncher()
val builder = StringBuilder()
val reporter: BaseReporter = object: BaseReporter() {
override fun exampleGroupFinished(group: Context.ExampleGroup, result: ExecutionResult) {
super.exampleGroupFinished(group, result)
builder.appendln(group.description)
}
override fun exampleFinished(example: Context.Example, result: ExecutionResult) {
super.exampleFinished(example, result)
builder.appendln(example.description)
}
}
launcher.addReporter(reporter)
val runner = ConsoleRunner(launcher)
val spec = Paths.get(
javaClass.classLoader.getResource("specs_raw/io/polymorphicpanda/kspec/sample/SampleSpec.kt").toURI()
)
runner.run(
"-s", spec.toString()
)
val expected = """
it: an example
context: a nested group
describe: a sample group
io.polymorphicpanda.kspec.sample.SampleSpec
""".trimIndent()
assertThat(builder.trimEnd().toString(), equalTo(expected))
assertThat(reporter.totalFailureCount, equalTo(0))
assertThat(reporter.exampleSuccessCount, equalTo(1))
assertThat(reporter.exampleGroupSuccessCount, equalTo(3))
}
}
| kspec-console-runner/src/test/kotlin/io/polymorphicpanda/kspec/console/ConsoleRunnerTest.kt | 928840292 |
package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param href
*/
data class Link(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("href") val href: kotlin.String? = null
) {
}
| clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/Link.kt | 1818049293 |
package com.jetbrains.rider.plugins.unity.ui.unitTesting
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.jetbrains.rider.plugins.unity.model.frontendBackend.UnitTestLaunchPreference
import com.jetbrains.rider.plugins.unity.model.frontendBackend.frontendBackendModel
import com.jetbrains.rider.plugins.unity.ui.UnityUIBundle
import com.jetbrains.rider.projectView.solution
class UseUnityPlayLauncherAction : DumbAwareAction(PlayModeDescription,
UnityUIBundle.message("action.run.with.unity.editor.in.play.mode.description"), null) {
companion object {
val PlayModeDescription = UnityUIBundle.message("action.run.with.unity.editor.in.play.mode.text")
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
project.solution.frontendBackendModel.unitTestPreference.value = UnitTestLaunchPreference.PlayMode
}
override fun update(e: AnActionEvent) {
e.presentation.isVisible = true
}
} | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ui/unitTesting/UseUnityPlayLauncherAction.kt | 1427814683 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.codecs
import groovy.lang.Closure
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.ReadContext
import org.gradle.instantexecution.serialization.WriteContext
object ClosureCodec : Codec<Closure<*>> {
private
val beanCodec = BeanCodec()
override suspend fun WriteContext.encode(value: Closure<*>) {
// TODO - should write the owner, delegate and thisObject, replacing project and script references
beanCodec.run { encode(value.dehydrate()) }
}
override suspend fun ReadContext.decode(): Closure<*>? {
return beanCodec.run { decode() as Closure<*> }
}
}
| subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/ClosureCodec.kt | 1954681881 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.lib.input
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
/**
* @author toastkidjp
*/
object Inputs {
/**
* Show software keyboard.
*
* @param activity
* @param editText
*/
fun showKeyboard(activity: Activity, editText: EditText) {
val inputMethodManager = obtainInputManager(activity)
inputMethodManager?.showSoftInput(editText, 0)
}
/**
* Hide software keyboard.
*
* @param v
*/
fun hideKeyboard(v: View?) {
val manager = obtainInputManager(v?.context)
manager?.hideSoftInputFromWindow(v?.windowToken, 0)
}
private fun obtainInputManager(context: Context?): InputMethodManager? {
val inputMethodManager =
context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
?: return null
if (!inputMethodManager.isActive) {
return null
}
return inputMethodManager
}
/**
* Show software keyboard for input dialog.
* You should call this method from `onActivityCreated(savedInstanceState: Bundle?)`.
*
* @param window Nullable [Window] for calling setSoftInputMode.
*/
fun showKeyboardForInputDialog(window: Window?) {
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
}
} | lib/src/main/java/jp/toastkid/lib/input/Inputs.kt | 1043255021 |
package com.example.android.camera2basic
import android.media.Image
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.ByteBuffer
/**
* Saves a JPEG [Image] into the specified [File].
*/
internal class ImageSaver(
/**
* The JPEG image
*/
private val image: Image,
/**
* The file we save the image into.
*/
private val file: File
) : Runnable {
override fun run() {
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.remaining())
buffer.get(bytes)
var output: FileOutputStream? = null
try {
output = FileOutputStream(file).apply {
write(bytes)
}
} catch (e: IOException) {
Log.e(TAG, e.toString())
} finally {
image.close()
output?.let {
try {
it.close()
} catch (e: IOException) {
Log.e(TAG, e.toString())
}
}
}
}
companion object {
/**
* Tag for the [Log].
*/
private val TAG = "ImageSaver"
}
}
| kotlinApp/Application/src/main/java/com/example/android/camera2basic/ImageSaver.kt | 4018639532 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.google.android.horologist.media3.service
import android.annotation.SuppressLint
import androidx.media3.exoplayer.offline.Download
import androidx.media3.exoplayer.offline.DownloadManager
import androidx.media3.exoplayer.scheduler.Requirements
import com.google.android.horologist.media3.ExperimentalHorologistMedia3BackendApi
import com.google.android.horologist.media3.logging.ErrorReporter
import com.google.android.horologist.media3.logging.ErrorReporter.Category.Downloads
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.RequestType.MediaRequest
import com.google.android.horologist.networks.data.RequestType.MediaRequest.MediaRequestType
import com.google.android.horologist.networks.highbandwidth.HighBandwidthConnectionLease
import com.google.android.horologist.networks.highbandwidth.HighBandwidthNetworkMediator
import com.google.android.horologist.networks.request.HighBandwidthRequest
import com.google.android.horologist.networks.rules.NetworkingRulesEngine
/**
* Simple implementation of [DownloadManager.Listener] for downloading with
* a required high bandwidth network. Also includes event logging.
*/
@SuppressLint("UnsafeOptInUsageError")
@ExperimentalHorologistMedia3BackendApi
@ExperimentalHorologistNetworksApi
public class NetworkAwareDownloadListener(
private val appEventLogger: ErrorReporter,
private val highBandwidthNetworkMediator: HighBandwidthNetworkMediator,
private val networkingRulesEngine: NetworkingRulesEngine
) : DownloadManager.Listener {
private var networkRequest: HighBandwidthConnectionLease? = null
override fun onInitialized(downloadManager: DownloadManager) {
appEventLogger.logMessage("init", category = Downloads)
updateNetworkState(downloadManager)
}
override fun onDownloadsPausedChanged(
downloadManager: DownloadManager,
downloadsPaused: Boolean
) {
appEventLogger.logMessage("paused $downloadsPaused", category = Downloads)
}
override fun onDownloadChanged(
downloadManager: DownloadManager,
download: Download,
finalException: Exception?
) {
val percent = (download.percentDownloaded).toInt().coerceAtLeast(0)
appEventLogger.logMessage(
"download ${download.request.uri.lastPathSegment} $percent% ${finalException?.message.orEmpty()}",
category = Downloads
)
updateNetworkState(downloadManager)
}
override fun onDownloadRemoved(downloadManager: DownloadManager, download: Download) {
appEventLogger.logMessage("removed ${download.name}", category = Downloads)
}
override fun onIdle(downloadManager: DownloadManager) {
updateNetworkState(downloadManager)
appEventLogger.logMessage("idle", category = Downloads)
}
override fun onRequirementsStateChanged(
downloadManager: DownloadManager,
requirements: Requirements,
notMetRequirements: Int
) {
appEventLogger.logMessage("missingReqs $notMetRequirements", category = Downloads)
}
override fun onWaitingForRequirementsChanged(
downloadManager: DownloadManager,
waitingForRequirements: Boolean
) {
updateNetworkState(downloadManager)
appEventLogger.logMessage(
"waitingForRequirements $waitingForRequirements",
category = Downloads
)
}
private fun updateNetworkState(downloadManager: DownloadManager) {
val hasReadyDownloads =
downloadManager.currentDownloads.isNotEmpty() && !downloadManager.isWaitingForRequirements
if (hasReadyDownloads) {
if (networkRequest == null) {
val types =
networkingRulesEngine.supportedTypes(MediaRequest(MediaRequestType.Download))
val request = HighBandwidthRequest.from(types)
appEventLogger.logMessage(
"Requesting network for downloads $networkRequest",
category = Downloads
)
networkRequest = highBandwidthNetworkMediator.requestHighBandwidthNetwork(request)
}
} else {
if (networkRequest != null) {
appEventLogger.logMessage("Releasing network for downloads", category = Downloads)
networkRequest?.close()
networkRequest = null
}
}
}
private val Download.name: String
get() = this.request.uri.lastPathSegment ?: "unknown"
}
| media3-backend/src/main/java/com/google/android/horologist/media3/service/NetworkAwareDownloadListener.kt | 3749327832 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
@file:OptIn(ExperimentalLifecycleComposeApi::class)
package com.google.android.horologist.compose.layout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.StateFlow
public object StateUtils {
@Deprecated(
message = "Replace with collectAsStateWithLifecycle",
replaceWith = ReplaceWith(
"flow.collectAsStateWithLifecycle()",
"androidx.lifecycle.compose.collectAsStateWithLifecycle"
)
)
@Composable
public fun <T> rememberStateWithLifecycle(
flow: StateFlow<T>,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): State<T> = flow.collectAsStateWithLifecycle(
lifecycle = lifecycle,
minActiveState = minActiveState
)
}
| compose-layout/src/main/java/com/google/android/horologist/compose/layout/StateUtils.kt | 3167561683 |
package org.seasar.doma.kotlin.jdbc.criteria.declaration
import org.seasar.doma.jdbc.criteria.declaration.SetDeclaration
import org.seasar.doma.jdbc.criteria.metamodel.PropertyMetamodel
class KSetDeclaration(private val declaration: SetDeclaration) {
fun <PROPERTY> value(left: PropertyMetamodel<PROPERTY>, right: PROPERTY?) {
declaration.value(left, right)
}
fun <PROPERTY> value(
left: PropertyMetamodel<PROPERTY>,
right: PropertyMetamodel<PROPERTY>
) {
declaration.value(left, right)
}
}
| doma-kotlin/src/main/kotlin/org/seasar/doma/kotlin/jdbc/criteria/declaration/KSetDeclaration.kt | 2186845562 |
package com.inverse.unofficial.proxertv.ui.util
import android.support.v17.leanback.widget.ImageCardView
import android.support.v17.leanback.widget.Presenter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.inverse.unofficial.proxertv.R
/**
* Object that represents a loading cover
*/
object LoadingCover
/**
* Presents a [LoadingCover]
*/
class LoadingCoverPresenter : Presenter() {
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.view_loading_cover, parent, false)
val card = view.findViewById(R.id.loading_cover_image_card) as ImageCardView
card.setMainImageDimensions(BaseCoverPresenter.CARD_WIDTH, BaseCoverPresenter.CARD_HEIGHT)
return LoadingViewHolder(view)
}
override fun onBindViewHolder(viewHolder: ViewHolder?, item: Any?) {}
override fun onUnbindViewHolder(viewHolder: ViewHolder?) {}
private class LoadingViewHolder(view: View) : Presenter.ViewHolder(view)
} | app/src/main/java/com/inverse/unofficial/proxertv/ui/util/LoadingCoverPresenter.kt | 430017030 |
package com.eden.orchid.impl.themes
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.theme.Theme
import javax.inject.Inject
@Description(
value = "The default theme, which adds no assets and lets you build your theme entirely by custom templates.",
name = "Default"
)
class DefaultTheme @Inject
constructor(context: OrchidContext) : Theme(context, "Default", 100)
| OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/DefaultTheme.kt | 3511669976 |
/*
* Copyright (c) 2012-2017 Frederic Julian
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.fragments
import android.app.Dialog
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.view.WindowManager
abstract class ImmersiveDialogFragment : DialogFragment() {
override fun setupDialog(dialog: Dialog, style: Int) {
super.setupDialog(dialog, style)
// Make the box non-focusable before showing it
dialog.window?.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
}
override fun show(manager: FragmentManager, tag: String) {
super.show(manager, tag)
showImmersive(manager)
}
override fun show(transaction: FragmentTransaction, tag: String): Int {
val result = super.show(transaction, tag)
showImmersive(fragmentManager)
return result
}
private fun showImmersive(manager: FragmentManager) {
// It is necessary to call executePendingTransactions() on the FragmentManager
// before hiding the navigation bar, because otherwise getWindow() would raise a
// NullPointerException since the window was not yet created.
manager.executePendingTransactions()
// Copy flags from the activity, assuming it's fullscreen.
// It is important to do this after show() was called. If we would do this in onCreateDialog(),
// we would get a requestFeature() error.
dialog.window?.decorView?.systemUiVisibility = activity.window.decorView.systemUiVisibility
// Make the dialogs window focusable again
dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
}
} | TaskGame-Hero/src/main/java/net/fred/taskgame/hero/fragments/ImmersiveDialogFragment.kt | 1637015153 |
package com.hosshan.android.salad.repository.github.service
import com.hosshan.android.salad.repository.github.entity.Event
import retrofit2.http.GET
import retrofit2.http.Path
import rx.Observable
/**
* https://developer.github.com/v3/activity/events/
*/
interface EventsService {
@GET("/events")
fun events(): Observable<List<Event>>
@GET("/repos/{owner}/{repository}/events")
fun repositoryEvents(@Path("owner") owner: String, @Path("repository") repository: String): Observable<List<Event>>
@GET("/repos/{owner}/{repository}/issues/events")
fun repositoryIssueEvents(@Path("owner") owner: String, @Path("repository") repository: String): Observable<List<Event>>
@GET("/networks/{owner}/{repository}/events")
fun repositoryNetworkEvents(@Path("owner") owner: String, @Path("repository") repository: String): Observable<List<Event>>
@GET("/users/{username}/events")
fun userEvents(@Path("username") username: String): Observable<List<Event>>
@GET("/users/{username}/events/public")
fun publicUserEvents(@Path("username") username: String): Observable<List<Event>>
@GET("/users/{username}/received_events")
fun receivedUserEvents(@Path("username") username: String): Observable<List<Event>>
@GET("/users/{username}/received_events/public")
fun receivedPublicUserEvents(@Path("username") username: String): Observable<List<Event>>
@GET("/orgs/{org}/events")
fun orgEvents(@Path("org") org: String): Observable<List<Event>>
@GET("/users/{username}/events/orgs/{org}")
fun userOrgEvents(@Path("username") username: String, @Path("org") org: String): Observable<List<Event>>
}
| app/src/main/kotlin/com/hosshan/android/salad/repository/github/service/EventsService.kt | 2578271596 |
package it.mpp0
actual class ExpectedClass {
actual val platform: String = "macos"
}
| integration-tests/gradle/projects/it-multiplatform-0/src/macosMain/kotlin/it/mpp0/ExpectedClass.kt | 1388747262 |
package com.hosshan.android.salad
import dagger.Component
/**
* Created by shunhosaka on 15/10/02.
*/
@Component(modules = arrayOf(ReleaseAppModule::class, ReleaseDataModule::class))
public interface AppComponent : BaseAppComponent {
fun inject(app: DaggerApplication)
object Initializer {
fun init(app: DaggerApplication): AppComponent =
DaggerAppComponent.builder()
.debugAppModule(ReleaseAppModule(app))
.debugDataModule(ReleaseDataModule())
.build()
}
}
| app/src/release/kotlin/com/hosshan/android/salad/AppComponent.kt | 784242424 |
package org.jetbrains.dokka.base.translators.descriptors
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.DClasslike
/**
* Service that can be queried with [DRI] and source set to obtain a documentable for classlike.
*
* There are some cases when there is a need to process documentables of classlikes that were not defined
* in the project itself but are somehow related to the symbols defined in the documented project (e.g. are supertypes
* of classes defined in project).
*/
fun interface ExternalDocumentablesProvider {
/**
* Returns [DClasslike] matching provided [DRI] in specified source set.
*
* Result is null if compiler haven't generated matching class descriptor.
*/
fun findClasslike(dri: DRI, sourceSet: DokkaConfiguration.DokkaSourceSet): DClasslike?
} | plugins/base/src/main/kotlin/translators/descriptors/ExternalDocumentablesProvider.kt | 1393612940 |
package com.artfable.telegram.api.request
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.type.TypeReference
import com.artfable.telegram.api.TelegramBotMethod
import com.artfable.telegram.api.TelegramResponse
import com.artfable.telegram.api.Update
import com.artfable.telegram.api.UpdateType
/**
* @author aveselov
* @since 05/08/2020
*/
data class GetUpdatesRequest(
@JsonProperty("offset") val offset: Long? = null,
@JsonProperty("timeout") val timeout: Int? = null,
@JsonProperty("limit") val limit: Int? = null,
@JsonProperty("allowed_updates") val allowedUpdates: Array<UpdateType>? = null
) : TelegramRequest<@JvmSuppressWildcards List<Update>>(
TelegramBotMethod.GET_UPDATES,
object : TypeReference<TelegramResponse<List<Update>>>() {}) {
init {
timeout?.let { check(it >= 0) }
limit?.let { check(it in 1..100) }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GetUpdatesRequest
if (offset != other.offset) return false
if (timeout != other.timeout) return false
if (limit != other.limit) return false
if (allowedUpdates != null) {
if (other.allowedUpdates == null) return false
if (!allowedUpdates.contentEquals(other.allowedUpdates)) return false
} else if (other.allowedUpdates != null) return false
return true
}
override fun hashCode(): Int {
var result = offset?.hashCode() ?: 0
result = 31 * result + (timeout ?: 0)
result = 31 * result + (limit ?: 0)
result = 31 * result + (allowedUpdates?.contentHashCode() ?: 0)
return result
}
}
| src/main/kotlin/com/artfable/telegram/api/request/GetUpdatesRequest.kt | 1093579357 |
package com.automation.remarks.kirk.conditions
/**
* Created by sepi on 24.07.17.
*/
abstract class BaseCondition<in T> : Condition<T>()
class Not<in T>(val condition: Condition<T>) : BaseCondition<T>() {
val msg: String =
"""%s
expected not: %s
actual: %s
"""
override fun matches(item: T): Boolean {
return !condition.matches(item)
}
override fun description(item: T): Description {
return condition.description(item).apply {
diff = false
message = msg
}
}
override fun toString(): String {
return condition.toString()
}
}
fun <T> not(condition: Condition<T>): Condition<T> {
return Not(condition)
} | kirk-core/src/main/kotlin/com/automation/remarks/kirk/conditions/Not.kt | 2040466825 |
package com.yy.codex.uikit
import android.content.Context
import android.view.MotionEvent
import com.yy.codex.foundation.lets
/**
* Created by cuiminghui on 2017/3/9.
*/
internal fun UITableViewCell._initEditingTouches() {
val editingPanGesture = UIPanGestureRecognizer(this, "onEditingPanned:")
this._editingPanGesture = editingPanGesture
editingPanGesture.stealer = true
editingPanGesture.delegate = object : UIGestureRecognizer.Delegate {
override fun shouldBegin(gestureRecognizer: UIGestureRecognizer): Boolean {
return Math.abs((gestureRecognizer as UIPanGestureRecognizer).translation().y) < 8.0
}
}
addGestureRecognizer(editingPanGesture)
}
internal fun UITableViewCell._initEditingView() {
_editingView = UITableViewCellActionView(context)
}
internal fun UITableViewCell._enableEditingView() {
_editingPanGesture?.enabled = false
_editingView.clearViews()
lets(_tableView, _indexPath) { tableView, indexPath ->
tableView.delegate()?.editActionsForRow(tableView, indexPath)?.let {
_editingPanGesture?.enabled = it.size > 0
}
}
}
internal fun UITableViewCell._resetEditingView() {
_editingView.clearViews()
lets(_tableView, _indexPath) { tableView, indexPath ->
tableView.delegate()?.editActionsForRow(tableView, indexPath)?.let {
_editingView.resetViews(it.map {
return@map it.requestActionView(context, indexPath)
})
}
}
}
internal fun UITableViewCell._onEditingPanned(sender: UIPanGestureRecognizer) {
when (sender.state) {
UIGestureRecognizerState.Began -> {
_resetEditingView()
}
UIGestureRecognizerState.Changed -> {
layoutSubviews()
}
UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled, UIGestureRecognizerState.Failed -> {
editing = _editingPanGesture?.velocity()?.x ?: 0.0 < 80.0 && (_editingPanGesture?.velocity()?.x ?: 0.0 < -200.0 || -Math.ceil(_editingPanGesture?.translation()?.x ?: 0.0) > _editingView.contentWidth * 2 / 3)
UIViewAnimator.springWithBounciness(1.0, 20.0, Runnable { _updateFrames() }, null)
if (editing) {
val maskView = UITableViewCellActionMaskView(context)
maskView.addGestureRecognizer(UITapGestureRecognizer(this, "_endEditing"))
maskView.touchesView = _editingView
maskView.frame = _tableView?.frame ?: CGRect(0, 0, 0, 0)
_tableView?.superview?.addSubview(maskView)
this._editingMaskView = maskView
}
}
}
}
internal class UITableViewCellActionView(context: Context) : UIView(context) {
var contentWidth = 0.0
fun clearViews() {
subviews.forEach(UIView::removeFromSuperview)
}
fun resetViews(views: List<UITableViewRowActionView>) {
views.forEach {
addSubview(it)
}
contentWidth = views.sumByDouble { it.contentWidth }
}
override fun layoutSubviews() {
super.layoutSubviews()
if (contentWidth <= 0.0) {
return
}
val percentage = frame.width / contentWidth
var currentX = 0.0
subviews.forEachIndexed { idx, subview ->
val subview = (subview as? UITableViewRowActionView) ?: return@forEachIndexed
subview.frame = CGRect(currentX, 0.0, subview.contentWidth * percentage + 1.0, frame.height)
currentX += subview.contentWidth * percentage
}
}
}
private class UITableViewCellActionMaskView(context: Context): UIView(context) {
internal var touchesView: UIView? = null
override fun hitTest(point: CGPoint, event: MotionEvent): UIView? {
touchesView?.let {
if (UIViewHelpers.pointInside(it, this.convertPoint(point, it))) {
return null
}
}
return super.hitTest(point, event)
}
} | library/src/main/java/com/yy/codex/uikit/UITableViewCell_Editing.kt | 2675980855 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.handlers.util
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.vladsch.flexmark.util.sequence.RepeatedSequence
import com.vladsch.md.nav.actions.api.MdElementContextInfoProvider
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.BlockPrefixes
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdPsiImplUtil.isWhitespaceOrBlankLine
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.settings.ListIndentationType
import com.vladsch.md.nav.settings.MdRenderingProfileManager
import com.vladsch.md.nav.util.format.MdFormatter
import com.vladsch.plugin.util.maxLimit
import com.vladsch.plugin.util.minLimit
import com.vladsch.plugin.util.psi.isTypeIn
import com.vladsch.plugin.util.psi.isTypeOf
import com.vladsch.plugin.util.toBased
import java.util.*
open class ListItemContext(
val context: CaretContextInfo,
val listElement: MdListImpl,
val listItemElement: MdListItemImpl,
val lineOffset: Int,
val isEmptyItem: Boolean,
val isTaskItem: Boolean,
val isItemDone: Boolean,
val wrappingContext: WrappingContext
) {
fun canIndentItem(): Boolean {
if (isNonFirstListItem()) return true
// see if it preceded by a list item
val listElement = listElement
val listLevel = getListLevel(listElement)
var prevSibling = listElement.prevSibling
while (prevSibling != null && isWhitespaceOrBlankLine(prevSibling.node.elementType)) prevSibling = prevSibling.prevSibling
while (prevSibling != null && prevSibling !is PsiFile && prevSibling.node.elementType !in listOf(MdTypes.BULLET_LIST, MdTypes.ORDERED_LIST)) {
prevSibling = prevSibling.parent
}
if (prevSibling == null || prevSibling is PsiFile) return false
if (prevSibling.javaClass != listElement.javaClass) {
// see if common mark where list types must match
val profile = MdRenderingProfileManager.getProfile(listElement.containingFile)
if (profile.parserSettings.parserListIndentationType == ListIndentationType.COMMONMARK) {
return false
}
}
val prevListLevel = getListLevel(prevSibling)
return prevListLevel >= listLevel
}
fun canUnIndentItem(): Boolean {
return isNonFirstLevelList()
}
fun isNonFirstLevelList(): Boolean {
var element = listElement.parent ?: return false
while (!(element is MdList)) {
if (element is PsiFile || element.node == null) return false
element = element.parent ?: return false
}
return element.isTypeOf(MdTokenSets.LIST_ELEMENT_TYPES)
}
fun isNonFirstListItem(): Boolean {
val listItemElement = listItemElement
val listElement = listElement
return listElement.firstChild !== listItemElement
}
open fun indentItem(adjustCaret: Boolean, onlyEmptyItemLine: Boolean) {
if (!canIndentItem()) return
// need to take all its contents and indent
val list = listElement
val listItem = listItemElement
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val caretLineInItem = context.caretLine - wrappingContext.firstLine
// indent this item by inserting 4 spaces for it and all its elements and changing its number to 1
val itemLines = MdPsiImplUtil.linesForWrapping(listItem, true, true, true, context)
var caretDelta = 0
var linesAdded = 0
// see if we need to insert a blank line before, if the previous item's last child is not the first indenting and not blank line
val prevSibling = context.findElementAt(context.offsetLineStart(listItem.node.startOffset)!! - 1)
if (prevSibling != null && !MdPsiImplUtil.isPrecededByBlankLine(listItem)) {
var blockElement = MdPsiImplUtil.getBlockElement(listItem)
if (blockElement != null && blockElement.node.elementType == MdTypes.PARAGRAPH_BLOCK) {
if (blockElement == MdPsiImplUtil.findChildTextBlock(blockElement.parent)?.parent) blockElement = blockElement.parent
}
if (blockElement !is MdListItemImpl) {
// add a blank line
if (blockElement == null || !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
itemLines.insertLine(0, itemLines[0].prefix, "")
linesAdded++
}
}
}
val prevListItem = prevListItem(list, listItem) ?: listItem
val listItemPrefixes = (prevListItem as MdListItemImpl).itemPrefixes(prefixes, context)
val prefixedLines = itemLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, listItemPrefixes.childPrefix, listItemPrefixes.childContPrefix)
// adjust for prefix change
// add 1 char for every \n added, plus one prefix for every line added plus one prefix change for every additional line caret is offset from the first line
val prefixChange = prefixedLines[0].prefixLength - itemLines[0].prefixLength
caretDelta += linesAdded + (linesAdded * listItemPrefixes.childPrefix.length) + prefixChange * (caretLineInItem + 1)
// need to adjust the replaced end to include the EOL, if not done for empty task items this causes an extra \n to be left in the document
val postEditNodeEnd = context.postEditNodeEnd(listItem.node)
val virtualSpaces = context.editor.caretModel.logicalPosition.column - (context.caretOffset - context.document.getLineStartOffset(context.document.getLineNumber(context.caretOffset)))
var endDelta = 0
while (postEditNodeEnd + endDelta < context.document.textLength && !context.document.charsSequence.subSequence(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta).endsWith("\n")) {
endDelta++
}
// need to insert trailing spaces after an empty list item
if (isEmptyItem) {
val trailingSpaces = context.beforeCaretChars.toBased().countTrailingSpaceTab()
if (trailingSpaces > 0) {
prefixedLines.setLine(0, prefixedLines[0].prefix, prefixedLines[0].text.append(RepeatedSequence.ofSpaces(trailingSpaces)))
}
}
context.document.replaceString(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta, prefixedLines.toString(1, 1))
val caretOffset = context.adjustedDocumentPosition((context.caretOffset + caretDelta).maxLimit(context.charSequence.length))
if (adjustCaret) {
if (endDelta > 0 || virtualSpaces > 0) {
// adjust for any trailing spaces after the marker that were removed for an empty item
val pos = context.editor.offsetToLogicalPosition(caretOffset.adjustedOffset - (endDelta - 1).minLimit(0))
context.editor.caretModel.moveToLogicalPosition(LogicalPosition(pos.line, pos.column + (endDelta - 1).minLimit(0) + virtualSpaces))
} else {
// System.out.println("Adjusting: change $prefixChange, line $caretLineInItem, caretDelta $caretDelta")
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
}
}
// this will make this item the next after the parent list item
open fun unIndentItem(adjustCaret: Boolean, onlyEmptyItemLine: Boolean) {
if (!canUnIndentItem()) return
val list = listElement
val listItem = listItemElement
val parentListItem = getParentListItemElement(list)
val parentList = if (parentListItem != null) getParentListElement(parentListItem) else null
val parentPrefixes = if (parentList != null) MdPsiImplUtil.getBlockPrefixes(parentList, null, context) else BlockPrefixes.EMPTY
val caretLineInItem = context.caretLine - wrappingContext.firstLine
// un indent this item by inserting the previous parent's prefix
val itemLines = MdPsiImplUtil.linesForWrapping(listItem, true, true, true, context)
var caretDelta = 0
val linesAdded = 0
val prefixedLines = itemLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, parentPrefixes.childPrefix, parentPrefixes.childContPrefix)
// adjust for prefix change
// add 1 char for every \n added, plus one prefix for every line added plus one prefix change for every additional line caret is offset from the first line
val prefixChange = prefixedLines[0].prefixLength - itemLines[0].prefixLength
caretDelta += linesAdded + (linesAdded * parentPrefixes.childPrefix.length) + prefixChange * (caretLineInItem + 1)
// need to adjust the replaced end to include the EOL, if not done for empty task items this causes an extra \n to be left in the document
val postEditNodeEnd = context.postEditNodeEnd(listItem.node)
val virtualSpaces = context.editor.caretModel.logicalPosition.column - (context.caretOffset - context.document.getLineStartOffset(context.document.getLineNumber(context.caretOffset)))
var endDelta = 0
while (postEditNodeEnd + endDelta < context.document.textLength && !context.document.charsSequence.subSequence(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta).endsWith("\n")) {
endDelta++
}
context.document.replaceString(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta, prefixedLines.toString(1, 1))
val caretOffset = context.adjustedDocumentPosition((context.caretOffset + caretDelta).minLimit(0))
if (adjustCaret) {
if (endDelta > 0 || virtualSpaces > 0) {
// adjust for any trailing spaces after the marker that were removed for an empty item
val pos = context.editor.offsetToLogicalPosition(caretOffset.adjustedOffset - (endDelta - 1).minLimit(0))
context.editor.caretModel.moveToLogicalPosition(LogicalPosition(pos.line, pos.column + (endDelta - 1).minLimit(0) + virtualSpaces))
} else {
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
}
}
open fun addItem(adjustCaret: Boolean, removeDoneMarker: Boolean) {
val startLineOffset = context.offsetLineStart(context.caretOffset)
val endLineOffset = context.offsetLineEnd(context.caretOffset)
val list = listElement
if (startLineOffset != null && endLineOffset != null) {
val listItem = listItemElement
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val prefix = prefixes.childPrefix
// take the prefix from wrapping context
val itemOnlyPrefix = listItem.actualTextPrefix(context, true).toString()
var itemPrefix = prefix.toString() + itemOnlyPrefix //wrappingContext.prefixText().toString()
if (removeDoneMarker) {
val taskMarkerPos = itemPrefix.toLowerCase().indexOf("[x]")
if (taskMarkerPos > 0) {
// replace by not completed task
itemPrefix = itemPrefix.substring(0, taskMarkerPos + 1) + " " + itemPrefix.substring(taskMarkerPos + 2)
}
}
// if prefix was inserted then it will have not just whitespace
var lastPos = startLineOffset
LOG.debug("replacing start of line prefix: '${context.charSequence.subSequence(lastPos, endLineOffset)}' with: '$itemPrefix'")
while (lastPos < endLineOffset) {
val c = context.charSequence[lastPos]
if (!(c.isWhitespace() || context.isIndentingChar(c))) break
lastPos++
}
context.document.replaceString(startLineOffset, lastPos, itemPrefix)
val prefixLength = itemPrefix.length
val caretOffset = context.adjustedDocumentPosition(startLineOffset + prefixLength)
if (adjustCaret) {
context.editor.caretModel.currentCaret.moveToOffset(caretOffset.adjustedOffset)
}
}
}
open fun removeItem(adjustCaret: Boolean, willBackspace: Boolean) {
val list = listElement
val listItem = listItemElement
val listMarkerNode = listItem.firstChild.node
val startLineOffset = context.offsetLineStart(context.caretOffset)
if (startLineOffset != null) {
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val prefix = prefixes.childPrefix
var replacePrefix = if (willBackspace) " " else ""
var adjustCaretOffset = if (willBackspace) 1 else 0
val nodeStartOffset = context.postEditNodeStart(listMarkerNode)
val lastMarkerNode = MdPsiImplUtil.nextNonWhiteSpaceSibling(listMarkerNode) ?: listMarkerNode
val nodeEndOffset = context.postEditNodeEnd(lastMarkerNode)
// see if we need to insert a blank line before, if the previous item's last child is not the first indenting and not blank line
if (!isEmptyItem) {
val prevSibling = context.findElementAt(context.offsetLineStart(listItem.node.startOffset)!! - 1)
if (prevSibling != null) {
if (prevSibling !is MdBlankLine) {
val blockElement = MdPsiImplUtil.getBlockElement(prevSibling)
if (blockElement == null || !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
// add a blank line
replacePrefix = "\n" + prefix + replacePrefix
adjustCaretOffset += prefix.length + 1
}
}
}
// see if we need to insert a blank line after, if the item's last child is not the first indenting and not blank line
val nextSibling = listItem.nextSibling
if (nextSibling !is MdBlankLine) {
if (listItem.children.size > 1) {
val childBlockElement = MdPsiImplUtil.getBlockElement(listItem.lastChild)
if (childBlockElement != null && !MdPsiImplUtil.isFollowedByBlankLine(childBlockElement)) {
val blockEndOffset = context.postEditNodeEnd(childBlockElement.node)
context.document.insertString(blockEndOffset, prefix.toString() + "\n")
}
}
// add a blank line after the paragraph or text
val blockElement = MdPsiImplUtil.findChildTextBlock(listItem)
if (blockElement != null && !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
val blockEndOffset = context.postEditNodeEnd(blockElement.node)
context.document.insertString(blockEndOffset, prefix.toString() + "\n")
}
}
context.document.replaceString(nodeStartOffset, if (willBackspace) context.wrappingContext?.firstPrefixEnd
?: nodeEndOffset else nodeEndOffset, replacePrefix)
} else {
context.document.replaceString(nodeStartOffset, if (willBackspace) context.wrappingContext?.firstPrefixEnd
?: nodeEndOffset else nodeEndOffset, replacePrefix + if (willBackspace) "" else "\n")
}
val caretOffset = context.adjustedDocumentPosition(nodeStartOffset)
if (adjustCaret) {
context.editor.caretModel.currentCaret.moveToOffset(caretOffset.adjustedOffset + adjustCaretOffset)
}
}
}
companion object {
private val LOG = Logger.getInstance("com.vladsch.md.nav.editor.handlers.list")
@JvmField
val TRACE_LIST_ITEM_EDIT: Boolean = false
@JvmStatic
fun getContext(context: CaretContextInfo, preEditListItemElement: PsiElement? = null): ListItemContext? {
val caretOffset = context.caretOffset
var caretLine = context.offsetLineNumber(context.preEditOffset(caretOffset))!!
var useContext = context
if (MdPsiImplUtil.isBlankLine(context.findElementAt(caretOffset))) {
// go up to non blank and check
while (caretLine > 0) {
caretLine--
val startIndex = context.lineStart(caretLine)
val endIndex = context.lineEnd(caretLine)
if (startIndex != null && endIndex != null && startIndex < endIndex) {
if (!MdPsiImplUtil.isBlankLine(context.file.findElementAt(endIndex - 1))) {
// can find start here
useContext = CaretContextInfo.subContext(context, endIndex)
break
}
}
if (context.caretLine - caretLine > 1) return null
}
}
val wrappingContext = useContext.wrappingContext?.withMainListItem(context, preEditListItemElement) ?: return null
if (wrappingContext.mainElement is MdListItem) {
if (wrappingContext.mainElement === preEditListItemElement || wrappingContext.formatElement == null || MdPsiImplUtil.isFirstIndentedBlock(wrappingContext.formatElement, false)) {
val nextSibling = MdPsiImplUtil.nextNonWhiteSpaceSibling(wrappingContext.mainElement.firstChild.node)
val isTaskItem = nextSibling.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)
val isItemDone = isTaskItem && nextSibling != null && nextSibling.elementType != MdTypes.TASK_ITEM_MARKER
val listElement = getParentListElement(wrappingContext.mainElement) as MdListImpl?
val listItemElement = wrappingContext.mainElement as? MdListItemImpl
if (listElement != null && listItemElement != null) {
return MdElementContextInfoProvider.PROVIDER.value.getListItemContext(context,
listElement,
listItemElement,
context.caretLine - caretLine,
wrappingContext.startOffset == wrappingContext.endOffset,
isTaskItem,
isItemDone,
wrappingContext)
}
}
}
return null
}
@JvmStatic
fun lastListItem(list: PsiElement): MdListItemImpl? {
var childListItem = list.lastChild
while (childListItem != null && childListItem !is MdListItemImpl) childListItem = childListItem.prevSibling
return childListItem as? MdListItemImpl
}
@JvmStatic
fun listItemCount(list: PsiElement?): Int {
var items = 0
if (list != null) {
for (child in list.children) {
if (child is MdListItemImpl) items++
}
}
return items
}
fun getParentListElement(listItem: PsiElement): PsiElement? {
var element = listItem
while (element !is MdList) {
element = element.parent ?: return null
if (element is PsiFile || element.node == null) return null
}
return element
}
fun getParentListItemElement(list: PsiElement): PsiElement? {
var element = list.parent ?: return null
while (element !is MdListItem) {
element = element.parent ?: return null
if (element is PsiFile || element.node == null) return null
}
return element
}
fun prevListItem(list: PsiElement, listItem: PsiElement): PsiElement? {
var prevListItem: PsiElement? = null
for (item in list.children) {
if (item === listItem) break
if (item is MdListItem) prevListItem = item
}
return prevListItem
}
fun getListLevel(listElement: PsiElement): Int {
@Suppress("NAME_SHADOWING")
var listElement = listElement
var listLevel = 0
while (listElement !is PsiFile) {
if (listElement is MdList) listLevel++
listElement = listElement.parent ?: break
}
return listLevel
}
enum class AddBlankLineType(val addBefore: Boolean, val addAfter: Boolean) {
NONE(false, false), AFTER(false, true), BEFORE(true, false), AROUND(true, true)
}
@JvmStatic
fun loosenListItems(listElement: PsiElement, listItems: Set<PsiElement>? = null, maxWanted: Int = Int.MAX_VALUE): Pair<List<AddBlankLineType>, Int> {
val result = ArrayList<AddBlankLineType>()
val listItemCount = listItemCount(listElement)
var listItemOrdinal = 0
var state = 0
if (listItemCount < 2 || listElement !is MdList) {
result.add(AddBlankLineType.NONE)
return Pair(result, state)
}
for (item in listElement.children) {
if (item !is MdListItem) {
continue
}
var addBlankLineType = AddBlankLineType.NONE
if (listItems == null || listItems.contains(item)) {
if (!(item.nextSibling == null || item.nextSibling.isTypeOf(MdTokenSets.BLANK_LINE_SET)) && !MdPsiImplUtil.isFollowedByBlankLine(item)) {
if (listItemOrdinal == listItemCount - 1) {
if (listElement.parent is MdListItem) {
} else {
addBlankLineType = AddBlankLineType.AFTER
}
} else {
addBlankLineType = AddBlankLineType.AFTER
}
}
if (listItemOrdinal == 0 && MdFormatter.listNeedsBlankLineBefore(listElement, null, false)) {
val startOffset = item.node.startOffset
if (startOffset > 0) {
if (!addBlankLineType.addAfter) addBlankLineType = AddBlankLineType.BEFORE
else addBlankLineType = AddBlankLineType.AROUND
}
}
result.add(addBlankLineType)
if (addBlankLineType.addAfter) ++state
if (addBlankLineType.addBefore) ++state
if (state >= maxWanted) return Pair(result, state)
}
listItemOrdinal++
}
return Pair(result, state)
}
@JvmStatic
fun tightenListItems(listElement: PsiElement, listItems: Set<PsiElement>? = null, maxWanted: Int = Int.MAX_VALUE): Pair<List<PsiElement>, Int> {
val result = ArrayList<PsiElement>()
val listItemCount = listItemCount(listElement)
var listItemOrdinal = 0
var state = 0
if (listItemCount < 2 || listElement !is MdList) {
return Pair(result, state)
}
loopFor@
for (item in listElement.children) {
if (item !is MdListItem) {
continue
}
if (listItems == null || listItems.contains(item)) {
if (listItemOrdinal == 0 && MdPsiImplUtil.parentSkipBlockQuote(listElement) is MdListItem && !MdFormatter.listNeedsBlankLineBefore(listElement, null, true)) {
val prevSibling = MdPsiImplUtil.prevNonWhiteSpaceSibling(item.prevSibling)
if (prevSibling is MdParagraph) {
// see if this is our parent item paragraph
val parent = listElement.parent
if (parent is MdListItem) {
if (parent.isFirstItemBlock(prevSibling)) {
var blankLine = MdPsiImplUtil.precedingBlankLine(item)
val index = result.size
while (blankLine != null) {
result.add(index, blankLine)
state++
if (state >= maxWanted) break@loopFor
blankLine = MdPsiImplUtil.precedingBlankLine(blankLine)
}
}
}
}
}
if (listItemOrdinal != listItemCount - 1) {
var blankLine = MdPsiImplUtil.followingBlankLine(item)
while (blankLine != null) {
result.add(blankLine)
state++
if (state >= maxWanted) break@loopFor
blankLine = MdPsiImplUtil.followingBlankLine(blankLine)
}
}
}
listItemOrdinal++
}
return Pair(result, state)
}
@JvmStatic
fun canTightenList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return listItemCount(listElement) > 1 && tightenListItems(listElement, listItems, 1).second > 0
}
@JvmStatic
fun canLoosenList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return listItemCount(listElement) > 1 && loosenListItems(listElement, listItems, 1).second > 0
}
@JvmStatic
fun isLooseList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return !canTightenList(listElement, listItems)
}
@JvmStatic
fun isTightList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return !canLoosenList(listElement, listItems)
}
@JvmStatic
fun makeLooseList(context: CaretContextInfo, listElement: PsiElement, listItems: Set<PsiElement>?) {
val caretOffset = context.adjustedDocumentPosition(context.caretOffset)
val prefixes = MdPsiImplUtil.getBlockPrefixes(listElement, null, context)
val (itemList, _) = loosenListItems(listElement, listItems)
val children = listElement.children
var i = listItems?.size ?: listItemCount(listElement)
for (item in children.reversed()) {
if (item !is MdListItemImpl || listItems != null && !listItems.contains(item)) continue
val insertType = itemList[--i]
if (insertType.addAfter) {
context.document.insertString(context.postEditNodeEnd(item.node), prefixes.childPrefix.toString() + "\n")
}
if (insertType.addBefore) {
context.document.insertString(context.offsetLineStart(context.postEditNodeStart(item.node))!!, prefixes.childPrefix.toString() + "\n")
}
}
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
@JvmStatic
fun makeTightList(context: CaretContextInfo, listElement: PsiElement, listItems: Set<PsiElement>?) {
val (blankLines, _) = tightenListItems(listElement, listItems)
val caretOffset = context.adjustedDocumentPosition(context.caretOffset)
for (line in blankLines.reversed()) {
val startOffset = line.node.startOffset
val endOffset = startOffset + line.node.textLength
context.document.deleteString(startOffset, endOffset.maxLimit(context.charSequence.length))
}
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
fun listItemOrdinal(list: PsiElement, listItem: PsiElement): Int {
var listItemOrdinal = 0
for (item in list.children) {
if (item !is MdListItem) continue
listItemOrdinal++
if (item === listItem) break
}
return listItemOrdinal
}
}
}
| src/main/java/com/vladsch/md/nav/actions/handlers/util/ListItemContext.kt | 1196678399 |
package ilove.quark.us
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
/**
* Example JPA entity.
*
* To use it, get access to a JPA EntityManager via injection.
*
* ```kotlin
* @Inject
* lateinit var em:EntityManager;
*
* fun doSomething() {
* val entity1 = MyKotlinEntity();
* entity1.field = "field-1"
* em.persist(entity1);
*
* val entities:List<MyKotlinEntity> = em.createQuery("from MyEntity", MyKotlinEntity::class.java).getResultList()
* }
* ```
*/
@Entity
class MyKotlinEntity {
@get:GeneratedValue
@get:Id
var id: Long? = null
var field: String? = null
} | integration-tests/devtools/src/test/resources/__snapshots__/HibernateOrmCodestartTest/testContent/src_main_kotlin_ilove_quark_us_MyKotlinEntity.kt | 1656626193 |
package org.roylance.yaorm.services.phoenix
import org.roylance.yaorm.services.IConnectionSourceFactory
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.sql.Statement
class PhoenixConnectionSourceFactory @Throws(ClassNotFoundException::class, SQLException::class)
constructor(host: String) : IConnectionSourceFactory {
private val actualReadConnection: Connection
private val actualWriteConnection: Connection
private var isClosed: Boolean = false
init {
Class.forName(JDBCDriverName)
val jdbcUrl = String.format(JDBCUrl, host)
this.actualReadConnection = DriverManager.getConnection(jdbcUrl)
this.actualWriteConnection = DriverManager.getConnection(jdbcUrl)
}
override val readConnection: Connection
get() {
if (this.isClosed) {
throw SQLException("already closed...")
}
return this.actualReadConnection
}
override val writeConnection: Connection
get() {
if (this.isClosed) {
throw SQLException("already closed...")
}
return this.actualWriteConnection
}
override fun close() {
if (!this.isClosed) {
this.readConnection.close()
this.writeConnection.close()
}
this.isClosed = true
}
override fun generateUpdateStatement(): Statement {
return this.writeConnection.createStatement()
}
override fun generateReadStatement(): Statement {
return this.readConnection.createStatement()
}
companion object {
private val JDBCDriverName = "org.apache.phoenix.jdbc.PhoenixDriver"
private val JDBCUrl = "jdbc:phoenix:%1\$s:/hbase-unsecure"
}
} | yaorm/src/main/java/org/roylance/yaorm/services/phoenix/PhoenixConnectionSourceFactory.kt | 2974694609 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.psi.PsiElement
import com.intellij.util.Query
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsEnumItem
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.searchForImplementations
import org.rust.lang.core.psi.ext.union
/**
* Annotates trait declaration with an icon on the gutter that allows to jump to
* its implementations.
*
* See [org.rust.ide.navigation.goto.RsImplsSearch]
*/
class RsImplsLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (el in elements) {
val (query, anchor) = implsQuery(el) ?: continue
val targets: NotNullLazyValue<Collection<PsiElement>> = NotNullLazyValue.createValue { query.findAll() }
val info = NavigationGutterIconBuilder
.create(RsIcons.IMPLEMENTED)
.setTargets(targets)
.setPopupTitle("Go to implementation")
.setTooltipText("Has implementations")
.createLineMarkerInfo(anchor)
result.add(info)
}
}
companion object {
fun implsQuery(psi: PsiElement): Pair<Query<RsImplItem>, PsiElement>? {
val (query, anchor) = when (psi) {
is RsTraitItem -> psi.searchForImplementations() to psi.trait
is RsStructItem -> psi.searchForImplementations() to (psi.struct ?: psi.union)!!
is RsEnumItem -> psi.searchForImplementations() to psi.enum
else -> return null
}
// Ideally, we want to avoid showing an icon if there are no implementations,
// but that might be costly. To save time, we always show an icon, but calculate
// the actual icons only when the user clicks it.
// if (query.isEmptyQuery) return null
return query to anchor
}
}
}
| src/main/kotlin/org/rust/ide/annotator/RsImplsLineMarkerProvider.kt | 3500780076 |
/*
AndroidSwissKnife
Copyright (C) 2016 macleod2486
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see [http://www.gnu.org/licenses/].
*/
package com.macleod2486.androidswissknife.components
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.NfcManager
import android.nfc.tech.Ndef
import androidx.fragment.app.FragmentActivity
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.macleod2486.androidswissknife.R
class NFCTool(var activity: FragmentActivity) : View.OnClickListener {
lateinit var manager: NfcManager
lateinit var adapter: NfcAdapter
lateinit var entryText: EditText
override fun onClick(view: View) {
Log.i("NFCTool", "Clicked")
manager = activity.getSystemService(Context.NFC_SERVICE) as NfcManager
adapter = manager.defaultAdapter
if (view.id == R.id.writeNFC) {
adapter.disableForegroundDispatch(activity)
Log.i("NFCTool", "Writing")
write()
}
if (view.id == R.id.clearText) {
Log.i("NFCTool", "Clearing text")
entryText = activity.findViewById<View>(R.id.textEntry) as EditText
entryText.setText("")
}
}
private fun write() {
Log.i("NFCTool", "Write")
entryText = activity.findViewById<View>(R.id.textEntry) as EditText
setUpWrite(entryText.text.toString())
}
private fun setUpWrite(message: String) {
Log.i("NFCTool", "Message received $message")
val nfcIntent = Intent(activity.applicationContext, NFCActivity::class.java)
nfcIntent.putExtra("NFCMode", "write")
nfcIntent.putExtra("NFCMessage", message)
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pendingIntent = PendingIntent.getActivity(activity, 0, nfcIntent, 0)
val filter = IntentFilter()
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED)
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED)
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED)
val filterArray = arrayOf(filter)
val techListsArray = arrayOf(arrayOf(Ndef::class.java.name), arrayOf(Ndef::class.java.name))
adapter.disableReaderMode(activity)
adapter.enableForegroundDispatch(activity, pendingIntent, filterArray, techListsArray)
Toast.makeText(activity, "Please scan tag with device.", Toast.LENGTH_LONG).show()
}
} | app/src/main/java/com/macleod2486/androidswissknife/components/NFCTool.kt | 692355812 |
package com.garpr.android.extensions
import android.app.Activity
import android.app.ActivityManager
import android.app.NotificationManager
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.view.inputmethod.InputMethodManager
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
val Context.activity: Activity?
get() {
if (this is Activity) {
return this
}
if (this is ContextWrapper) {
var context = this
do {
context = (context as ContextWrapper).baseContext
if (context is Activity) {
return context
}
} while (context is ContextWrapper)
}
return null
}
val Context.activityManager: ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
@ColorInt
@Throws(Resources.NotFoundException::class)
fun Context.getAttrColor(@AttrRes attrResId: Int): Int {
val attrs = intArrayOf(attrResId)
val ta = obtainStyledAttributes(attrs)
if (!ta.hasValue(0)) {
ta.recycle()
throw Resources.NotFoundException("unable to find resId ($attrResId): " +
resources.getResourceEntryName(attrResId))
}
val color = ta.getColor(0, 0)
ta.recycle()
return color
}
val Context.inputMethodManager: InputMethodManager
get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val Context.notificationManagerCompat: NotificationManagerCompat
get() = NotificationManagerCompat.from(this)
fun Context.requireActivity(): Activity {
return checkNotNull(activity) { "Context ($this) is not attached to an Activity" }
}
fun Context.requireDrawable(@DrawableRes id: Int): Drawable {
return ContextCompat.getDrawable(this, id) ?: throw Resources.NotFoundException(
"unable to find Drawable for resId ($id): ${resources.getResourceEntryName(id)}")
}
| smash-ranks-android/app/src/main/java/com/garpr/android/extensions/ContextExt.kt | 1268391341 |
package com.gojuno.composer
import com.gojuno.commander.android.AdbDevice
import com.gojuno.composer.AdbDeviceTest.Status.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.it
import rx.observers.TestSubscriber
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.TimeUnit.SECONDS
class JUnitReportSpec : Spek({
val LF = System.getProperty("line.separator")
context("write test run result as junit4 report to file") {
val adbDevice by memoized { AdbDevice(id = "testDevice", online = true) }
val subscriber by memoized { TestSubscriber<Unit>() }
val outputFile by memoized { testFile() }
perform {
writeJunit4Report(
suite = Suite(
testPackage = "com.gojuno.test",
devices = listOf(Device(
id = adbDevice.id,
logcat = testFile(),
instrumentationOutput = testFile(),
model = adbDevice.model
)),
tests = listOf(
AdbDeviceTest(
adbDevice = adbDevice,
className = "test.class.name1",
testName = "test1",
status = Passed,
durationNanos = SECONDS.toNanos(2),
logcat = testFile(),
files = emptyList(),
screenshots = emptyList()
),
AdbDeviceTest(
adbDevice = adbDevice,
className = "test.class.name2",
testName = "test2",
status = Failed(stacktrace = "multi${LF}line${LF}stacktrace"),
durationNanos = MILLISECONDS.toNanos(3250),
logcat = testFile(),
files = emptyList(),
screenshots = emptyList()
),
AdbDeviceTest(
adbDevice = adbDevice,
className = "test.class.name3",
testName = "test3",
status = Passed,
durationNanos = SECONDS.toNanos(1),
logcat = testFile(),
files = emptyList(),
screenshots = emptyList()
),
AdbDeviceTest(
adbDevice = adbDevice,
className = "test.class.name4",
testName = "test4",
status = Ignored(""),
durationNanos = SECONDS.toNanos(0),
logcat = testFile(),
files = emptyList(),
screenshots = emptyList()
),
AdbDeviceTest(
adbDevice = adbDevice,
className = "test.class.name5",
testName = "test5",
status = Ignored("multi${LF}line${LF}stacktrace"),
durationNanos = SECONDS.toNanos(0),
logcat = testFile(),
files = emptyList(),
screenshots = emptyList()
)
),
passedCount = 2,
ignoredCount = 2,
failedCount = 1,
durationNanos = MILLISECONDS.toNanos(6250),
timestampMillis = 1490200150000
),
outputFile = outputFile
).subscribe(subscriber)
}
it("produces correct xml report") {
var expected = """
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="com.gojuno.test" tests="5" failures="1" errors="0" skipped="2" time="6.25" timestamp="2017-03-22T16:29:10" hostname="localhost">
<properties/>
<testcase classname="test.class.name1" name="test1" time="2.0"/>
<testcase classname="test.class.name2" name="test2" time="3.25">
<failure>
multi
line
stacktrace
</failure>
</testcase>
<testcase classname="test.class.name3" name="test3" time="1.0"/>
<testcase classname="test.class.name4" name="test4" time="0.0">
<skipped/>
</testcase>
<testcase classname="test.class.name5" name="test5" time="0.0">
<skipped>
multi
line
stacktrace
</skipped>
</testcase>
</testsuite>
""".trimIndent() + "\n"
expected = normalizeLinefeed(expected)
val actual = outputFile.readText()
assertThat(actual).isEqualTo(expected)
}
it("emits completion") {
subscriber.assertCompleted()
}
it("does not emit values") {
subscriber.assertNoValues()
}
it("does not emit error") {
subscriber.assertNoErrors()
}
}
})
| composer/src/test/kotlin/com/gojuno/composer/JUnitReportSpec.kt | 3386725674 |
package edu.cs4730.guidemo_kt
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
class Image_Fragment : Fragment() {
var TAG = "Image_Fragment"
lateinit var myContext: Context
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.image_fragment, container, false)
}
override fun onAttach(context: Context) {
super.onAttach(context)
myContext = context
Log.d(TAG, "onAttach")
}
} | Advanced/GuiDemo_kt/app/src/main/java/edu/cs4730/guidemo_kt/Image_Fragment.kt | 882969473 |
/*
* 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.jdbi.v3.sqlobject.kotlin
import org.jdbi.v3.meta.Beta
import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizingAnnotation
import org.jdbi.v3.sqlobject.kotlin.internal.BindKotlinFactory
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.VALUE_PARAMETER)
@SqlStatementCustomizingAnnotation(BindKotlinFactory::class)
@Beta
annotation class BindKotlin(
/**
* Prefix to apply to each property. If specified, properties will be bound as
* `prefix.propertyName`.
*
* @return the prefix
*/
val value:String = ""
)
| kotlin-sqlobject/src/main/kotlin/org/jdbi/v3/sqlobject/kotlin/BindKotlin.kt | 946920019 |
package com.vutrankien.t9vietnamese.lib
import com.vutrankien.t9vietnamese.engine.T9Engine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.system.measureTimeMillis
class Presenter(
lg: LogFactory,
private val engine: T9Engine,
private val view: View
) {
private val log = lg.newLog("Presenter")
fun start() {
view.scope.launch {
receiveUiEvents()
}
view.scope.launch {
receiveEngineEvents()
}
}
private suspend fun receiveUiEvents() {
for (eventWithData in view.eventSource) {
//log.d("receiveEvents:$eventWithData")
when (eventWithData.event) {
Event.START -> {
log.i("Start initializing")
view.showProgress(0)
val loadTime = measureTimeMillis {
engine.init()
}
log.i("Initialization Completed! loadTime=$loadTime")
view.showKeyboard()
}
Event.KEY_PRESS -> {
withContext(Dispatchers.Default) {
engine.push(eventWithData.data ?:
throw IllegalStateException("UI KEY_PRESS event with null data!"))
}
}
}
}
}
private suspend fun receiveEngineEvents() {
for (event in engine.eventSource) {
log.v("receiveEngineEvents:$event")
when(event) {
is T9Engine.Event.LoadProgress -> view.showProgress(event.bytes)
is T9Engine.Event.Confirm -> view.confirmInput(event.word)
is T9Engine.Event.NewCandidates -> view.showCandidates(event.candidates)
is T9Engine.Event.SelectCandidate -> view.highlightCandidate(event.selectedCandidate)
is T9Engine.Event.Backspace -> view.deleteBackward()
}
}
}
}
| lib/src/main/java/com/vutrankien/t9vietnamese/lib/Presenter.kt | 227973972 |
/*
* Copyright 2016 Juliane Lehmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.ui
import android.content.ContentValues
import android.database.Cursor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.lambdasoup.quickfit.alarm.AlarmService
import com.lambdasoup.quickfit.databinding.FragmentSchedulesBinding
import com.lambdasoup.quickfit.model.DayOfWeek
import com.lambdasoup.quickfit.persist.QuickFitContentProvider
import com.lambdasoup.quickfit.persist.QuickFitContract.ScheduleEntry
import com.lambdasoup.quickfit.util.ui.DividerItemDecoration
import com.lambdasoup.quickfit.util.ui.LeaveBehind
import com.lambdasoup.quickfit.util.ui.systemWindowInsetsRelative
import com.lambdasoup.quickfit.util.ui.updatePadding
import timber.log.Timber
import java.util.*
class SchedulesFragment : Fragment(),
LoaderManager.LoaderCallbacks<Cursor>, SchedulesRecyclerViewAdapter.OnScheduleInteractionListener,
TimeDialogFragment.OnFragmentInteractionListener, DayOfWeekDialogFragment.OnFragmentInteractionListener
{
internal var workoutId: Long = 0
private set
private lateinit var schedulesAdapter: SchedulesRecyclerViewAdapter
private lateinit var schedulesBinding: FragmentSchedulesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
workoutId = arguments?.let {
if (it.containsKey(ARG_WORKOUT_ID)) {
it.getLong(ARG_WORKOUT_ID)
} else {
null
}
} ?: throw IllegalArgumentException("Argument 'workoutId' is missing")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
schedulesBinding = FragmentSchedulesBinding.inflate(inflater, container, false)
return schedulesBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.setOnApplyWindowInsetsListener { v, windowInsets ->
v.setOnApplyWindowInsetsListener(null)
schedulesBinding.scheduleList.updatePadding {
oldPadding -> oldPadding + windowInsets.systemWindowInsetsRelative(v).copy(top = 0)
}
windowInsets
}
view.requestApplyInsets()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.d("activity created, initializing view binding")
schedulesAdapter = SchedulesRecyclerViewAdapter().apply {
setOnScheduleInteractionListener(this@SchedulesFragment)
}
schedulesBinding.scheduleList.adapter = schedulesAdapter
val swipeDismiss = ItemTouchHelper(object : LeaveBehind() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
onRemoveSchedule(viewHolder.itemId)
}
})
swipeDismiss.attachToRecyclerView(schedulesBinding.scheduleList)
schedulesBinding.scheduleList.addItemDecoration(DividerItemDecoration(requireContext(), true))
val bundle = Bundle(1)
bundle.putLong(ARG_WORKOUT_ID, workoutId)
loaderManager.initLoader(LOADER_SCHEDULES, bundle, this)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
Timber.d("onCreateLoader with args %s on schedules fragment %d", args, this.hashCode())
when (id) {
LOADER_SCHEDULES -> return SchedulesLoader(context, args!!.getLong(ARG_WORKOUT_ID))
}
throw IllegalArgumentException("Not a loader id: $id")
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
Timber.d("onLoadFinished, cursor is null? %s, cursor size is %d on schedules fragment %d",
data == null, data?.count ?: 0, this.hashCode())
when (loader.id) {
LOADER_SCHEDULES -> {
schedulesAdapter.swapCursor(data)
return
}
else -> throw IllegalArgumentException("Not a loader id: " + loader.id)
}
}
override fun onLoaderReset(loader: Loader<Cursor>) {
when (loader.id) {
LOADER_SCHEDULES -> {
schedulesAdapter.swapCursor(null)
return
}
else -> throw IllegalArgumentException("Not a loader id: " + loader.id)
}
}
override fun onDayOfWeekEditRequested(scheduleId: Long, oldValue: DayOfWeek) {
(activity as DialogActivity).showDialog(DayOfWeekDialogFragment.newInstance(scheduleId, oldValue))
}
override fun onListItemChanged(scheduleId: Long, newDayOfWeek: DayOfWeek) {
requireContext().contentResolver.update(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
ContentValues(1).apply {
put(ScheduleEntry.COL_DAY_OF_WEEK, newDayOfWeek.name)
},
null,
null
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
scheduleId
)
)
}
override fun onTimeEditRequested(scheduleId: Long, oldHour: Int, oldMinute: Int) {
(activity as DialogActivity).showDialog(TimeDialogFragment.newInstance(scheduleId, oldHour, oldMinute))
}
override fun onTimeChanged(scheduleId: Long, newHour: Int, newMinute: Int) {
requireContext().contentResolver.update(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
ContentValues(2).apply {
put(ScheduleEntry.COL_HOUR, newHour)
put(ScheduleEntry.COL_MINUTE, newMinute)
},
null,
null
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
scheduleId
)
)
}
internal fun onAddNewSchedule() {
// initialize with current day and time
val calendar = Calendar.getInstance()
val dayOfWeek = DayOfWeek.getByCalendarConst(calendar.get(Calendar.DAY_OF_WEEK))
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val scheduleUri = requireContext().contentResolver.insert(
QuickFitContentProvider.getUriWorkoutsIdSchedules(workoutId),
ContentValues(3).apply {
put(ScheduleEntry.COL_DAY_OF_WEEK, dayOfWeek.name)
put(ScheduleEntry.COL_HOUR, hour)
put(ScheduleEntry.COL_MINUTE, minute)
}
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
QuickFitContentProvider.getScheduleIdFromUriOrThrow(scheduleUri)
)
)
}
private fun onRemoveSchedule(scheduleId: Long) {
requireContext().contentResolver.delete(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
null,
null
)
ContextCompat.startForegroundService(requireContext(), AlarmService.getOnScheduleDeletedIntent(requireContext(), scheduleId))
}
companion object {
private const val ARG_WORKOUT_ID = "com.lambdasoup.quickfit_workoutId"
private const val LOADER_SCHEDULES = 1
fun create(workoutId: Long): SchedulesFragment {
Timber.d("Creating schedules fragment with id %d", workoutId)
val fragment = SchedulesFragment().apply {
arguments = Bundle().apply {
putLong(ARG_WORKOUT_ID, workoutId)
}
}
Timber.d("created schedules fragment: %d", fragment.hashCode())
return fragment
}
}
}
| app/src/main/java/com/lambdasoup/quickfit/ui/SchedulesFragment.kt | 3012619247 |
/*
* Copyright (C) 2022 Block, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.loader.internal.cache
import app.cash.zipline.loader.randomToken
import app.cash.zipline.loader.systemFileSystem
import app.cash.zipline.loader.testSqlDriverFactory
import app.cash.zipline.loader.testing.LoaderTestFixtures
import com.squareup.sqldelight.db.SqlDriver
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import okio.ByteString.Companion.encodeUtf8
import okio.FileSystem
class DatabaseCommonTest {
private lateinit var driver: SqlDriver
private lateinit var database: Database
private val fileSystem = systemFileSystem
private val directory = FileSystem.SYSTEM_TEMPORARY_DIRECTORY / "okio-${randomToken().hex()}"
private lateinit var testFixtures: LoaderTestFixtures
@BeforeTest
fun setUp() {
fileSystem.createDirectories(directory)
driver = testSqlDriverFactory().create(
path = directory / "zipline.db",
schema = Database.Schema,
)
database = createDatabase(driver)
testFixtures = LoaderTestFixtures()
}
@AfterTest
fun tearDown() {
driver.close()
}
@Test
fun insertCollisionThrowsSQLiteException() {
val manifestForApplicationName = "app1"
val sha256 = "hello".encodeUtf8().sha256()
// Insert a row into our empty DB.
database.filesQueries.insert(
sha256_hex = sha256.hex(),
manifest_for_application_name = manifestForApplicationName,
file_state = FileState.DIRTY,
size_bytes = 0L,
last_used_at_epoch_ms = 1,
fresh_at_epoch_ms = 1
)
// Inserting another row with the same sha256_hex should fail!
val exception = assertFailsWith<Exception> {
database.filesQueries.insert(
sha256_hex = sha256.hex(),
manifest_for_application_name = manifestForApplicationName,
file_state = FileState.DIRTY,
size_bytes = 0L,
last_used_at_epoch_ms = 1,
fresh_at_epoch_ms = 1
)
}
assertTrue(isSqlException(exception))
}
}
| zipline-loader/src/commonTest/kotlin/app/cash/zipline/loader/internal/cache/DatabaseCommonTest.kt | 1002590339 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.