repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
JetBrains/intellij-community | plugins/devkit/devkit-kotlin-tests/testData/inspections/useCoupleFix/UseCoupleOfFactoryMethodInMethodParameterWhenPairCreateUsed.kt | 1 | 315 | import com.intellij.openapi.util.Pair
class UseCoupleOfFactoryMethodInVariableWhenPairCreateUsed {
fun any() {
takePair(<warning descr="Replace with 'Couple.of()'">Pair.cr<caret>eate("a", "b")</warning>)
}
@Suppress("UNUSED_PARAMETER")
fun <A, B> takePair(pair: Pair<A, B>?) {
// do nothing
}
}
| apache-2.0 |
vhromada/Catalog | web/src/main/kotlin/com/github/vhromada/catalog/web/controller/AccessDeniedController.kt | 1 | 744 | package com.github.vhromada.catalog.web.controller
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
/**
* A class represents controller for access denied.
*
* @author Vladimir Hromada
*/
@Controller("accessDeniedController")
class AccessDeniedController {
/**
* Shows page for access denied.
*
* @param model model
* @return view for page for access denied
*/
@GetMapping("/access-denied")
fun login(model: Model): String {
model.addAttribute("errorMessage", "Access denied")
model.addAttribute("title", "Error")
model.addAttribute("inner", false)
return "errors"
}
}
| mit |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/network/site/YapLoader.kt | 1 | 14045 | package com.sedsoftware.yaptalker.data.network.site
import com.sedsoftware.yaptalker.data.parsed.ActiveTopicsPageParsed
import com.sedsoftware.yaptalker.data.parsed.BookmarksParsed
import com.sedsoftware.yaptalker.data.parsed.EditedPostParsed
import com.sedsoftware.yaptalker.data.parsed.EmojiListParsed
import com.sedsoftware.yaptalker.data.parsed.ForumPageParsed
import com.sedsoftware.yaptalker.data.parsed.ForumsListParsed
import com.sedsoftware.yaptalker.data.parsed.LoginSessionInfoParsed
import com.sedsoftware.yaptalker.data.parsed.NewsPageParsed
import com.sedsoftware.yaptalker.data.parsed.QuotedPostParsed
import com.sedsoftware.yaptalker.data.parsed.SearchTopicsPageParsed
import com.sedsoftware.yaptalker.data.parsed.SitePreferencesPageParsed
import com.sedsoftware.yaptalker.data.parsed.TopicPageParsed
import com.sedsoftware.yaptalker.data.parsed.UserProfileParsed
import io.reactivex.Observable
import io.reactivex.Single
import okhttp3.MultipartBody
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.Url
/**
* Retrofit 2 interface definition for sending and retrieving data from the site.
*/
@Suppress("ComplexInterface", "LongParameterList", "TooManyFunctions")
interface YapLoader {
/**
* Load news from the main page.
*
* @param startPage Chosen page, starts from zero.
*
* @return Parsed news page Observable.
*/
@GET
fun loadNews(@Url url: String): Observable<NewsPageParsed>
/**
* Load forums list from the site.
*
* @return Parsed forums list page Observable.
*/
@GET("/forum")
fun loadForumsList(): Observable<ForumsListParsed>
/**
* Load chosen forum page from the site.
*
* @param forumId Chosen forum id.
* @param startFrom Starting page number.
* @param sortingMode Sorting mode (rank or last_post).
*
* @return Parsed forum page Observable.
*/
@GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
fun loadForumPage(
@Path("forumId") forumId: Int,
@Path("startFrom") startFrom: Int,
@Path("sortingMode") sortingMode: String
): Observable<ForumPageParsed>
/**
* Load chosen topic page from the site.
*
* @param forumId Topic's parent forum id.
* @param topicId Chosen topic id.
* @param startPostNumber Starting page number.
*
* @return Parsed topic page Single.
*/
@GET("/forum{forumId}/st/{startFrom}/topic{topicId}.html")
fun loadTopicPage(
@Path("forumId") forumId: Int,
@Path("topicId") topicId: Int,
@Path("startFrom") startPostNumber: Int
): Single<TopicPageParsed>
/**
* Load user's profile page from the site.
*
* @param profileId Chosen user id.
*
* @return Parsed user profile page Single.
*/
@GET("/members/member{profileId}.html")
fun loadUserProfile(@Path("profileId") profileId: Int): Single<UserProfileParsed>
/**
* Load current authorization session info.
*
* @return Parsed authorization status summary Single.
*/
@GET("/forum")
fun loadAuthorizedUserInfo(): Single<LoginSessionInfoParsed>
/**
* Load active topics page.
*
* @param act Active topics action type.
* @param code Active topics action code.
* @param searchId Current searchId.
* @param startTopicNumber Starting page number.
*
* @return Parsed active topics page Single.
*/
@GET("/")
fun loadActiveTopics(
@Query("act") act: String,
@Query("CODE") code: String,
@Query("searchid") searchId: String,
@Query("st") startTopicNumber: Int
): Single<ActiveTopicsPageParsed>
/**
* Loads search result topics list.
*
* @param act Search request action type.
* @param code Search request action code.
* @param forums Forums for searching.
* @param keywords Target search keyword of phrase.
* @param prune Search period.
* @param searchHow Search type.
* @param searchIn Search targets.
* @param searchSubs Search in subforums flag.
* @param sortBy Sorting mode.
*
* @return Parsed search results page.
*/
@POST("/")
@Multipart
fun loadSearchedTopics(
@Query("act") act: String,
@Query("CODE") code: String,
@Part("forums[]") forums: List<String>,
@Part("keywords") keywords: String,
@Part("prune") prune: Int,
@Part("search_how") searchHow: String,
@Part("search_in") searchIn: String,
@Part("searchsubs") searchSubs: Int,
@Part("sort_by") sortBy: String
): Single<SearchTopicsPageParsed>
/**
* Loads tag search result topics list.
*
* @param act Search request action type.
* @param code Search request action code.
*
* @return Parsed search results page.
*/
@GET("/act/{act}/CODE/{CODE}/{tag}")
fun loadSearchedTagTopics(
@Path("act") act: String,
@Path("CODE") code: String,
@Path("tag") tag: String
): Single<SearchTopicsPageParsed>
/**
* Loads next page of search result topics list.
*
* @param act Search request action type.
* @param code Search request action code.
* @param hl Highlighted word.
* @param nav Unknown (empty).
* @param resultType Results type (empty for now).
* @param searchIn Search targets.
* @param searchId Constant search id.
* @param st Results page, should be multiple of 25.
*
* @return Parsed search results page.
*/
@GET("/")
fun loadSearchedTopicsNextPage(
@Query("act") act: String,
@Query("CODE") code: String,
@Query("hl") hl: String,
@Query("nav") nav: String,
@Query("result_type") resultType: String,
@Query("search_in") searchIn: String,
@Query("searchid") searchId: String,
@Query("st") st: Int
): Single<SearchTopicsPageParsed>
/**
* Load active emojis list page.
*
* @param act Emoji list action type.
* @param code Emoji list action code.
*
* @return Parsed emojis page Single.
*/
@GET("/")
fun loadEmojiList(
@Query("act") act: String,
@Query("CODE") code: String
): Single<EmojiListParsed>
/**
* Load bookmarks block.
*
* @param act Load bookmarks action type.
* @param code Load bookmarks action code.
*
* @return Parsed bookmarks block Observable.
*/
@Headers("X-Requested-With:XMLHttpRequest")
@GET("/")
fun loadBookmarks(
@Query("act") act: String,
@Query("CODE") code: String
): Observable<BookmarksParsed>
/**
* Load site preferences page.
*
* @param act Load user data action type.
* @param code Code for loading user CP forum settings page.
*
* @return Parsed forum settings page Single.
*/
@GET("/")
fun loadSitePreferences(
@Query("act") act: String,
@Query("CODE") code: String
): Single<SitePreferencesPageParsed>
/**
* Load targeted post text prepared for quoting.
*
* @param forumId Current topic's parent forum id.
* @param topicId Current topic id.
* @param targetPostId Quoted post id.
*
* @return Parsed quoted text Single.
*/
@GET("/act/Post/CODE/06/forum{forumId}/topic{topicId}/post/{targetPostId}/st/0/")
fun loadTargetPostQuotedText(
@Path("forumId") forumId: Int,
@Path("topicId") topicId: Int,
@Path("targetPostId") targetPostId: Int
): Single<QuotedPostParsed>
/**
* Load target post prepared for editing.
*
* @param forumId Current topic's parent forum id.
* @param topicId Current topic id.
* @param targetPostId Quoted post id.
* @param startingPost Current topic page.
*
* @return Parsed quoted text Single.
*/
@GET("/act/Post/CODE/08/forum{forumId}/topic{topicId}/post/{targetPostId}/st/{startingPost}/")
fun loadTargetPostEditedText(
@Path("forumId") forumId: Int,
@Path("topicId") topicId: Int,
@Path("targetPostId") targetPostId: Int,
@Path("startingPost") startingPost: Int
): Single<EditedPostParsed>
/**
* Send message posting request to the site.
*
* @param act Message posting action type.
* @param code Message posting action code.
* @param forum Topic's parent forum id.
* @param topic Chosen topic id.
* @param st Starting page.
* @param enableemo Enable emoji.
* @param enablesig Enable signature.
* @param authKey Authorization key.
* @param postContent Message content.
* @param maxFileSize File size limit.
* @param enabletag Enable site sign for image.
*
* @return Parsed topic page Single.
*/
@Suppress("LongParameterList")
@Multipart
@POST("/")
fun postMessage(
@Part("act") act: String,
@Part("CODE") code: String,
@Part("f") forum: Int,
@Part("t") topic: Int,
@Part("st") st: Int,
@Part("enableemo") enableemo: String,
@Part("enablesig") enablesig: String,
@Part("auth_key") authKey: String,
@Part("Post") postContent: String,
@Part("enabletag") enabletag: Int,
@Part("MAX_FILE_SIZE") maxFileSize: Int,
@Part uploadedFile: MultipartBody.Part?
): Single<Response<ResponseBody>>
/**
* Send edited message posting request to the site.
*
* @param act Message posting action type.
* @param code Message posting action code.
* @param forum Topic's parent forum id.
* @param topic Current topic id.
* @param st Starting page.
* @param s Unknown for now (empty).
* @param enableemo Enable emoji.
* @param enablesig Enable signature.
* @param authKey Authorization key.
* @param postContent Message content.
* @param maxFileSize File size limit.
* @param fileupload File upload marker.
* @param enabletag Enable site sign for image.
* @param post Edited post id.
*
* @return Parsed topic page Single.
*/
@Suppress("LongParameterList")
@Multipart
@POST("/")
fun postEditedMessage(
@Part("act") act: String,
@Part("CODE") code: String,
@Part("f") forum: Int,
@Part("t") topic: Int,
@Part("st") st: Int,
@Part("s") s: String,
@Part("enableemo") enableemo: String,
@Part("enablesig") enablesig: String,
@Part("auth_key") authKey: String,
@Part("Post") postContent: String,
@Part("MAX_FILE_SIZE") maxFileSize: Int,
@Part("FILE_UPLOAD") fileupload: String,
@Part("enabletag") enabletag: Int,
@Part("p") post: Int
): Single<Response<ResponseBody>>
/**
* Send sign in request to the site.
*
* @param cookieDate Cookie behaviour type (set to 1).
* @param privacy Anonymous sign in (1 or 0).
* @param password User password.
* @param userName User login.
* @param referer Referer link.
* @param submit Submit action type.
* @param userKey Generated md5 user hash key.
*
* @return Raw site response Single.
*/
@FormUrlEncoded
@POST("/act/Login/CODE/01/")
fun signIn(
@Field("CookieDate") cookieDate: Int,
@Field("Privacy") privacy: Boolean,
@Field("PassWord") password: String,
@Field("UserName") userName: String,
@Field("referer") referer: String,
@Field("submit") submit: String,
@Field("user_key") userKey: String
): Single<Response<ResponseBody>>
/**
* Send sign out request to the site.
*
* @param key Current user hash key.
*
* @return Raw site response Single.
*/
@GET("/act/Login/CODE/03/")
fun signOut(@Query("key") key: String): Single<Response<ResponseBody>>
/**
* Send adding to bookmarks request.
*
* @param act Add to bookmarks action type.
* @param code Add to bookmarks action code.
* @param item Chosen topic id.
* @param startPostNumber Starting page number.
* @param type Request type (set to 1).
*
*/
@Headers("X-Requested-With:XMLHttpRequest")
@GET("/")
fun addToBookmarks(
@Query("act") act: String,
@Query("CODE") code: String,
@Query("item") item: Int,
@Query("st") startPostNumber: Int,
@Query("type") type: Int
): Observable<Response<ResponseBody>>
/**
* Send remove to bookmarks request.
*
* @param act Add to bookmarks action type.
* @param code Add to bookmarks action code.
* @param id Bookmark id.
*
* @return Raw site response Single.
*/
@Headers("X-Requested-With:XMLHttpRequest")
@GET("/")
fun removeFromBookmarks(
@Query("act") act: String,
@Query("CODE") code: String,
@Query("id") id: Int
): Single<Response<ResponseBody>>
/**
* Send karma change request.
*
* @param act Add to bookmarks action type.
* @param code Add to bookmarks action code.
* @param rank Karma diff (1 or -1).
* @param postId Target post id.
* @param topicId Target topic id.
* @param type Karma type (1 for topic and 0 for post).
*
* @return Raw site response Single.
*/
@Headers("X-Requested-With:XMLHttpRequest")
@GET("/")
fun changeKarma(
@Query("act") act: String,
@Query("CODE") code: String,
@Query("rank") rank: Int,
@Query("p") postId: Int,
@Query("t") topicId: Int,
@Query("n") type: Int
): Single<Response<ResponseBody>>
}
| apache-2.0 |
oldcwj/iPing | app/src/main/java/com/wpapper/iping/base/ui/BaseStatefulActivity.kt | 1 | 1222 | package com.wpapper.iping.base.ui
import android.support.annotation.CallSuper
import com.wpapper.iping.R
import org.jetbrains.anko.find
abstract class BaseStatefulActivity : BaseActivity() {
val statefulLayout by lazy { find<com.gturedi.views.StatefulLayout>(R.id.stateful_layout) }
private val statefulViewContainer by lazy { find<android.widget.FrameLayout>(R.id.stateful_view_container) }
@CallSuper
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
super.setContentView(R.layout.activity_stateful_base)
}
override fun setContentView(layoutResID: Int) {
statefulViewContainer.apply {
removeAllViews();
addView(layoutInflater.inflate(layoutResID, statefulViewContainer, false))
}
}
override fun setContentView(view: android.view.View?) {
statefulViewContainer.apply {
removeAllViews();
addView(view)
}
}
override fun setContentView(view: android.view.View?, params: android.view.ViewGroup.LayoutParams?) {
statefulViewContainer.apply {
removeAllViews();
addView(view, params)
}
}
} | gpl-3.0 |
androidx/androidx | wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/ScalingLazyListLayoutInfoTest.kt | 3 | 46833 | /*
* 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.material
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.math.roundToInt
import org.junit.Ignore
@MediumTest
@RunWith(AndroidJUnit4::class)
public class ScalingLazyListLayoutInfoTest {
@get:Rule
val rule = createComposeRule()
private var itemSizePx: Int = 50
private var itemSizeDp: Dp = Dp.Infinity
private var defaultItemSpacingDp: Dp = 4.dp
private var defaultItemSpacingPx = Int.MAX_VALUE
@Before
fun before() {
with(rule.density) {
itemSizeDp = itemSizePx.toDp()
defaultItemSpacingPx = defaultItemSpacingDp.roundToPx()
}
}
@Ignore("Awaiting fix for b/236217874")
@Test
fun visibleItemsAreCorrect() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = AutoCenteringParams()
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(1)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
state.layoutInfo.assertVisibleItems(count = 4)
}
}
@Test
fun centerItemIndexIsCorrectAfterScrolling() {
lateinit var state: ScalingLazyListState
var itemSpacingPx: Int = -1
val itemSpacingDp = 20.dp
var scope: CoroutineScope? = null
rule.setContent {
scope = rememberCoroutineScope()
itemSpacingPx = with(LocalDensity.current) { itemSpacingDp.roundToPx() }
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + itemSpacingDp * 2.5f
),
verticalArrangement = Arrangement.spacedBy(itemSpacingDp),
autoCentering = AutoCenteringParams()
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(1)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
state.layoutInfo.assertVisibleItems(count = 3, spacing = itemSpacingPx)
}
// Scroll so that the center item is just above the center line and check that it is still
// the correct center item
val scrollDistance = (itemSizePx / 2) + 1
scope!!.launch {
state.animateScrollBy(scrollDistance.toFloat())
}
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(1)
assertThat(state.centerItemScrollOffset).isEqualTo(scrollDistance)
}
}
@Test
fun orientationIsCorrect() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = AutoCenteringParams(),
contentPadding = PaddingValues(all = 0.dp)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.orientation).isEqualTo(Orientation.Vertical)
}
}
@Test
fun reverseLayoutIsCorrectWhenNotReversed() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = AutoCenteringParams(),
contentPadding = PaddingValues(all = 0.dp)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.reverseLayout).isEqualTo(false)
}
}
@Test
fun reverseLayoutIsCorrectWhenReversed() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = AutoCenteringParams(),
contentPadding = PaddingValues(all = 0.dp),
reverseLayout = true
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.reverseLayout).isEqualTo(true)
}
}
@Test
fun visibleItemsAreCorrectSetExplicitInitialItemIndex() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(initialCenterItemIndex = 0)
.also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(0)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
state.layoutInfo.assertVisibleItems(count = 3)
}
}
@Test
fun visibleItemsAreCorrectNoAutoCentering() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 4)
}
}
@Test
fun visibleItemsAreCorrectForReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
reverseLayout = true,
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(1)
state.layoutInfo.assertVisibleItems(count = 4)
}
}
@Test
fun visibleItemsAreCorrectForReverseLayoutWithAutoCentering() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(initialCenterItemIndex = 0)
.also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
reverseLayout = true,
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(0)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
state.layoutInfo.assertVisibleItems(count = 3)
}
}
@Test
fun visibleItemsAreCorrectAfterScrolling() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
runBlocking {
state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1)
}
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemZeroOddHeightViewportOddHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 41, false)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemZeroOddHeightViewportEvenHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 40, false)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemZeroEvenHeightViewportOddHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 41, true)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemZeroEvenHeightViewportEvenHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 40, true)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemOneOddHeightViewportOddHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 41, false)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemOneOddHeightViewportEvenHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 40, false)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemOneEvenHeightViewportOddHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 41, true)
}
@Test
fun itemsCorrectScrollPastStartEndAutoCenterItemOneEvenHeightViewportEvenHeightItems() {
visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 40, true)
}
private fun visibleItemsAreCorrectAfterScrollingPastEndOfItems(
autoCenterItem: Int,
localItemSizePx: Int,
viewPortSizeEven: Boolean
) {
lateinit var state: ScalingLazyListState
lateinit var scope: CoroutineScope
rule.setContent {
with(LocalDensity.current) {
val viewportSizePx =
(((localItemSizePx * 4 + defaultItemSpacingPx * 3) / 2) * 2) +
if (viewPortSizeEven) 0 else 1
scope = rememberCoroutineScope()
ScalingLazyColumn(
state = rememberScalingLazyListState(
initialCenterItemIndex = autoCenterItem
).also { state = it },
modifier = Modifier.requiredSize(
viewportSizePx.toDp()
),
autoCentering = AutoCenteringParams(itemIndex = autoCenterItem)
) {
items(5) {
Box(Modifier.requiredSize(localItemSizePx.toDp()))
}
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
scope.launch {
state.animateScrollBy(localItemSizePx.toFloat() * 10)
}
rule.waitUntil { !state.isScrollInProgress }
assertThat(state.centerItemIndex).isEqualTo(4)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
scope.launch {
state.animateScrollBy(- localItemSizePx.toFloat() * 10)
}
rule.waitUntil { !state.isScrollInProgress }
assertThat(state.centerItemIndex).isEqualTo(autoCenterItem)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
}
@Test
fun largeItemLargerThanViewPortDoesNotGetScaled() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp
),
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp * 5))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
runBlocking {
state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
val firstItem = state.layoutInfo.visibleItemsInfo.first()
assertThat(firstItem.offset).isLessThan(0)
assertThat(firstItem.offset + firstItem.size).isGreaterThan(itemSizePx)
assertThat(state.layoutInfo.visibleItemsInfo.first().scale).isEqualTo(1.0f)
}
}
@Test
fun itemInsideScalingLinesDoesNotGetScaled() {
lateinit var state: ScalingLazyListState
val centerItemIndex = 2
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(centerItemIndex).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3
),
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
// Get the middle item on the screen
val centerScreenItem =
state.layoutInfo.visibleItemsInfo.find { it.index == centerItemIndex }
// and confirm its offset is 0
assertThat(centerScreenItem!!.offset).isEqualTo(0)
// And that it is not scaled
assertThat(centerScreenItem.scale).isEqualTo(1.0f)
}
}
@Test
fun itemOutsideScalingLinesDoesGetScaled() {
lateinit var state: ScalingLazyListState
val centerItemIndex = 2
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(centerItemIndex).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 4 + defaultItemSpacingDp * 3
),
) {
items(6) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
// Get the middle item on the screen
val edgeScreenItem =
state.layoutInfo.visibleItemsInfo.find { it.index == 0 }
// And that it is it scaled
assertThat(edgeScreenItem!!.scale).isLessThan(1.0f)
}
}
@Test
fun visibleItemsAreCorrectAfterScrollingReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
reverseLayout = true,
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
runBlocking {
state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1)
}
}
@Test
fun visibleItemsAreCorrectCenterPivotNoOffset() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(2).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 2f + defaultItemSpacingDp * 1f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1)
assertThat(state.centerItemIndex).isEqualTo(2)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
}
}
@Test
fun visibleItemsAreCorrectCenterPivotWithOffset() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(2, -5).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 2f + defaultItemSpacingDp * 1f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1)
assertThat(state.centerItemIndex).isEqualTo(2)
assertThat(state.centerItemScrollOffset).isEqualTo(-5)
}
}
@Test
fun visibleItemsAreCorrectCenterPivotNoOffsetReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(2).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 2f + defaultItemSpacingDp * 1f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
reverseLayout = true
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1)
assertThat(state.centerItemIndex).isEqualTo(2)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
}
}
@Test
fun visibleItemsAreCorrectCenterPivotWithOffsetReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(2, -5).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 2f + defaultItemSpacingDp * 1f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
reverseLayout = true
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1)
assertThat(state.centerItemIndex).isEqualTo(2)
assertThat(state.centerItemScrollOffset).isEqualTo(-5)
}
}
@Test
fun visibleItemsAreCorrectNoScalingForReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(8).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 4f + defaultItemSpacingDp * 3f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
reverseLayout = true
) {
items(15) {
Box(Modifier.requiredSize(itemSizeDp).testTag("Item:$it"))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.waitForIdle()
// Assert that items are being shown at the end of the parent as this is reverseLayout
rule.onNodeWithTag(testTag = "Item:8").assertIsDisplayed()
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6)
}
}
@Test
fun visibleItemsAreCorrectAfterScrollNoScaling() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(initialCenterItemIndex = 0)
.also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
items(5) {
Box(
Modifier
.requiredSize(itemSizeDp)
.testTag("Item:$it"))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.waitForIdle()
rule.onNodeWithTag(testTag = "Item:0").assertIsDisplayed()
val scrollAmount = (itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()).roundToInt()
rule.runOnIdle {
assertThat(state.centerItemIndex).isEqualTo(0)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
runBlocking {
state.scrollBy(scrollAmount.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 4)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(-scrollAmount)
}
rule.runOnIdle {
runBlocking {
state.scrollBy(-scrollAmount.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 3)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(0)
}
}
@Test
fun visibleItemsAreCorrectAfterScrollNoScalingForReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(8).also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 4f + defaultItemSpacingDp * 3f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
reverseLayout = true
) {
items(15) {
Box(Modifier.requiredSize(itemSizeDp).testTag("Item:$it"))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.waitForIdle()
rule.onNodeWithTag(testTag = "Item:8").assertIsDisplayed()
val scrollAmount = (itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()).roundToInt()
rule.runOnIdle {
state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6)
assertThat(state.centerItemIndex).isEqualTo(8)
assertThat(state.centerItemScrollOffset).isEqualTo(0)
runBlocking {
state.scrollBy(scrollAmount.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 5, startIndex = 7)
}
rule.runOnIdle {
runBlocking {
state.scrollBy(-scrollAmount.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6)
}
}
@Test
fun visibleItemsAreCorrectAfterDispatchRawDeltaScrollNoScaling() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState(initialCenterItemIndex = 0)
.also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
autoCentering = AutoCenteringParams(itemIndex = 0)
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
val scrollAmount = itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()
rule.runOnIdle {
runBlocking {
state.dispatchRawDelta(scrollAmount)
}
state.layoutInfo.assertVisibleItems(count = 4, startIndex = 0)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset)
.isEqualTo(-scrollAmount.roundToInt())
}
rule.runOnIdle {
runBlocking {
state.dispatchRawDelta(-scrollAmount)
}
state.layoutInfo.assertVisibleItems(count = 3, startIndex = 0)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(0)
}
}
@Test
fun visibleItemsAreCorrectAfterDispatchRawDeltaScrollNoScalingForReverseLayout() {
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(
itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f
),
scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f),
reverseLayout = true,
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
val firstItemOffset = state.layoutInfo.visibleItemsInfo.first().offset
rule.runOnIdle {
runBlocking {
state.dispatchRawDelta(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(firstItemOffset)
}
rule.runOnIdle {
runBlocking {
state.dispatchRawDelta(-(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()))
}
state.layoutInfo.assertVisibleItems(count = 4, startIndex = 0)
assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(firstItemOffset)
}
}
@Test
fun visibleItemsAreCorrectWithCustomSpacing() {
lateinit var state: ScalingLazyListState
val spacing: Dp = 10.dp
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + spacing * 2.5f),
verticalArrangement = Arrangement.spacedBy(spacing),
autoCentering = null
) {
items(5) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
val spacingPx = with(rule.density) {
spacing.roundToPx()
}
state.layoutInfo.assertVisibleItems(
count = 4,
spacing = spacingPx
)
}
}
@Composable
fun ObservingFun(
state: ScalingLazyListState,
currentInfo: StableRef<ScalingLazyListLayoutInfo?>
) {
currentInfo.value = state.layoutInfo
}
@Test
fun visibleItemsAreObservableWhenWeScroll() {
lateinit var state: ScalingLazyListState
val currentInfo = StableRef<ScalingLazyListLayoutInfo?>(null)
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f),
autoCentering = null
) {
items(6) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
ObservingFun(state, currentInfo)
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
// empty it here and scrolling should invoke observingFun again
currentInfo.value = null
runBlocking {
state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
}
rule.runOnIdle {
assertThat(currentInfo.value).isNotNull()
currentInfo.value!!.assertVisibleItems(count = 4, startIndex = 1)
}
}
@Test
fun visibleItemsAreObservableWhenWeDispatchRawDeltaScroll() {
lateinit var state: ScalingLazyListState
val currentInfo = StableRef<ScalingLazyListLayoutInfo?>(null)
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f),
autoCentering = null
) {
items(6) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
ObservingFun(state, currentInfo)
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
// empty it here and scrolling should invoke observingFun again
currentInfo.value = null
runBlocking {
state.dispatchRawDelta(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
}
rule.runOnIdle {
assertThat(currentInfo.value).isNotNull()
currentInfo.value!!.assertVisibleItems(count = 4, startIndex = 1)
}
}
@Composable
fun ObservingIsScrollInProgressTrueFun(
state: ScalingLazyListState,
currentInfo: StableRef<Boolean?>
) {
// If isScrollInProgress is ever true record it - otherwise leave the value as null
if (state.isScrollInProgress) {
currentInfo.value = true
}
}
@Test
fun isScrollInProgressIsObservableWhenWeScroll() {
lateinit var state: ScalingLazyListState
lateinit var scope: CoroutineScope
val currentInfo = StableRef<Boolean?>(null)
rule.setContent {
scope = rememberCoroutineScope()
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f)
) {
items(6) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
ObservingIsScrollInProgressTrueFun(state, currentInfo)
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
scope.launch {
// empty it here and scrolling should invoke observingFun again
currentInfo.value = null
state.animateScrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
rule.runOnIdle {
assertThat(currentInfo.value).isNotNull()
assertThat(currentInfo.value).isTrue()
}
}
@Composable
fun ObservingCentralItemIndexFun(
state: ScalingLazyListState,
currentInfo: StableRef<Int?>
) {
currentInfo.value = state.centerItemIndex
}
@Test
fun isCentralListItemIndexObservableWhenWeScroll() {
lateinit var state: ScalingLazyListState
lateinit var scope: CoroutineScope
val currentInfo = StableRef<Int?>(null)
rule.setContent {
scope = rememberCoroutineScope()
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it },
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f),
autoCentering = null
) {
items(6) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
ObservingCentralItemIndexFun(state, currentInfo)
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
scope.launch {
// empty it here and scrolling should invoke observingFun again
currentInfo.value = null
state.animateScrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())
}
rule.runOnIdle {
assertThat(currentInfo.value).isNotNull()
assertThat(currentInfo.value).isEqualTo(2)
}
}
@Test
fun visibleItemsAreObservableWhenResize() {
lateinit var state: ScalingLazyListState
var size by mutableStateOf(itemSizeDp * 2)
var currentInfo: ScalingLazyListLayoutInfo? = null
@Composable
fun observingFun() {
currentInfo = state.layoutInfo
}
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it }
) {
item {
Box(Modifier.requiredSize(size))
}
}
observingFun()
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(currentInfo).isNotNull()
currentInfo!!.assertVisibleItems(count = 1, unscaledSize = itemSizePx * 2)
currentInfo = null
size = itemSizeDp
}
rule.runOnIdle {
assertThat(currentInfo).isNotNull()
currentInfo!!.assertVisibleItems(count = 1, unscaledSize = itemSizePx)
}
}
@Test
fun viewportOffsetsAndSizeAreCorrect() {
val sizePx = 45
val sizeDp = with(rule.density) { sizePx.toDp() }
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
Modifier.requiredSize(sizeDp),
state = rememberScalingLazyListState().also { state = it }
) {
items(4) {
Box(Modifier.requiredSize(sizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(0)
assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx)
assertThat(state.layoutInfo.viewportSize).isEqualTo(IntSize(sizePx, sizePx))
assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterContentPadding).isEqualTo(0)
assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0)
}
}
@Test
fun viewportOffsetsAndSizeAreCorrectWithContentPadding() {
val sizePx = 45
val startPaddingPx = 10
val endPaddingPx = 15
val sizeDp = with(rule.density) { sizePx.toDp() }
val topPaddingDp = with(rule.density) { startPaddingPx.toDp() }
val bottomPaddingDp = with(rule.density) { endPaddingPx.toDp() }
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
Modifier.requiredSize(sizeDp),
contentPadding = PaddingValues(top = topPaddingDp, bottom = bottomPaddingDp),
state = rememberScalingLazyListState().also { state = it }
) {
items(4) {
Box(Modifier.requiredSize(sizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(-startPaddingPx)
assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx - startPaddingPx)
assertThat(state.layoutInfo.viewportSize).isEqualTo(IntSize(sizePx, sizePx))
assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(10)
assertThat(state.layoutInfo.afterContentPadding).isEqualTo(15)
assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0)
}
}
@Test
fun viewportOffsetsAreCorrectWithAutoCentering() {
val itemSizePx = 45
val itemSizeDp = with(rule.density) { itemSizePx.toDp() }
val viewPortSizePx = itemSizePx * 4
val viewPortSizeDp = with(rule.density) { viewPortSizePx.toDp() }
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
Modifier.requiredSize(viewPortSizeDp),
state = rememberScalingLazyListState(
initialCenterItemIndex = 0
).also { state = it },
autoCentering = AutoCenteringParams()
) {
items(7) {
Box(Modifier.requiredSize(itemSizeDp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(0)
assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(viewPortSizePx)
assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterContentPadding).isEqualTo(0)
assertThat(state.layoutInfo.beforeAutoCenteringPadding).isGreaterThan(0)
assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0)
runBlocking {
state.scrollToItem(3)
}
assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0)
runBlocking {
state.scrollToItem(5)
}
assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0)
assertThat(state.layoutInfo.afterAutoCenteringPadding).isGreaterThan(0)
}
}
@Test
fun totalCountIsCorrect() {
var count by mutableStateOf(10)
lateinit var state: ScalingLazyListState
rule.setContent {
ScalingLazyColumn(
state = rememberScalingLazyListState().also { state = it }
) {
items(count) {
Box(Modifier.requiredSize(10.dp))
}
}
}
// TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization
rule.waitUntil { state.initialized.value }
rule.runOnIdle {
assertThat(state.layoutInfo.totalItemsCount).isEqualTo(10)
count = 20
}
rule.runOnIdle {
assertThat(state.layoutInfo.totalItemsCount).isEqualTo(20)
}
}
private fun ScalingLazyListLayoutInfo.assertVisibleItems(
count: Int,
startIndex: Int = 0,
unscaledSize: Int = itemSizePx,
spacing: Int = defaultItemSpacingPx,
anchorType: ScalingLazyListAnchorType = ScalingLazyListAnchorType.ItemCenter
) {
assertThat(visibleItemsInfo.size).isEqualTo(count)
var currentIndex = startIndex
var previousEndOffset = -1
visibleItemsInfo.forEach {
assertThat(it.index).isEqualTo(currentIndex)
assertThat(it.size).isEqualTo((unscaledSize * it.scale).roundToInt())
currentIndex++
val startOffset = it.startOffset(anchorType).roundToInt()
if (previousEndOffset != -1) {
assertThat(spacing).isEqualTo(startOffset - previousEndOffset)
}
previousEndOffset = startOffset + it.size
}
}
}
@Stable
public class StableRef<T>(var value: T) | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/properties/PropertyReference.kt | 4 | 1071 | // 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.tools.projectWizard.core.entity.properties
import org.jetbrains.kotlin.tools.projectWizard.core.entity.EntityReference
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
sealed class PropertyReference<out T : Any> : EntityReference() {
abstract val property: Property<T>
}
class PluginPropertyReference<out T: Any>(override val property: PluginProperty<T>): PropertyReference<T>() {
override val path: String
get() = property.path
}
class ModuleConfiguratorPropertyReference<out T : Any>(
val configurator: ModuleConfigurator,
val module: Module,
override val property: ModuleConfiguratorProperty<T>
) : PropertyReference<T>() {
override val path: String
get() = "${configurator.id}/${module.identificator}/${property.path}"
} | apache-2.0 |
GunoH/intellij-community | jps/jps-builders/testSrc/org/jetbrains/jps/builders/ParallelBuildTest.kt | 7 | 1089 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.jps.builders
import com.intellij.util.PathUtil
import org.jetbrains.jps.api.GlobalOptions
class ParallelBuildTest: JpsBuildTestCase() {
override fun setUp() {
super.setUp()
System.setProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, true.toString())
}
override fun tearDown() {
try {
System.setProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, false.toString())
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
fun testBuildDependentModules() {
createFile("m1/Class0.java", "public class Class0 {}")
for (i in 1..10) {
val file = createFile("m$i/Class$i.java", "public class Class$i { Class${i-1} prev; }")
val module = addModule("m$i", PathUtil.getParentPath(file))
if (i > 1) {
module.dependenciesList.addModuleDependency(myProject.modules.first { it.name == "m${i-1}" })
}
}
rebuildAllModules()
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/when/addElseBranchSealed.kt | 8 | 194 | // "Add else branch" "true"
sealed class Base {
class A : Base()
class B : Base()
class C : Base()
}
fun test(base: Base) {
when<caret> (base) {
is Base.A -> ""
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/psiUtils.kt | 2 | 1962 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.util
import com.intellij.psi.*
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun ValueArgument.findSingleLiteralStringTemplateText(): String? {
return getArgumentExpression()
?.safeAs<KtStringTemplateExpression>()
?.entries
?.singleOrNull()
?.safeAs<KtLiteralStringTemplateEntry>()
?.text
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("The function is ad-hoc, has arbitrary naming and does not support extension receivers")
fun KtCallableDeclaration.numberOfArguments(countReceiver: Boolean = false): Int =
valueParameters.size + (1.takeIf { countReceiver && receiverTypeReference != null } ?: 0)
fun KtExpression.resultingWhens(): List<KtWhenExpression> = when (this) {
is KtWhenExpression -> listOf(this) + entries.map { it.expression?.resultingWhens() ?: listOf() }.flatten()
is KtIfExpression -> (then?.resultingWhens() ?: listOf()) + (`else`?.resultingWhens() ?: listOf())
is KtBinaryExpression -> (left?.resultingWhens() ?: listOf()) + (right?.resultingWhens() ?: listOf())
is KtUnaryExpression -> this.baseExpression?.resultingWhens() ?: listOf()
is KtBlockExpression -> statements.lastOrNull()?.resultingWhens() ?: listOf()
else -> listOf()
}
fun PsiClass.isSyntheticKotlinClass(): Boolean {
if ('$' !in name!!) return false // optimization to not analyze annotations of all classes
val metadata = modifierList?.findAnnotation(JvmAnnotationNames.METADATA_FQ_NAME.asString())
return (metadata?.findAttributeValue(JvmAnnotationNames.KIND_FIELD_NAME) as? PsiLiteral)?.value ==
KotlinClassHeader.Kind.SYNTHETIC_CLASS.id
} | apache-2.0 |
googlecodelabs/android-dagger-to-hilt | app/src/main/java/com/example/android/dagger/settings/SettingsViewModel.kt | 1 | 1202 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.dagger.settings
import com.example.android.dagger.user.UserDataRepository
import com.example.android.dagger.user.UserManager
import javax.inject.Inject
/**
* SettingsViewModel is the ViewModel that [SettingsActivity] uses to handle complex logic.
*/
class SettingsViewModel @Inject constructor(
private val userDataRepository: UserDataRepository,
private val userManager: UserManager
) {
fun refreshNotifications() {
userDataRepository.refreshUnreadNotifications()
}
fun logout() {
userManager.logout()
}
}
| apache-2.0 |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/rtmp/RtmpHandshake.kt | 1 | 1286 | package com.haishinkit.rtmp
import java.nio.ByteBuffer
import java.util.Random
internal class RtmpHandshake {
var c0C1Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE + 1)
get() {
if (field.position() == 0) {
val random = Random()
field.put(0x03)
field.position(1 + 8)
for (i in 0..SIGNAL_SIZE - 9) {
field.put(random.nextInt().toByte())
}
}
return field
}
var c2Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE)
var s0S1Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE + 1)
set(value) {
field = ByteBuffer.wrap(value.array(), 0, SIGNAL_SIZE + 1)
c2Packet.clear()
c2Packet.put(value.array(), 1, 4)
c2Packet.position(8)
c2Packet.put(value.array(), 9, SIGNAL_SIZE - 8)
}
var s2Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE)
set(value) {
field = ByteBuffer.wrap(value.array(), 0, SIGNAL_SIZE)
}
fun clear() {
c0C1Packet.clear()
s0S1Packet.clear()
c2Packet.clear()
s2Packet.clear()
}
companion object {
const val SIGNAL_SIZE = 1536
}
}
| bsd-3-clause |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/scraper/ScraperRepository.kt | 1 | 421 | package io.github.feelfreelinux.wykopmobilny.api.scraper
import io.github.feelfreelinux.wykopmobilny.models.scraper.Blacklist
import io.reactivex.Single
import retrofit2.Retrofit
class ScraperRepository(val retrofit: Retrofit) : ScraperApi {
private val scraperApi by lazy { retrofit.create(ScraperRetrofitApi::class.java) }
override fun getBlacklist(): Single<Blacklist> =
scraperApi.getBlacklist()
} | mit |
siosio/intellij-community | plugins/kotlin/fir/test/org/jetbrains/kotlin/asJava/classes/AbstractFirClassLoadingTest.kt | 2 | 1711 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.asJava.classes
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.executeOnPooledThreadInReadAction
import org.jetbrains.kotlin.findUsages.doTestWithFIRFlagsByPath
import org.jetbrains.kotlin.idea.perf.UltraLightChecker
import org.jetbrains.kotlin.idea.perf.UltraLightChecker.getJavaFileForTest
import org.jetbrains.kotlin.idea.perf.UltraLightChecker.renderLightClasses
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractFirClassLoadingTest : AbstractUltraLightClassLoadingTest() {
override fun isFirPlugin(): Boolean = true
override fun doTest(testDataPath: String) = doTestWithFIRFlagsByPath(testDataPath) {
doTestImpl(testDataPath)
}
private fun doTestImpl(testDataPath: String) {
val testDataFile = File(testDataPath)
val sourceText = testDataFile.readText()
val file = myFixture.addFileToProject(testDataPath, sourceText) as KtFile
val classFabric = KotlinAsJavaSupport.getInstance(project)
val expectedTextFile = getJavaFileForTest(testDataPath)
val renderedClasses = executeOnPooledThreadInReadAction {
val lightClasses = UltraLightChecker.allClasses(file).mapNotNull { classFabric.getLightClass(it) }
renderLightClasses(testDataPath, lightClasses)
}!!
KotlinTestUtils.assertEqualsToFile(expectedTextFile, renderedClasses)
}
}
| apache-2.0 |
Shurup228/brainfuck_kotlin | tests/ParserTest.kt | 1 | 1291 | import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import java.util.LinkedList
internal class ParserTest {
val parser = Parser("kek")
@Test
fun parse() {
val code = "< > + - [ ] , ."
val tokens = parser.parse(code)
val expectedTokens = arrayOf(
Move(-1), Move(1), ChangeValue(1),
ChangeValue(-1), OpenLoop(),
CloseLoop(), Write, Print
).toCollection(LinkedList())
assertEquals(tokens, expectedTokens)
}
@Test
fun optimize() {
val code = "++---.>>>"
val tokens = parser.optimize(parser.parse(code))
val expectedTokens = arrayOf(
ChangeValue(-1), Print, Move(3)
).toCollection(LinkedList())
assertEquals(expectedTokens, tokens)
}
@Test
fun loopParse() {
val code = "+[--[-]++]"
val tokens = parser.loopParse(parser.optimize(parser.parse(code)))
val expectedTokens = arrayOf(
ChangeValue(1), OpenLoop(1, 7),
ChangeValue(-2), OpenLoop(3, 5),
ChangeValue(-1), CloseLoop(5, 3),
ChangeValue(2), CloseLoop(7, 1)
).toCollection(LinkedList())
assertEquals(expectedTokens, tokens)
}
} | mit |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/vararg/addedSpreadArgumentAfterRuntime.kt | 4 | 311 | // "Replace with 'newFun(*p, *list.toIntArray())'" "true"
// WITH_RUNTIME
@Deprecated("", ReplaceWith("newFun(*p, *list.toIntArray())"))
fun oldFun(list: List<Int>, vararg p: Int){
newFun(*p, *list.toIntArray())
}
fun newFun(vararg p: Int){}
fun foo(list: List<Int>) {
<caret>oldFun(list, 1, 2, 3)
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/modifiers/nestedDataClass.kt | 1 | 284 | // "Add 'inner' modifier" "false"
// ACTION: Create test
// ACTION: Do not show return expression hints
// ERROR: Class is not allowed here
// ERROR: Data class must have at least one primary constructor parameter
class A() {
inner class B() {
data class <caret>C
}
}
| apache-2.0 |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/export/support/PermissionUtils.kt | 1 | 508 | package com.maubis.scarlet.base.export.support
import android.Manifest
import androidx.appcompat.app.AppCompatActivity
import com.github.bijoysingh.starter.util.PermissionManager
class PermissionUtils() {
fun getStoragePermissionManager(activity: AppCompatActivity): PermissionManager {
val manager = PermissionManager(activity)
manager.setPermissions(
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE))
return manager
}
} | gpl-3.0 |
smmribeiro/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectTest.kt | 1 | 17362 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project
import com.intellij.compiler.CompilerConfiguration
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType.*
import com.intellij.openapi.externalSystem.model.project.LibraryLevel
import com.intellij.openapi.externalSystem.model.project.LibraryPathType
import com.intellij.platform.externalSystem.testFramework.ExternalSystemProjectTestCase
import com.intellij.platform.externalSystem.testFramework.ExternalSystemTestCase.collectRootsInside
import com.intellij.openapi.externalSystem.test.javaProject
import com.intellij.platform.externalSystem.testFramework.toDataNode
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.util.PathUtil
import junit.framework.TestCase
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.entry
import org.junit.Test
import java.io.File
class ExternalSystemProjectTest : ExternalSystemProjectTestCase() {
@Test
fun `test module names deduplication`() {
val projectModel = project {
module("root", externalProjectPath = "root")
module("root", externalProjectPath = "root/1")
module("root", externalProjectPath = "root/2")
module("root", externalProjectPath = "root/3")
module("root", externalProjectPath = "another/root")
module("root", externalProjectPath = "another/notRoot")
module("root", externalProjectPath = "root/root/root")
module("root", externalProjectPath = "root/root/root/root")
module("root", externalProjectPath = "yetanother/root/root")
module("group-root", externalProjectPath = "root")
module("group-root", externalProjectPath = "root/group/root")
module("group-root", externalProjectPath = "root/my/group/root")
module("group-root", externalProjectPath = "root/my-group/root")
}
val modelsProvider = IdeModelsProviderImpl(project)
applyProjectModel(projectModel)
val expectedNames = arrayOf(
"root", "1.root", "2.root", "3.root", "another.root", "notRoot.root", "root.root", "root.root.root", "yetanother.root.root",
"group-root", "root.group-root", "group.root.group-root", "my-group.root.group-root"
)
assertOrderedEquals(modelsProvider.modules.map { it.name }, *expectedNames)
// check reimport with the same data
applyProjectModel(projectModel)
assertOrderedEquals(modelsProvider.modules.map { it.name }, *expectedNames)
}
@Test
fun `test no duplicate library dependency is added on subsequent refresh when there is an unresolved library`() {
val projectModel = project {
module {
lib("lib1")
lib("lib2", unresolved = true)
}
}
applyProjectModel(projectModel, projectModel)
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module")
val entries = modelsProvider.getOrderEntries(module!!)
val dependencies = mutableMapOf<String?, Int>()
entries.groupingBy { (it as? LibraryOrderEntry)?.libraryName }.eachCountTo(dependencies).remove(null)
assertThat(dependencies).containsExactly(
entry("Test_external_system_id: lib1", 1),
entry("Test_external_system_id: lib2", 1)
)
}
@Test
fun `test no duplicate module dependency is added on subsequent refresh when duplicated dependencies exist`() {
val projectModel = project {
module("module1")
module("module2") {
moduleDependency("module1", DependencyScope.RUNTIME)
moduleDependency("module1", DependencyScope.TEST)
}
}
applyProjectModel(projectModel)
val assertOrderEntries = {
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module2")
val dependencies = modelsProvider.getOrderEntries(module!!)
.filterIsInstance<ExportableOrderEntry>().map { it.presentableName to it.scope }
val expected = listOf("module1" to DependencyScope.RUNTIME, "module1" to DependencyScope.TEST)
assertThat(dependencies).containsExactlyInAnyOrderElementsOf(expected)
}
assertOrderEntries.invoke()
// change dependency scope to test to get duplicated order entries
with(ProjectDataManager.getInstance().createModifiableModelsProvider(project)) {
val modifiableRootModel = getModifiableRootModel(findIdeModule("module2"))
modifiableRootModel.orderEntries.filterIsInstance<ExportableOrderEntry>().forEach { it.scope = DependencyScope.TEST }
runWriteAction { commit() }
}
applyProjectModel(projectModel)
assertOrderEntries.invoke()
}
@Test
fun `test optimized method for getting modules libraries order entries`() {
val libBinPath = File(projectPath, "bin_path")
val libSrcPath = File(projectPath, "source_path")
FileUtil.createDirectory(libBinPath)
FileUtil.createDirectory(libSrcPath)
val projectModel = project {
module {
lib("", level = LibraryLevel.MODULE) {
roots(LibraryPathType.BINARY, libBinPath.absolutePath)
}
lib("", level = LibraryLevel.MODULE) {
roots(LibraryPathType.BINARY, libSrcPath.absolutePath)
}
}
}
applyProjectModel(projectModel, projectModel)
val modelsProvider = IdeModelsProviderImpl(project)
val projectNode = projectModel.toDataNode()
val moduleNodeList = ExternalSystemApiUtil.findAll(projectNode, ProjectKeys.MODULE)
assertThat(moduleNodeList).hasSize(1)
val moduleNode = moduleNodeList.first()
assertEquals("module", moduleNode.data.moduleName)
val libraryDependencyDataList = ExternalSystemApiUtil.findAll(moduleNode, ProjectKeys.LIBRARY_DEPENDENCY)
.filter { it.data.level == LibraryLevel.MODULE }
.map { it.data }
val libraryOrderEntries = modelsProvider.findIdeModuleLibraryOrderEntries(moduleNode.data, libraryDependencyDataList)
assertThat(libraryOrderEntries).hasSize(2)
for ((libraryEntry, libraryData) in libraryOrderEntries) {
val expected = libraryData.target.getPaths(LibraryPathType.BINARY).map(PathUtil::getLocalPath)
val actual = libraryEntry.getUrls(OrderRootType.CLASSES).map { PathUtil.getLocalPath(VfsUtilCore.urlToPath(it)) }
assertThat(expected).containsExactlyInAnyOrderElementsOf(actual)
}
}
private fun buildProjectModel(contentRoots: Map<ExternalSystemSourceType, List<String>>) =
project {
module {
contentRoot {
for ((key, values) in contentRoots) {
values.forEach {
folder(type = key, relativePath = it)
}
}
}
}
}
@Test
fun `test changes in a project layout (content roots) could be detected on Refresh`() {
val contentRoots = mutableMapOf(
TEST to mutableListOf("src/test/resources", "/src/test/java", "src/test/groovy"),
SOURCE to mutableListOf("src/main/resources", "src/main/java", "src/main/groovy"),
EXCLUDED to mutableListOf(".gradle", "build")
)
(contentRoots[TEST]!! union contentRoots[SOURCE]!!).forEach {
FileUtil.createDirectory(File(projectPath, it))
}
val projectModelInitial = buildProjectModel(contentRoots)
contentRoots[SOURCE]!!.removeFirst()
contentRoots[TEST]!!.removeFirst()
val projectModelRefreshed = buildProjectModel(contentRoots)
applyProjectModel(projectModelInitial, projectModelRefreshed)
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module")!!
val entries = modelsProvider.getOrderEntries(module)
val folders = mutableMapOf<String?, Int>()
for (entry in entries) {
if (entry is ModuleSourceOrderEntry) {
val contentEntry = entry.rootModel.contentEntries.first()
folders.merge("source", contentEntry.sourceFolders.size, Integer::sum)
folders.merge("excluded", contentEntry.excludeFolders.size, Integer::sum)
}
}
assertThat(folders).containsExactly(entry("source", 4), entry("excluded", 2))
}
@Test
fun `test import does not fail if filename contains space`() {
val nameWithTrailingSpace = "source2 "
val contentRoots = mapOf(
SOURCE to listOf(" source1", nameWithTrailingSpace, "source 3")
)
// note, dir.mkdirs() used at ExternalSystemProjectTestCase.createProjectSubDirectory -> FileUtil.ensureExists
// will create "source2" instead of "source2 " on disk on Windows
contentRoots.forEach { (_, v) -> v.forEach { createProjectSubDirectory(it) } }
applyProjectModel(buildProjectModel(contentRoots), buildProjectModel(contentRoots))
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module")
if (module == null) {
fail("Could not find single module")
} else {
val folders = ArrayList<String>()
modelsProvider.getOrderEntries(module)
.filterIsInstance<ModuleSourceOrderEntry>()
.flatMap { it.rootModel.contentEntries.asIterable() }
.forEach { contentEntry -> folders.addAll(contentEntry.sourceFolders.map { File(it.url).name }) }
val expected = if (SystemInfo.isWindows) contentRoots[SOURCE]!! - nameWithTrailingSpace else contentRoots[SOURCE]
TestCase.assertEquals(expected, folders)
}
}
@Test
fun `test excluded directories merge`() {
val contentRoots = mutableMapOf(
EXCLUDED to mutableListOf(".gradle", "build")
)
val projectModelInitial = buildProjectModel(contentRoots)
contentRoots[EXCLUDED]!!.removeFirst()
contentRoots[EXCLUDED]!!.add("newExclDir")
val projectModelRefreshed = buildProjectModel(contentRoots)
applyProjectModel(projectModelInitial, projectModelRefreshed)
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module")!!
val folders = mutableListOf<String>()
modelsProvider.getOrderEntries(module)
.filterIsInstance<ModuleSourceOrderEntry>()
.flatMap { it.rootModel.contentEntries.asIterable() }
.forEach { contentEntry -> folders.addAll(contentEntry.excludeFolders.map { File(it.url).name }) }
assertThat(folders).containsExactlyInAnyOrderElementsOf(listOf(".gradle", "build", "newExclDir"))
}
@Test
fun `test library dependency with sources path added on subsequent refresh`() {
val libBinPath = File(projectPath, "bin_path")
val libSrcPath = File(projectPath, "source_path")
val libDocPath = File(projectPath, "doc_path")
FileUtil.createDirectory(libBinPath)
FileUtil.createDirectory(libSrcPath)
FileUtil.createDirectory(libDocPath)
applyProjectModel(
project {
module {
lib("lib1", level = LibraryLevel.MODULE) {
roots(LibraryPathType.BINARY, libBinPath.absolutePath)
}
}
},
project {
module {
lib("lib1", level = LibraryLevel.MODULE) {
roots(LibraryPathType.BINARY, libBinPath.absolutePath)
roots(LibraryPathType.SOURCE, libSrcPath.absolutePath)
}
}
},
project {
module {
lib("lib1", level = LibraryLevel.MODULE) {
roots(LibraryPathType.BINARY, libBinPath.absolutePath)
roots(LibraryPathType.SOURCE, libSrcPath.absolutePath)
roots(LibraryPathType.DOC, libDocPath.absolutePath)
}
}
}
)
val modelsProvider = IdeModelsProviderImpl(project)
val module = modelsProvider.findIdeModule("module")!!
val dependencies = mutableMapOf<String?, Int>()
for (entry in modelsProvider.getOrderEntries(module)) {
if (entry is LibraryOrderEntry) {
val name = entry.libraryName
dependencies.merge(name, 1, Integer::sum)
if ("Test_external_system_id: lib1" == name) {
val classesUrls = entry.getUrls(OrderRootType.CLASSES)
assertThat(classesUrls).hasSize(1)
assertTrue(classesUrls.first().endsWith("bin_path"))
val sourceUrls = entry.getUrls(OrderRootType.SOURCES)
assertThat(sourceUrls).hasSize(1)
assertTrue(sourceUrls.first().endsWith("source_path"))
val docUrls = entry.getUrls(JavadocOrderRootType.getInstance())
assertThat(docUrls).hasSize(1)
assertTrue(docUrls.first().endsWith("doc_path"))
}
else {
fail()
}
}
}
assertThat(dependencies).containsExactly(entry("Test_external_system_id: lib1", 1))
}
@Test
fun `test package prefix setup`() {
createProjectSubDirectory("src/main/java")
applyProjectModel(
project {
module {
contentRoot {
folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "org.example")
}
}
}
)
assertSourcePackagePrefix("module", "src/main/java", "org.example")
applyProjectModel(
project {
module {
contentRoot {
folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "org.jetbrains")
}
}
}
)
assertSourcePackagePrefix("module", "src/main/java", "org.jetbrains")
applyProjectModel(
project {
module {
contentRoot {
folder(type = SOURCE, relativePath = "src/main/java", packagePrefix = "")
}
}
}
)
assertSourcePackagePrefix("module", "src/main/java", "org.jetbrains")
}
@Test
fun `test project SDK configuration import`() {
val myJdkName = "My JDK"
val myJdkHome = IdeaTestUtil.requireRealJdkHome()
val allowedRoots = mutableListOf<String>()
allowedRoots.add(myJdkHome)
allowedRoots.addAll(collectRootsInside(myJdkHome))
VfsRootAccess.allowRootAccess(testRootDisposable, *allowedRoots.toTypedArray())
runWriteAction {
val oldJdk = ProjectJdkTable.getInstance().findJdk(myJdkName)
if (oldJdk != null) {
ProjectJdkTable.getInstance().removeJdk(oldJdk)
}
val jdkHomeDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(File(myJdkHome))!!
val jdk = SdkConfigurationUtil.setupSdk(emptyArray(), jdkHomeDir, JavaSdk.getInstance(), true, null, myJdkName)
assertNotNull("Cannot create JDK for $myJdkHome", jdk)
ProjectJdkTable.getInstance().addJdk(jdk!!, project)
}
applyProjectModel(
project {
javaProject(compileOutputPath = "$projectPath/out",
languageLevel = LanguageLevel.JDK_1_7,
targetBytecodeVersion = "1.5")
}
)
val languageLevelExtension = LanguageLevelProjectExtension.getInstance(project)
assertEquals(LanguageLevel.JDK_1_7, languageLevelExtension.languageLevel)
val compilerConfiguration = CompilerConfiguration.getInstance(project)
assertEquals("1.5", compilerConfiguration.projectBytecodeTarget)
}
private fun assertSourcePackagePrefix(moduleName: String, sourcePath: String, packagePrefix: String) {
val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) }
assertNotNull("Module $moduleName not found", module)
assertSourcePackagePrefix(module!!, sourcePath, packagePrefix)
}
private fun assertSourcePackagePrefix(module: com.intellij.openapi.module.Module, sourcePath: String, packagePrefix: String) {
val rootManger = ModuleRootManager.getInstance(module)
val sourceFolder = findSourceFolder(rootManger, sourcePath)
assertNotNull("Source folder $sourcePath not found in module ${module.name}", sourceFolder)
assertEquals(packagePrefix, sourceFolder!!.packagePrefix)
}
private fun findSourceFolder(moduleRootManager: ModuleRootModel, sourcePath: String): SourceFolder? {
val contentEntries = moduleRootManager.contentEntries
val module = moduleRootManager.module
val externalProjectPath = ExternalSystemApiUtil.getExternalProjectPath(module) ?: return null
for (contentEntry in contentEntries) {
for (sourceFolder in contentEntry.sourceFolders) {
val folderPath = urlToPath(sourceFolder.url)
val rootPath = urlToPath("$externalProjectPath/$sourcePath")
if (folderPath == rootPath) return sourceFolder
}
}
return null
}
private fun urlToPath(url: String): String {
val path = VfsUtilCore.urlToPath(url)
return FileUtil.toSystemIndependentName(path)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/constant/Read.kt | 9 | 72 | package one.two
fun read() {
val c = KotlinObject.Nested.constant
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/boxedType/kt-671.kt | 13 | 127 | internal class Test {
fun test() {
val i = Integer.valueOf(100)
val s: Short = 3
val ss = s
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/iterable.kt | 9 | 110 | // WITH_STDLIB
fun test(i: Iterable<Int>): List<Int> {
return i.<caret>filter { it > 1 }.map { it * 2 }
} | apache-2.0 |
Helabs/generator-he-kotlin-mvp | app/templates/app_mvp/src/debug/kotlin/data/DebugApiModule.kt | 1 | 321 | package <%= appPackage %>.data
import com.facebook.stetho.okhttp3.StethoInterceptor
import dagger.Module
import okhttp3.OkHttpClient
@Module
class DebugApiModule: ApiModule() {
override fun getOkHttpBuilder(): OkHttpClient.Builder =
super.getOkHttpBuilder().addNetworkInterceptor(StethoInterceptor())
}
| mit |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/addValVar/addValAfterVarArg.kt | 6 | 93 | // "Add 'val'/'var' to parameter 'x'" "true"
class Foo(vararg <caret>x: Int, val y: Int) {
} | apache-2.0 |
LouisCAD/Splitties | modules/mainthread/src/androidTest/kotlin/splitties/mainthread/MainThreadCheckingPerformanceTest.kt | 1 | 4001 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.mainthread
import android.os.Looper
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LIBRARY_IMPL
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_BY_ID
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_ID
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_REF
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOOPER
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOOPER_THREAD_REF
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.THREAD_EQUALS
import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.THREAD_ID
import kotlin.system.measureNanoTime
import kotlin.test.Test
import kotlin.test.assertTrue
class MainThreadCheckingPerformanceTest {
private enum class MainThreadCheckTechnique {
LOOPER,
THREAD_ID,
THREAD_EQUALS,
LOCAL_CACHED_THREAD_BY_ID,
LOCAL_CACHED_THREAD_ID,
LOOPER_THREAD_REF,
LOCAL_CACHED_THREAD_REF,
LIBRARY_IMPL
}
@Test
fun compareMainThreadChecks(): Unit = runBlocking(Dispatchers.Main) {
val techniqueList = MainThreadCheckTechnique.values().asList()
val results = mutableMapOf<MainThreadCheckTechnique, Long>().also { resultsMap ->
val reverseList = techniqueList.reversed()
repeat(100) { i ->
val runList = (if (i % 2 == 0) techniqueList else reverseList)
runList.onEach { technique ->
val result = runBenchmark(technique)
resultsMap[technique] = resultsMap.getOrElse(technique) { 0 } + result
}
}
}.toList().sortedBy { (_, result) -> result }
val techniqueNameLength = MainThreadCheckTechnique.values().maxBy {
it.name.length
}!!.name.length
val tag = "MainThreadPerformanceTest"
Log.i(tag, "Benchmark results below")
results.forEach { (technique, result) ->
val techName = technique.name.replace('_', ' ').toLowerCase().capitalize()
.padEnd(techniqueNameLength)
Log.d(tag, "$techName duration (in µs): $result")
}
assertTrue("Library implementation should be the fastest technique! Check logs.") {
val (technique, _) = results.minBy { (_, result) -> result }!!
technique == LIBRARY_IMPL
}
}.let { Unit }
private fun runBenchmark(technique: MainThreadCheckTechnique): Long {
val mainThread = mainLooper.thread
val mainThreadId = mainThread.id
return when (technique) {
LIBRARY_IMPL -> benchmark { isMainThread }
LOOPER -> benchmark { mainLooper == Looper.myLooper() }
THREAD_ID -> benchmark { mainLooper.thread.id == Thread.currentThread().id }
THREAD_EQUALS -> benchmark { mainLooper.thread == Thread.currentThread() }
LOCAL_CACHED_THREAD_BY_ID -> benchmark { mainThread.id == Thread.currentThread().id }
LOCAL_CACHED_THREAD_ID -> benchmark { mainThreadId == Thread.currentThread().id }
LOOPER_THREAD_REF -> benchmark { mainLooper.thread === Thread.currentThread() }
LOCAL_CACHED_THREAD_REF -> benchmark {
mainThread == Thread.currentThread() // This seems to be the fastest technique.
}
}
}
private inline fun benchmark(runs: Int = 10_000, f: () -> Boolean): Long = measureNanoTime {
repeat(runs) { check(f()) }
} / 1000
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/project-model/src/org/jetbrains/kotlin/idea/projectModel/CompilerArgumentsCacheAware.kt | 5 | 935 | // 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.projectModel
import java.io.Serializable
/**
* Entity is used for storing information about IDs for compiler argument caches.
* API allows only to retrieve info, entity acts as immutable container
*
* @constructor Create empty Compiler arguments cache aware
*/
interface CompilerArgumentsCacheAware : Serializable, CacheOriginIdentifierAware {
/**
* Retrieve compiler argument value from cache
*
* @param cacheId Int cache id number to retrieve
* @return `String` value of compiler argument or null if it is absent
*/
fun getCached(cacheId: Int): String?
/**
* Distribute cache ids
*
* @return container with all used Cache Ids
*/
fun distributeCacheIds(): Iterable<Int>
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/extensionPropertyOnTypeAliasFromOtherTypeAlias.after.kt | 3 | 137 | // "Import" "true"
// ERROR: Unresolved reference: ext
import dep.TA1
import dep.ext
fun use() {
val ta = TA1()
ta.ext<caret>
} | apache-2.0 |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/editor/EditorView.kt | 1 | 12678 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.editor
import android.app.Activity
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.linkedin.android.spyglass.mentions.MentionsEditable
import com.linkedin.android.spyglass.suggestions.SuggestionsResult
import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager
import com.linkedin.android.spyglass.tokenization.QueryToken
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig
import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.STATUS_LIMIT
import com.sinyuk.fanfou.domain.StatusCreation
import com.sinyuk.fanfou.glide.GlideApp
import com.sinyuk.fanfou.ui.QMUIRoundButtonDrawable
import com.sinyuk.fanfou.util.PictureHelper
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.fanfou.viewmodel.PlayerViewModel
import com.sinyuk.myutils.system.ToastUtils
import kotlinx.android.synthetic.main.editor_picture_list_item.view.*
import kotlinx.android.synthetic.main.editor_view.*
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/16.
*
*/
class EditorView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager {
companion object {
fun newInstance(id: String? = null, content: MentionsEditable? = null, action: Int, screenName: String? = null) = EditorView().apply {
arguments = Bundle().apply {
putString("id", id)
putParcelable("content", content)
putInt("action", action)
putString("screenName", screenName)
}
}
const val OPEN_PICTURE_REQUEST_CODE = 0X123
}
override fun layoutId() = R.layout.editor_view
@Inject
lateinit var factory: FanfouViewModelFactory
private val queryMap = mutableMapOf<String, String?>()
private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) }
override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
super.onEnterAnimationEnd(savedInstanceState)
closeButton.setOnClickListener { pop() }
setupKeyboard()
setupEditor()
renderUI()
val action = arguments!!.getInt("action")
when (action) {
StatusCreation.CREATE_NEW -> {
actionButton.text = "发送"
}
StatusCreation.REPOST_STATUS -> {
arguments!!.getParcelable<MentionsEditable>("content")?.let { contentEt.text = it }
arguments!!.getString("id")?.let { queryMap["repost_status_id"] = it }
actionButton.text = "转发"
}
else -> TODO()
}
onFormValidation(0)
}
private val config = WordTokenizerConfig.Builder().setExplicitChars("@").setThreshold(1).setWordBreakChars(" ").build()
private fun setupEditor() {
contentEt.tokenizer = WordTokenizer(config)
contentEt.setAvoidPrefixOnTap(true)
contentEt.setQueryTokenReceiver(this)
contentEt.setSuggestionsVisibilityManager(this)
contentEt.setAvoidPrefixOnTap(true)
textCountProgress.max = STATUS_LIMIT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) textCountProgress.min = 0
// contentEt.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(STATUS_LIMIT))
contentEt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
onTextCountUpdated(s?.length ?: 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
/**
* @param count 字数
*/
private fun onTextCountUpdated(count: Int) {
onFormValidation(count)
textCountProgress.progress = count
textCount.text = count.toString()
}
private fun renderUI() {
actionButton.setOnClickListener {
}
addPictureButton.setOnClickListener {
startActivityForResult(PictureHelper.fileSearchIntent(), OPEN_PICTURE_REQUEST_CODE)
}
pictureItem.image.setOnClickListener {
startActivityForResult(PictureHelper.fileSearchIntent(), OPEN_PICTURE_REQUEST_CODE)
}
pictureItem.deleteButton.setOnClickListener {
viewAnimator.displayedChildId = R.id.emptyLayout
uri = null
GlideApp.with(this).clear(pictureItem.image)
onFormValidation(contentEt.text.length)
}
pictureItem.editButton.setOnClickListener {
val editIntent = Intent(Intent.ACTION_EDIT)
editIntent.setDataAndType(uri, "image/*")
editIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
startActivity(Intent.createChooser(editIntent, null))
}
}
private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null
private fun setupKeyboard() {
nestedScrollView.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_UP) KPSwitchConflictUtil.hidePanelAndKeyboard(panelRoot)
return@setOnTouchListener false
}
keyboardListener = KeyboardUtil.attach(activity, panelRoot, {
panelRoot.visibility =
if (it) {
if (contentEt.requestFocus()) contentEt.setSelection(contentEt.text.length)
View.VISIBLE
} else {
contentEt.clearFocus()
View.GONE
}
})
}
@Suppress("PrivatePropertyName")
private val BUCKET = "player-mentioned"
override fun onQueryReceived(queryToken: QueryToken): MutableList<String> {
val data = playerViewModel.filter(queryToken.keywords)
onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET)
return arrayOf(BUCKET).toMutableList()
}
override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) {
val data = result.suggestions
displaySuggestions(data?.isNotEmpty() == true)
if (data?.isEmpty() != false) return
if (findChildFragment(MentionListView::class.java) == null) {
val fragment = MentionListView.newInstance(data.toTypedArray())
fragment.onItemClickListener = object : MentionListView.OnItemClickListener {
override fun onItemClick(position: Int, item: Suggestible) {
(item as Player).let {
contentEt.insertMention(it)
displaySuggestions(false)
playerViewModel.updateMentionedAt(it) //
onTextCountUpdated(contentEt.text.length)
contentEt.requestFocus()
contentEt.setSelection(contentEt.text.length)
}
}
}
loadRootFragment(R.id.mentionLayout, fragment)
} else {
findChildFragment(MentionListView::class.java)?.apply {
showHideFragment(this)
setData(data = data)
}
}
}
override fun displaySuggestions(display: Boolean) {
viewAnimator.displayedChildId = if (display) {
R.id.mentionLayout
} else {
if (uri == null) {
R.id.emptyLayout
} else {
R.id.pictureLayout
}
}
}
private fun onFormValidation(count: Int) {
if (count in 1..STATUS_LIMIT || isPictureValid()) {
if (actionButton.isEnabled) return
(actionButton.background as QMUIRoundButtonDrawable).color = ColorStateList.valueOf(ContextCompat.getColor(context!!, R.color.colorControlActivated))
actionButton.isEnabled = true
} else {
if (!actionButton.isEnabled) return
(actionButton.background as QMUIRoundButtonDrawable).color = ColorStateList.valueOf(ContextCompat.getColor(context!!, R.color.colorControlDisable))
actionButton.isEnabled = false
}
}
private fun isPictureValid() = uri != null
override fun isDisplayingSuggestions() = viewAnimator.displayedChildId == R.id.mentionLayout
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == OPEN_PICTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
data?.let { showImage(it.data) }
}
}
@Inject
lateinit var toast: ToastUtils
private var uri: Uri? = null
private fun showImage(data: Uri?) {
if (data == null) {
uri = null
onFormValidation(contentEt.text.length)
GlideApp.with(this).clear(pictureItem.image)
viewAnimator.displayedChildId = R.id.emptyLayout
} else {
GlideApp.with(this).asBitmap().load(data).listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
toast.toastShort(e?.message ?: "( ˉ ⌓ ˉ ๑)图片加载失败")
viewAnimator.displayedChildId = if (uri == null) {
R.id.emptyLayout
} else {
R.id.pictureLayout
}
onFormValidation(contentEt.text.length)
return false
}
override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
uri = data
onFormValidation(contentEt.text.length)
viewAnimator.displayedChildId = R.id.pictureLayout
return false
}
}).into(pictureItem.image)
}
}
override fun onDestroy() {
keyboardListener?.let { KeyboardUtil.detach(activity, it) }
activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) }
super.onDestroy()
}
} | mit |
testIT-LivingDoc/livingdoc2 | livingdoc-repository-file/src/main/kotlin/org/livingdoc/repositories/file/DocumentFile.kt | 2 | 343 | package org.livingdoc.repositories.file
import java.io.File
import org.livingdoc.repositories.Document
/**
* A DocumentFile wraps a [File] that contains a [Document]
*
* @see Document
* @see File
*/
open class DocumentFile(private val file: File) {
open fun extension() = file.extension
open fun stream() = file.inputStream()
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | platform/lang-api/src/com/intellij/execution/configurations/LogFileOptions.kt | 3 | 4327 | /*
* 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 com.intellij.execution.configurations
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.xmlb.Converter
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Tag
import java.io.File
import java.nio.charset.Charset
import java.util.regex.Pattern
/**
* The information about a single log file displayed in the console when the configuration
* is run.
*
* @since 5.1
*/
@Tag("log_file")
class LogFileOptions : BaseState {
companion object {
@JvmStatic
fun collectMatchedFiles(root: File, pattern: Pattern, files: MutableList<File>) {
val dirs = root.listFiles() ?: return
dirs.filterTo(files) { pattern.matcher(it.name).matches() && it.isFile }
}
@JvmStatic
fun areEqual(options1: LogFileOptions?, options2: LogFileOptions?): Boolean {
return if (options1 == null || options2 == null) {
options1 === options2
}
else options1.name == options2.name &&
options1.pathPattern == options2.pathPattern &&
!options1.isShowAll == !options2.isShowAll &&
options1.isEnabled == options2.isEnabled &&
options1.isSkipContent == options2.isSkipContent
}
}
@get:Attribute("alias")
var name by string()
@get:Attribute(value = "path", converter = PathConverter::class)
var pathPattern by string()
@get:Attribute("checked")
var isEnabled by property(true)
@get:Attribute("skipped")
var isSkipContent by property(true)
@get:Attribute("show_all")
var isShowAll by property(false)
@get:Attribute(value = "charset", converter = CharsetConverter::class)
var charset: Charset by property(Charset.defaultCharset())
fun getPaths(): Set<String> {
val logFile = File(pathPattern!!)
if (logFile.exists()) {
return setOf(pathPattern!!)
}
val dirIndex = pathPattern!!.lastIndexOf(File.separator)
if (dirIndex == -1) {
return emptySet()
}
val files = SmartList<File>()
collectMatchedFiles(File(pathPattern!!.substring(0, dirIndex)),
Pattern.compile(FileUtil.convertAntToRegexp(pathPattern!!.substring(dirIndex + File.separator.length))), files)
if (files.isEmpty()) {
return emptySet()
}
if (isShowAll) {
val result = SmartHashSet<String>()
result.ensureCapacity(files.size)
files.mapTo(result) { it.path }
return result
}
else {
var lastFile: File? = null
for (file in files) {
if (lastFile != null) {
if (file.lastModified() > lastFile.lastModified()) {
lastFile = file
}
}
else {
lastFile = file
}
}
assert(lastFile != null)
return setOf(lastFile!!.path)
}
}
//read external
constructor()
@JvmOverloads
constructor(name: String?, path: String?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) : this(name, path, null, enabled, skipContent, showAll)
@JvmOverloads
constructor(name: String?, path: String?, charset: Charset?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) {
this.name = name
pathPattern = path
isEnabled = enabled
isSkipContent = skipContent
isShowAll = showAll
this.charset = charset ?: Charset.defaultCharset()
}
fun setLast(last: Boolean) {
isShowAll = !last
}
}
private class PathConverter : Converter<String>() {
override fun fromString(value: String): String? {
return FileUtilRt.toSystemDependentName(value)
}
override fun toString(value: String): String {
return FileUtilRt.toSystemIndependentName(value)
}
}
private class CharsetConverter : Converter<Charset>() {
override fun fromString(value: String): Charset? {
return try {
Charset.forName(value)
}
catch (ignored: Exception) {
Charset.defaultCharset()
}
}
override fun toString(value: Charset): String {
return value.name()
}
} | apache-2.0 |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Widget/GatherDialogFragment.kt | 1 | 5705 | package stan.androiddemo.project.petal.Widget
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.project.petal.API.OperateAPI
import stan.androiddemo.project.petal.Base.BaseDialogFragment
import stan.androiddemo.project.petal.Event.OnDialogInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Module.ImageDetail.GatherInfoBean
import stan.androiddemo.tool.Logger
/**
* Created by stanhu on 14/8/2017.
*/
class GatherDialogFragment: BaseDialogFragment() {
lateinit var mEditTextDescribe: EditText
lateinit var mTVGatherWarning: TextView
lateinit var mSpinnerBoardTitle: Spinner
lateinit var mContext: Context
lateinit var mViaId: String
lateinit var mDescribeText: String
lateinit var mBoardTitleArray: ArrayList<String>
private var mSelectPosition = 0//默认的选中项
var mListener:OnDialogInteractionListener? = null
override fun getTAGInfo(): String {
return this.toString()
}
companion object {
private val KEYAUTHORIZATION = "keyAuthorization"
private val KEYVIAID = "keyViaId"
private val KEYDESCRIBE = "keyDescribe"
private val KEYBOARDTITLEARRAY = "keyBoardTitleArray"
fun create(authorization:String,viaId:String,describe:String,boardTitleArray:ArrayList<String>):GatherDialogFragment{
val bundle = Bundle()
bundle.putString(KEYAUTHORIZATION,authorization)
bundle.putString(KEYVIAID,viaId)
bundle.putString(KEYDESCRIBE,describe)
bundle.putStringArrayList(KEYBOARDTITLEARRAY,boardTitleArray)
val fragment = GatherDialogFragment()
fragment.arguments = bundle
return fragment
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
mContext = context!!
if (context is OnDialogInteractionListener){
mListener = context
}
else{
throwRuntimeException(context)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAuthorization = arguments.getString(KEYAUTHORIZATION)
mViaId = arguments.getString(KEYVIAID)
mDescribeText = arguments.getString(KEYDESCRIBE)
mBoardTitleArray = arguments.getStringArrayList(KEYBOARDTITLEARRAY)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(mContext)
builder.setTitle(resources.getString(R.string.dialog_title_gather))
val inflate = LayoutInflater.from(mContext)
val dialogView = inflate.inflate(R.layout.petal_dialog_gather,null)
initView(dialogView)
builder.setView(dialogView)
builder.setNegativeButton(resources.getString(R.string.dialog_negative),null)
builder.setPositiveButton(resources.getString(R.string.dialog_gather_positive),DialogInterface.OnClickListener { dialogInterface, i ->
var input = mEditTextDescribe.text.toString().trim()
if (input.isNullOrEmpty()){
input = mEditTextDescribe.hint.toString()
}
mListener?.onDialogClick(true, hashMapOf("describe" to input,"position" to mSelectPosition))
})
addSubscription(getGatherInfo())
return builder.create()
}
fun initView(view: View){
mEditTextDescribe = view.findViewById(R.id.edit_describe)
mTVGatherWarning = view.findViewById(R.id.tv_gather_warning)
mSpinnerBoardTitle = view.findViewById(R.id.spinner_title)
val adapter = ArrayAdapter<String>(context,R.layout.support_simple_spinner_dropdown_item,mBoardTitleArray)
if (!mDescribeText.isNullOrEmpty()){
mEditTextDescribe.hint = mDescribeText
}
else{
mEditTextDescribe.hint = resources.getString(R.string.text_image_describe_null)
}
mSpinnerBoardTitle.adapter = adapter
mSpinnerBoardTitle.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
Logger.d("position=" + position)
mSelectPosition = position
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
}
fun getGatherInfo():Subscription{
return RetrofitClient.createService(OperateAPI::class.java).httpsGatherInfo(mAuthorization,mViaId,true)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object:Subscriber<GatherInfoBean>(){
override fun onNext(t: GatherInfoBean?) {
if (t?.exist_pin != null){
val format = resources.getString(R.string.text_gather_warning)
mTVGatherWarning.visibility = View.VISIBLE
mTVGatherWarning.text = String.format(format,t!!.exist_pin!!.board?.title)
}
}
override fun onError(e: Throwable?) {
}
override fun onCompleted() {
}
})
}
} | mit |
shofujimoto/examples | until_201803/kotlin/todo-spark/src/main/java/todolist/JsonTransformer.kt | 1 | 288 | package todolist
import com.fasterxml.jackson.databind.ObjectMapper
import spark.ResponseTransformer
class JsonTransformer(private val objectMapper: ObjectMapper) : ResponseTransformer {
override fun render(model: Any?): String =
objectMapper.writeValueAsString(model)
} | mit |
sksamuel/ktest | kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/internal/tags/lookup.kt | 1 | 1594 | package io.kotest.core.internal.tags
import io.kotest.core.Tag
import io.kotest.core.Tags
import io.kotest.core.config.Configuration
import io.kotest.core.extensions.TagExtension
import io.kotest.core.test.TestCase
import kotlin.reflect.KClass
import io.kotest.core.NamedTag
import io.kotest.mpp.annotation
/**
* Returns all runtime tags when invoked, wrapping into an instance of [Tags].
*/
interface TagProvider {
fun tags(): Tags
}
/**
* Implementation of [TagProvider] that uses a [Configuration] to provide those tags.
*/
class ConfigurationTagProvider(private val configuration: Configuration) : TagProvider {
override fun tags(): Tags = configuration.activeTags()
}
/**
* Returns the tags specified on the given class from the @Tags annotation if present.
*/
fun KClass<*>.tags(): Set<Tag> {
val annotation = annotation<io.kotest.core.annotation.Tags>() ?: return emptySet()
return annotation.values.map { NamedTag(it) }.toSet()
}
/**
* Returns runtime active [Tag]'s by invocating all registered [TagExtension]s and combining
* any returned tags into a [Tags] container.
*/
fun Configuration.activeTags(): Tags {
val extensions = this.extensions().filterIsInstance<TagExtension>()
return if (extensions.isEmpty()) Tags.Empty else extensions.map { it.tags() }.reduce { a, b -> a.combine(b) }
}
/**
* Returns all tags assigned to a [TestCase], taken from the test case config, spec inline function,
* spec override function, or the spec class.
*/
fun TestCase.allTags(): Set<Tag> = this.config.tags + this.spec.declaredTags() + this.spec::class.tags()
| mit |
intrigus/jtransc | jtransc-core/src/com/jtransc/ast/optimize/ast_optimize.kt | 1 | 10987 | package com.jtransc.ast.optimize
import com.jtransc.ast.*
import com.jtransc.log.log
//const val DEBUG = false
//const val DEBUG = true
// @TODO: rewrite using method.transformInplace
class AstOptimizer(val flags: AstBodyFlags) : AstVisitor() {
val types: AstTypes = flags.types
private var stm: AstStm? = null
override fun visit(stm: AstStm?) {
super.visit(stm)
this.stm = stm
}
val METHODS_TO_STRIP = setOf<AstMethodRef>(
AstMethodRef("kotlin.jvm.internal.Intrinsics".fqname, "checkParameterIsNotNull", AstType.METHOD(AstType.VOID, listOf(AstType.OBJECT, AstType.STRING)))
)
private val invertComparisons = mapOf(
AstBinop.LT to AstBinop.GE,
AstBinop.LE to AstBinop.GT,
AstBinop.EQ to AstBinop.NE,
AstBinop.NE to AstBinop.EQ,
AstBinop.GT to AstBinop.LE,
AstBinop.GE to AstBinop.LT
)
override fun visit(expr: AstExpr.BINOP) {
super.visit(expr)
val box = expr.box
val left = expr.left.value
val right = expr.right.value
when (expr.op) {
AstBinop.EQ, AstBinop.NE -> {
if ((left is AstExpr.CAST) && (right is AstExpr.LITERAL)) {
if (left.from == AstType.BOOL && left.to == AstType.INT && right.value is Int) {
//println("optimize")
val leftExpr = left.subject.value
val toZero = right.value == 0
val equals = expr.op == AstBinop.EQ
box.value = if (toZero xor equals) leftExpr else AstExpr.UNOP(AstUnop.NOT, leftExpr)
AstAnnotateExpressions.visitExprWithStm(stm, box)
}
}
}
AstBinop.LT, AstBinop.LE, AstBinop.GT, AstBinop.GE -> {
if (!flags.strictfp && (left is AstExpr.BINOP) && (right is AstExpr.LITERAL)) {
when (left.op) {
AstBinop.CMPG, AstBinop.CMPL -> {
val l = left.left
val r = left.right
val op = expr.op
val compareValue = right.value
if (compareValue == 0) {
box.value = AstExpr.UNOP(AstUnop.NOT, AstExpr.BINOP(AstType.BOOL, l.value, invertComparisons[op]!!, r.value))
} else {
log.warn("WARNING: Unhandled float comparison (because compareValue != 0)! op = ${expr.op} :: compareValue = $compareValue")
}
}
else -> Unit
}
}
}
else -> Unit
}
}
override fun visit(expr: AstExpr.CALL_BASE) {
//println("CALL_BASE:$expr:${expr.method}")
super.visit(expr)
}
override fun visit(expr: AstExpr.CALL_STATIC) {
super.visit(expr)
if (expr.method in METHODS_TO_STRIP) {
//println("STRIP:${expr.method}")
expr.stm?.box?.value = AstStm.NOP("method to strip")
} else {
//println("NO_STRIP:${expr.method}")
}
}
override fun visit(body: AstBody?) {
if (body == null) return
// @TODO: this should be easier when having the SSA form
for (local in body.locals) {
if (local.writes.size == 1) {
val write = local.writes[0]
var writeExpr2 = write.expr.value
while (writeExpr2 is AstExpr.CAST) writeExpr2 = writeExpr2.subject.value
val writeExpr = writeExpr2
//println("Single write: $local = $writeExpr")
when (writeExpr) {
is AstExpr.PARAM, is AstExpr.THIS -> { // LITERALS!
for (read in local.reads) {
//println(" :: read: $read")
read.box.value = write.expr.value.clone()
}
write.box.value = AstStm.NOP("optimized literal")
local.writes.clear()
local.reads.clear()
}
}
//println("Written once! $local")
}
}
super.visit(body)
// REMOVE UNUSED VARIABLES
//body.locals = body.locals.filter { it.isUsed }
val unoptstms = body.stm.expand()
//if (unoptstms.any { it is AstStm.NOP }) {
// println("done")
//}
val optstms = unoptstms.filter { it !is AstStm.NOP }
body.stm = optstms.stm()
//if (unoptstms.any { it is AstStm.NOP }) {
// println("done")
//}
val stms = body.stm.expand().map { it.box }
var n = 0
while (n < stms.size) {
val startStmIndex = n
val abox = stms[n++]
val a = abox.value
if ((a is AstStm.SET_ARRAY) && (a.index.value is AstExpr.LITERAL) && (a.array.value is AstExpr.CAST) && ((a.array.value as AstExpr.CAST).subject.value is AstExpr.LOCAL)) {
val exprs = arrayListOf<AstExpr.Box>()
val alocal = ((a.array.value as AstExpr.CAST).subject.value as AstExpr.LOCAL).local
val baseindex = (a.index.value as AstExpr.LITERAL).value as Int
var lastindex = baseindex
exprs += a.expr
while (n < stms.size) {
val bbox = stms[n++]
val b = bbox.value
if ((b is AstStm.SET_ARRAY) && (b.index.value is AstExpr.LITERAL) && (b.array.value is AstExpr.CAST) && ((b.array.value as AstExpr.CAST).subject.value is AstExpr.LOCAL)) {
val blocal = ((b.array.value as AstExpr.CAST).subject.value as AstExpr.LOCAL).local
val nextindex = (b.index.value as AstExpr.LITERAL).value as Int
if (alocal == blocal && nextindex == lastindex + 1) {
exprs += b.expr
//println("$baseindex, $lastindex, $nextindex")
lastindex = nextindex
continue
}
}
n--
break
}
if (baseindex != lastindex) {
for (m in startStmIndex until n) stms[m].value = AstStm.NOP("array_literals")
stms[startStmIndex].value = AstStm.SET_ARRAY_LITERALS(a.array.value, baseindex, exprs)
//println("ranged: $baseindex, $lastindex")
}
}
}
}
override fun visit(stm: AstStm.STMS) {
super.visit(stm)
for (n in 1 until stm.stms.size) {
val abox = stm.stms[n - 1]
val bbox = stm.stms[n - 0]
val a = abox.value
val b = bbox.value
//println("${a.javaClass}")
if (a is AstStm.SET_LOCAL && b is AstStm.SET_LOCAL) {
val alocal = a.local.local
val blocal = b.local.local
val aexpr = a.expr.value
val bexpr = b.expr.value
if (aexpr is AstExpr.LOCAL && bexpr is AstExpr.LOCAL) {
//println("double set locals! $alocal = ${aexpr.local} :: ${blocal} == ${bexpr.local}")
if ((alocal == bexpr.local) && (aexpr.local == blocal)) {
//println("LOCAL[a]:" + alocal)
blocal.writes.remove(b)
alocal.reads.remove(bexpr)
val aold = a
abox.value = AstStm.NOP("optimized set local")
bbox.value = aold
//println("LOCAL[b]:" + alocal)
//println("double set! CROSS!")
}
}
}
if (a is AstStm.SET_LOCAL && a.expr.value is AstExpr.LOCAL) {
//val blocal = a.expr.value as AstExpr.LOCAL
val alocal = a.local.local
if (alocal.writesCount == 1 && alocal.readCount == 1 && alocal.reads.first().stm == b) {
alocal.reads.first().box.value = a.expr.value
abox.value = AstStm.NOP("optimized set local 2")
alocal.writes.clear()
alocal.reads.clear()
}
}
}
val finalStms = stm.stms.filter { it.value !is AstStm.NOP }
if (finalStms.size == 1) {
stm.box.value = finalStms.first().value
}
}
override fun visit(expr: AstExpr.UNOP) {
super.visit(expr)
if (expr.op == AstUnop.NOT) {
val right = expr.right.value
when (right) {
is AstExpr.BINOP -> {
val newop = when (right.op) {
AstBinop.NE -> AstBinop.EQ
AstBinop.EQ -> AstBinop.NE
AstBinop.LT -> AstBinop.GE
AstBinop.LE -> AstBinop.GT
AstBinop.GT -> AstBinop.LE
AstBinop.GE -> AstBinop.LT
else -> null
}
if (newop != null) expr.box.value = AstExpr.BINOP(right.type, right.left.value, newop, right.right.value)
}
is AstExpr.UNOP -> {
if (right.op == AstUnop.NOT) {
// negate twice!
expr.box.value = right.right.value
}
}
}
}
}
override fun visit(stm: AstStm.SET_LOCAL) {
super.visit(stm)
val box = stm.box
val expr = stm.expr.value
val storeLocal = stm.local.local
if (expr is AstExpr.LOCAL) {
// FIX: Assigning a value to itself
if (storeLocal == expr.local) {
storeLocal.writes.remove(stm)
storeLocal.reads.remove(expr)
box.value = AstStm.NOP("assign to itself")
return
}
}
// Do not assign and remove variables that are not going to be used!
if (storeLocal.readCount == 0 && storeLocal.writesCount == 1) {
box.value = AstStm.STM_EXPR(stm.expr.value)
storeLocal.writes.clear()
visit(box)
return
}
// Dummy cast
if (expr is AstExpr.CAST && stm.local.type == expr.from) {
val exprBox = expr.box
exprBox.value = expr.subject.value
AstAnnotateExpressions.visitExprWithStm(stm, exprBox)
return
}
}
override fun visit(stm: AstStm.IF) {
super.visit(stm)
val strue = stm.strue.value
if (strue is AstStm.IF) {
val cond = AstExpr.BINOP(AstType.BOOL, stm.cond.value, AstBinop.BAND, strue.cond.value)
stm.box.value = AstStm.IF(cond, strue.strue.value)
}
}
override fun visit(stm: AstStm.IF_ELSE) {
super.visit(stm)
val cond = stm.cond.value
val strue = stm.strue.value
val sfalse = stm.sfalse.value
if ((strue is AstStm.SET_LOCAL) && (sfalse is AstStm.SET_LOCAL) && (strue.local.local == sfalse.local.local)) {
val local = strue.local
// TERNARY OPERATOR
//println("ternary!")
local.local.writes.remove(strue)
local.local.writes.remove(sfalse)
val newset = local.setTo(AstExpr.TERNARY(cond, strue.expr.value, sfalse.expr.value, types))
stm.box.value = newset
local.local.writes.add(newset)
}
}
override fun visit(stm: AstStm.STM_EXPR) {
// Remove unnecessary cast
while (stm.expr.value is AstExpr.CAST) {
//println(stm.expr.value)
stm.expr.value = (stm.expr.value as AstExpr.CAST).subject.value
}
super.visit(stm)
if (stm.expr.value.isPure()) {
stm.box.value = AstStm.NOP("pure stm")
}
}
}
object AstAnnotateExpressions : AstVisitor() {
private var stm: AstStm? = null
fun visitExprWithStm(stm: AstStm?, box: AstExpr.Box) {
this.stm = stm
visit(box)
}
override fun visit(stm: AstStm?) {
this.stm = stm
super.visit(stm)
}
override fun visit(expr: AstExpr?) {
expr?.stm = stm
super.visit(expr)
}
}
val OPTIMIZATIONS = listOf(
{ AstCastOptimizer() }
)
val STM_OPTIMIZATIONS = listOf(
{ AstLocalTyper() }
)
fun AstBody.optimize() = this.apply {
AstAnnotateExpressions.visit(this)
AstOptimizer(this.flags).visit(this)
for (opt in OPTIMIZATIONS) opt().transformAndFinish(this)
for (opt in STM_OPTIMIZATIONS) opt().transformAndFinish(this)
invalidate()
}
fun AstStm.Box.optimize(flags: AstBodyFlags) = this.apply {
AstAnnotateExpressions.visit(this)
AstOptimizer(flags).visit(this)
for (opt in OPTIMIZATIONS) opt().transformAndFinish(this)
for (opt in STM_OPTIMIZATIONS) opt().transformAndFinish(this)
}
fun AstExpr.Box.optimize(types: AstTypes, strictfp: Boolean = true) = this.optimize(AstBodyFlags(types, strictfp))
fun AstExpr.Box.optimize(flags: AstBodyFlags) = this.apply {
AstAnnotateExpressions.visit(this)
AstOptimizer(flags).visit(this)
for (opt in OPTIMIZATIONS) opt().transformAndFinish(this)
}
fun AstStm.optimize(types: AstTypes, strictfp: Boolean = true): AstStm = this.let { this.box.optimize(AstBodyFlags(types, strictfp)).value }
fun AstStm.optimize(flags: AstBodyFlags): AstStm = this.let { this.box.optimize(flags).value }
fun AstExpr.optimize(flags: AstBodyFlags): AstExpr = this.let { this.box.optimize(flags).value }
| apache-2.0 |
intrigus/jtransc | jtransc-utils/src/com/jtransc/util/NumberExt.kt | 2 | 4408 | @file:Suppress("NOTHING_TO_INLINE")
package com.jtransc.util
inline fun Int.mask(): Int = (1 shl this) - 1
inline fun Long.mask(): Long = (1L shl this.toInt()) - 1L
fun Int.toUInt(): Long = this.toLong() and 0xFFFFFFFFL
fun Int.getBits(offset: Int, count: Int): Int = (this ushr offset) and count.mask()
fun Int.extract(offset: Int, count: Int): Int = (this ushr offset) and count.mask()
fun Int.extract8(offset: Int): Int = (this ushr offset) and 0xFF
fun Int.extract(offset: Int): Boolean = ((this ushr offset) and 1) != 0
fun Int.extractScaled(offset: Int, count: Int, scale: Int): Int {
val mask = count.mask()
return (extract(offset, count) * scale) / mask
}
fun Int.extractScaledf01(offset: Int, count: Int): Double {
val mask = count.mask().toDouble()
return extract(offset, count).toDouble() / mask
}
fun Int.extractScaledFF(offset: Int, count: Int): Int = extractScaled(offset, count, 0xFF)
fun Int.extractScaledFFDefault(offset: Int, count: Int, default: Int): Int = if (count == 0) default else extractScaled(offset, count, 0xFF)
fun Int.insert(value: Int, offset: Int, count: Int): Int {
val mask = count.mask()
val clearValue = this and (mask shl offset).inv()
return clearValue or ((value and mask) shl offset)
}
fun Int.insert8(value: Int, offset: Int): Int = insert(value, offset, 8)
fun Int.insert(value: Boolean, offset: Int): Int = this.insert(if (value) 1 else 0, offset, 1)
fun Int.insertScaled(value: Int, offset: Int, count: Int, scale: Int): Int {
val mask = count.mask()
return insert((value * mask) / scale, offset, count)
}
fun Int.insertScaledFF(value: Int, offset: Int, count: Int): Int = if (count == 0) this else this.insertScaled(value, offset, count, 0xFF)
fun Long.nextAlignedTo(align: Long) = if (this % align == 0L) {
this
} else {
(((this / align) + 1) * align)
}
fun Int.clamp(min: Int, max: Int): Int = if (this < min) min else if (this > max) max else this
fun Double.clamp(min: Double, max: Double): Double = if (this < min) min else if (this > max) max else this
fun Long.clamp(min: Long, max: Long): Long = if (this < min) min else if (this > max) max else this
fun Long.toIntSafe(): Int {
if (this.toInt().toLong() != this) throw IllegalArgumentException("Long doesn't fit Integer")
return this.toInt()
}
fun Long.toIntClamp(min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE): Int {
if (this < min) return min
if (this > max) return max
return this.toInt()
}
fun Long.toUintClamp(min: Int = 0, max: Int = Int.MAX_VALUE) = this.toIntClamp(0, Int.MAX_VALUE)
fun String.toDoubleOrNull2(): Double? = try {
this.toDouble()
} catch (e: NumberFormatException) {
null
}
fun String.toLongOrNull2(): Long? = try {
this.toLong()
} catch (e: NumberFormatException) {
null
}
fun String.toIntOrNull2(): Int? = try {
this.toInt()
} catch (e: NumberFormatException) {
null
}
fun String.toNumber(): Number = this.toIntOrNull2() as Number? ?: this.toLongOrNull2() as Number? ?: this.toDoubleOrNull2() as Number? ?: 0
fun Byte.toUnsigned() = this.toInt() and 0xFF
fun Int.toUnsigned() = this.toLong() and 0xFFFFFFFFL
fun Int.signExtend(bits: Int) = (this shl (32 - bits)) shr (32 - bits)
fun Long.signExtend(bits: Int) = (this shl (64 - bits)) shr (64 - bits)
infix fun Int.umod(other: Int): Int {
val remainder = this % other
return when {
remainder < 0 -> remainder + other
else -> remainder
}
}
fun Double.convertRange(srcMin: Double, srcMax: Double, dstMin: Double, dstMax: Double): Double {
val ratio = (this - srcMin) / (srcMax - srcMin)
return (dstMin + (dstMax - dstMin) * ratio)
}
fun Long.convertRange(srcMin: Long, srcMax: Long, dstMin: Long, dstMax: Long): Long {
val ratio = (this - srcMin).toDouble() / (srcMax - srcMin).toDouble()
return (dstMin + (dstMax - dstMin) * ratio).toLong()
}
object Bits {
@JvmStatic
fun mask(count: Int): Int = (1 shl count) - 1
@JvmStatic
fun extract(data: Int, offset: Int, length: Int): Int {
return (data ushr offset) and mask(length)
}
@JvmStatic
fun extractBool(data: Int, offset: Int): Boolean = extract(data, offset, 1) != 0
}
fun Int.extractBool(offset: Int): Boolean = Bits.extractBool(this, offset)
fun Int.hasBitmask(mask: Int): Boolean = (this and mask) == mask
fun Int.withBool(offset: Int): Int {
val v = (1 shl offset)
return (this and v.inv()) or (v)
}
fun Int.withoutBool(offset: Int): Int {
val v = (1 shl offset)
return (this and v.inv())
}
| apache-2.0 |
deviant-studio/energy-meter-scanner | app/src/main/java/ds/meterscanner/mvvm/view/ChartsActivity.kt | 1 | 4380 | package ds.meterscanner.mvvm.view
import android.app.Activity
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import ds.bindingtools.withBindable
import ds.meterscanner.R
import ds.meterscanner.mvvm.BindableActivity
import ds.meterscanner.mvvm.ChartsView
import ds.meterscanner.mvvm.viewmodel.ChartsViewModel
import ds.meterscanner.mvvm.viewmodel.Period
import ds.meterscanner.util.FileTools
import kotlinx.android.synthetic.main.activity_charts.*
import kotlinx.android.synthetic.main.toolbar.*
import lecho.lib.hellocharts.gesture.ZoomType
import lecho.lib.hellocharts.model.ColumnChartData
import lecho.lib.hellocharts.model.Viewport
import lecho.lib.hellocharts.util.ChartUtils
class ChartsActivity : BindableActivity<ChartsViewModel>(), ChartsView {
override fun provideViewModel(): ChartsViewModel = defaultViewModelOf()
override fun getLayoutId(): Int = R.layout.activity_charts
override fun bindView() {
super.bindView()
toolbar.title = getString(R.string.charts)
columnsChart.isScrollEnabled = false
columnsChart.isZoomEnabled = false
linesChart.isScrollEnabled = false
linesChart.isZoomEnabled = false
previewChart.setViewportChangeListener(ViewportListener(columnsChart, linesChart))
radioGroup.setOnCheckedChangeListener { _, checkedId -> viewModel.onCheckedChanged(checkedId) }
withBindable(viewModel) {
bind(::linesData, {
linesChart.lineChartData = it
val v = Viewport(linesChart.maximumViewport.left, 30f, linesChart.maximumViewport.right, -30f)
linesChart.maximumViewport = v
})
bind(::columnsData, columnsChart::setColumnChartData)
bind(::columnsData, {
val previewData = ColumnChartData(it)
previewData
.columns
.flatMap { it.values }
.forEach { it.color = ChartUtils.DEFAULT_DARKEN_COLOR }
previewData.axisYLeft = null
previewData.axisXBottom = null
previewChart.columnChartData = previewData
val tempViewport = Viewport(columnsChart.maximumViewport)
val visibleItems = 20
tempViewport.left = tempViewport.right - visibleItems
previewChart.currentViewport = tempViewport
previewChart.zoomType = ZoomType.HORIZONTAL
})
bind(this::checkedButtonId, radioGroup::check, radioGroup::getCheckedRadioButtonId)
bind(::showProgress, { radioGroup.isEnabled = !it })
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.charts, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(when (viewModel.period) {
Period.ALL -> R.id.action_period_all
Period.YEAR -> R.id.action_period_year
Period.LAST_SEASON -> R.id.action_period_season
}).isChecked = true
menu.findItem(R.id.action_correction).isChecked = viewModel.positiveCorrection
menu.findItem(R.id.action_show_temp).isChecked = viewModel.tempVisible
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.isCheckable)
item.isChecked = !item.isChecked
when (item.itemId) {
R.id.action_correction -> viewModel.toggleCorection(item.isChecked)
R.id.action_show_temp -> viewModel.toggleTemperature(item.isChecked)
R.id.action_period_all -> viewModel.period = Period.ALL
R.id.action_period_year -> viewModel.period = Period.YEAR
R.id.action_period_season -> viewModel.period = Period.LAST_SEASON
R.id.action_export_csv -> FileTools.chooseDir(this, FileTools.CSV_FILE_NAME)
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Requests.SAVE_FILE && resultCode == Activity.RESULT_OK) {
viewModel.onDirectoryChoosen(contentResolver, data!!.data)
}
}
}
| mit |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/mirror/Constants.kt | 2 | 104 | package com.github.kerubistan.kerub.planner.steps.storage.lvm.mirror
const val maxMirrors = 4.toByte()
| apache-2.0 |
Duke1/UnrealMedia | UnrealMedia/app/src/main/java/com/qfleng/um/util/Extension.kt | 1 | 3761 | package com.qfleng.um.util
import android.content.Context
import android.text.TextUtils
import com.google.gson.*
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
import java.lang.reflect.Type
class StringConverter : JsonSerializer<String>, JsonDeserializer<String> {
override fun serialize(src: String?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
return if (src == null) {
JsonPrimitive("")
} else {
JsonPrimitive(src.toString())
}
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): String {
return json
.asJsonPrimitive
.asString
}
}
class StringAdapter : TypeAdapter<String>() {
@Throws(IOException::class)
override fun read(reader: JsonReader): String {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
return ""
}
return reader.nextString()
}
@Throws(IOException::class)
override fun write(writer: JsonWriter, value: String?) {
if (value == null) {
writer.jsonValue("\"\"")
return
}
writer.value(value)
}
}
/**
* Gson扩展
*/
fun <T> Context.objectFrom(tClass: Class<T>, str: String): T? {
if (TextUtils.isEmpty(str)) return null
return gsonObjectFrom(tClass, str)
}
fun <T> gsonObjectFrom(tClass: Class<T>, str: String): T? {
if (TextUtils.isEmpty(str)) return null
try {
return GsonBuilder()
.serializeNulls()
.registerTypeAdapter(String::class.java, StringConverter())
.create()
.fromJson(str, tClass)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
fun Any?.toJsonString(fast: Boolean = false): String {
if (null == this) return ""
try {
return if (fast) {
GsonBuilder()
.addSerializationExclusionStrategy(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes): Boolean {
return null != f.getAnnotation(ObjectFieldExclude::class.java)
}
override fun shouldSkipClass(clazz: Class<*>): Boolean {
return false
}
})
.create().toJson(this)
} else {
GsonBuilder()
.serializeNulls()
.addSerializationExclusionStrategy(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes): Boolean {
return null != f.getAnnotation(ObjectFieldExclude::class.java)
}
override fun shouldSkipClass(clazz: Class<*>): Boolean {
return false
}
})
.registerTypeAdapter(String::class.java, StringAdapter())
// .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
.create()
.toJson(this)
}
} catch (e: Exception) {
e.printStackTrace()
return ""
}
}
/**
* Created by Duke .
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
annotation class ObjectFieldExclude
| mit |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/database/SuraTimingDatabaseHandler.kt | 2 | 3094 | package com.quran.labs.androidquran.database
import android.database.Cursor
import android.database.DefaultDatabaseErrorHandler
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabaseCorruptException
import timber.log.Timber
import java.io.File
import java.lang.Exception
import java.util.HashMap
class SuraTimingDatabaseHandler private constructor(path: String) {
private var database: SQLiteDatabase? = null
object TimingsTable {
const val TABLE_NAME = "timings"
const val COL_SURA = "sura"
const val COL_AYAH = "ayah"
const val COL_TIME = "time"
}
object PropertiesTable {
const val TABLE_NAME = "properties"
const val COL_PROPERTY = "property"
const val COL_VALUE = "value"
}
companion object {
private val databaseMap: MutableMap<String, SuraTimingDatabaseHandler> = HashMap()
@JvmStatic
@Synchronized
fun getDatabaseHandler(path: String): SuraTimingDatabaseHandler {
var handler = databaseMap[path]
if (handler == null) {
handler = SuraTimingDatabaseHandler(path)
databaseMap[path] = handler
}
return handler
}
@Synchronized
fun clearDatabaseHandlerIfExists(databasePath: String) {
try {
val handler = databaseMap.remove(databasePath)
if (handler != null) {
handler.database?.close()
databaseMap.remove(databasePath)
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
init {
Timber.d("opening gapless data file, %s", path)
database = try {
SQLiteDatabase.openDatabase(
path, null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS, DefaultDatabaseErrorHandler()
)
} catch (sce: SQLiteDatabaseCorruptException) {
Timber.d("database corrupted: %s", path)
null
} catch (se: SQLException) {
Timber.d("database at $path ${if (File(path).exists()) "exists " else "doesn 't exist"}")
Timber.e(se)
null
}
}
private fun validDatabase(): Boolean = database?.isOpen ?: false
fun getAyahTimings(sura: Int): Cursor? {
if (!validDatabase()) return null
return try {
database?.query(
TimingsTable.TABLE_NAME, arrayOf(
TimingsTable.COL_SURA,
TimingsTable.COL_AYAH, TimingsTable.COL_TIME
),
TimingsTable.COL_SURA + "=" + sura,
null, null, null, TimingsTable.COL_AYAH + " ASC"
)
} catch (e: Exception) {
null
}
}
fun getVersion(): Int {
if (!validDatabase()) {
return -1
}
var cursor: Cursor? = null
return try {
cursor = database?.query(
PropertiesTable.TABLE_NAME, arrayOf(PropertiesTable.COL_VALUE),
PropertiesTable.COL_PROPERTY + "= 'version'", null, null, null, null
)
if (cursor != null && cursor.moveToFirst()) {
cursor.getInt(0)
} else {
1
}
} catch (e: Exception) {
1
} finally {
DatabaseUtils.closeCursor(cursor)
}
}
}
| gpl-3.0 |
line/armeria | examples/context-propagation/kotlin/src/main/kotlin/example/armeria/contextpropagation/kotlin/Main.kt | 3 | 1558 | /*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you 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 example.armeria.contextpropagation.kotlin
import com.linecorp.armeria.client.WebClient
import com.linecorp.armeria.common.HttpResponse
import com.linecorp.armeria.common.HttpStatus
import com.linecorp.armeria.server.Server
fun main() {
val backend = Server.builder()
.service("/square/{num}") { ctx, _ ->
val num = ctx.pathParam("num")?.toLong()
if (num != null) {
HttpResponse.of((num * num).toString())
} else {
HttpResponse.of(HttpStatus.BAD_REQUEST)
}
}
.http(8081)
.build()
val backendClient = WebClient.of("http://localhost:8081")
val frontend = Server.builder()
.http(8080)
.serviceUnder("/", MainService(backendClient))
.build()
backend.closeOnJvmShutdown()
frontend.closeOnJvmShutdown()
backend.start().join()
frontend.start().join()
}
| apache-2.0 |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/SingleAction.kt | 1 | 11330 | /*
* Copyright (C) 2017-2019 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.action
import android.os.Parcel
import android.os.Parcelable
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import jp.hazuki.yuzubrowser.legacy.action.item.*
import jp.hazuki.yuzubrowser.legacy.action.item.startactivity.StartActivitySingleAction
import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity
import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo
import java.io.IOException
open class SingleAction : Parcelable {
val id: Int
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
}
protected constructor(source: Parcel) {
this.id = source.readInt()
}
//for extended class
protected constructor(id: Int) {
this.id = id
//if(id < 0) throw new IllegalArgumentException();
}
//node can be null
@Throws(IOException::class)
private constructor(id: Int, reader: JsonReader?) : this(id) {
reader?.skipValue()
}
@Throws(IOException::class)
open fun writeIdAndData(writer: JsonWriter) {
writer.value(id)
writer.nullValue()
}
open fun showMainPreference(context: ActionActivity): StartActivityInfo? {
return null
}
open fun showSubPreference(context: ActionActivity): StartActivityInfo? {
return null
}
open fun toString(nameArray: ActionNameArray): String? {
for ((i, value) in nameArray.actionValues.withIndex()) {
if (value == id)
return nameArray.actionList[i]
}
return null
}
companion object {
const val GO_BACK = 1000
const val GO_FORWARD = 1001
const val WEB_RELOAD_STOP = 1005
const val WEB_RELOAD = 1006
const val WEB_STOP = 1007
const val GO_HOME = 1020
const val ZOOM_IN = 1205
const val ZOOM_OUT = 1206
const val PAGE_UP = 1207
const val PAGE_DOWN = 1208
const val PAGE_TOP = 1209
const val PAGE_BOTTOM = 1210
const val PAGE_SCROLL = 1215
const val PAGE_FAST_SCROLL = 1216
const val PAGE_AUTO_SCROLL = 1217
const val FOCUS_UP = 1220
const val FOCUS_DOWN = 1221
const val FOCUS_LEFT = 1222
const val FOCUS_RIGHT = 1223
const val FOCUS_CLICK = 1224
const val TOGGLE_JS = 2000
const val TOGGLE_IMAGE = 2001
const val TOGGLE_COOKIE = 2002
const val TOGGLE_USERJS = 2200
const val TOGGLE_NAV_LOCK = 2300
const val PAGE_INFO = 5000
const val COPY_URL = 5001
const val COPY_TITLE = 5002
const val COPY_TITLE_URL = 5003
const val TAB_HISTORY = 5010
const val MOUSE_POINTER = 5015
const val FIND_ON_PAGE = 5020
const val SAVE_SCREENSHOT = 5030
const val SHARE_SCREENSHOT = 5031
const val SAVE_PAGE = 5035
const val OPEN_URL = 5200
const val TRANSLATE_PAGE = 5300
const val NEW_TAB = 10000
const val CLOSE_TAB = 10001
const val CLOSE_ALL = 10002
const val CLOSE_OTHERS = 10003
const val CLOSE_AUTO_SELECT = 10100
const val LEFT_TAB = 10005
const val RIGHT_TAB = 10006
const val SWAP_LEFT_TAB = 10007
const val SWAP_RIGHT_TAB = 10008
const val TAB_LIST = 10010
const val CLOSE_ALL_LEFT = 10015
const val CLOSE_ALL_RIGHT = 10016
const val RESTORE_TAB = 10020
const val REPLICATE_TAB = 10021
const val SHOW_SEARCHBOX = 35000
const val PASTE_SEARCHBOX = 35001
const val PASTE_GO = 35002
const val SHOW_BOOKMARK = 35010
const val SHOW_HISTORY = 35011
const val SHOW_DOWNLOADS = 35012
const val SHOW_SETTINGS = 35013
const val OPEN_SPEED_DIAL = 35014
const val ADD_BOOKMARK = 35020
const val ADD_SPEED_DIAL = 35021
const val ADD_PATTERN = 35022
const val ADD_TO_HOME = 35023
const val SUB_GESTURE = 35031
const val CLEAR_DATA = 35300
const val SHOW_PROXY_SETTING = 35301
const val ORIENTATION_SETTING = 35302
const val OPEN_LINK_SETTING = 35304
const val USERAGENT_SETTING = 35305
const val TEXTSIZE_SETTING = 35306
const val USERJS_SETTING = 35307
const val WEB_ENCODE_SETTING = 35308
const val DEFALUT_USERAGENT_SETTING = 35309
const val RENDER_ALL_SETTING = 35400
const val RENDER_SETTING = 35401
const val TOGGLE_VISIBLE_TAB = 38000
const val TOGGLE_VISIBLE_URL = 38001
const val TOGGLE_VISIBLE_PROGRESS = 38002
const val TOGGLE_VISIBLE_CUSTOM = 38003
const val TOGGLE_WEB_TITLEBAR = 38010
const val TOGGLE_WEB_GESTURE = 38100
const val TOGGLE_FLICK = 38101
const val TOGGLE_QUICK_CONTROL = 38102
const val TOGGLE_MULTI_FINGER_GESTURE = 38103
const val TOGGLE_AD_BLOCK = 38200
const val OPEN_BLACK_LIST = 38210
const val OPEN_WHITE_LIST = 38211
const val OPEN_WHITE_PATE_LIST = 38212
const val ADD_WHITE_LIST_PAGE = 38220
const val SHARE_WEB = 50000
const val OPEN_OTHER = 50001
const val START_ACTIVITY = 50005
const val TOGGLE_FULL_SCREEN = 50100
const val OPEN_OPTIONS_MENU = 50120
const val CUSTOM_MENU = 80000
const val FINISH = 90001
const val MINIMIZE = 90005
const val CUSTOM_ACTION = 100000
const val VIBRATION = 100100
const val TOAST = 100101
const val PRIVATE = 100110
const val VIEW_SOURCE = 101000
const val PRINT = 101010
const val TAB_PINNING = 101020
const val ALL_ACTION = 101030
const val READER_MODE = 101040
const val READ_IT_LATER = 101050
const val READ_IT_LATER_LIST = 101051
const val WEB_THEME = 101060
const val LPRESS_OPEN = -10
const val LPRESS_OPEN_NEW = -11
const val LPRESS_OPEN_BG = -12
const val LPRESS_OPEN_NEW_RIGHT = -13
const val LPRESS_OPEN_BG_RIGHT = -14
const val LPRESS_SHARE = -50
const val LPRESS_OPEN_OTHERS = -51
const val LPRESS_COPY_URL = -52
const val LPRESS_SAVE_PAGE_AS = -53
const val LPRESS_SAVE_PAGE = -54
const val LPRESS_OPEN_IMAGE = -110
const val LPRESS_OPEN_IMAGE_NEW = -111
const val LPRESS_OPEN_IMAGE_BG = -112
const val LPRESS_OPEN_IMAGE_NEW_RIGHT = -113
const val LPRESS_OPEN_IMAGE_BG_RIGHT = -114
const val LPRESS_SHARE_IMAGE_URL = -150
const val LPRESS_OPEN_IMAGE_OTHERS = -151
const val LPRESS_COPY_IMAGE_URL = -152
const val LPRESS_SAVE_IMAGE_AS = -153
const val LPRESS_GOOGLE_IMAGE_SEARCH = -154
const val LPRESS_IMAGE_RES_BLOCK = -155
const val LPRESS_PATTERN_MATCH = -156
const val LPRESS_COPY_LINK_TEXT = -157
const val LPRESS_SHARE_IMAGE = -158
const val LPRESS_SAVE_IMAGE = -159
const val LPRESS_ADD_BLACK_LIST = -160
const val LPRESS_ADD_IMAGE_BLACK_LIST = -161
const val LPRESS_ADD_WHITE_LIST = -162
const val LPRESS_ADD_IMAGE_WHITE_LIST = -163
@JvmStatic
fun makeInstance(id: Int): SingleAction {
try {
return makeInstance(id, null)
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
}
throw IllegalStateException()
}
@JvmField
val CREATOR: Parcelable.Creator<SingleAction> = object : Parcelable.Creator<SingleAction> {
override fun createFromParcel(source: Parcel): SingleAction {
return SingleAction(source)
}
override fun newArray(size: Int): Array<SingleAction?> {
return arrayOfNulls(size)
}
}
@Throws(IOException::class)
fun makeInstance(id: Int, parser: JsonReader?): SingleAction {
return when (id) {
GO_BACK -> GoBackSingleAction(id, parser)
PAGE_SCROLL -> WebScrollSingleAction(id, parser)
PAGE_AUTO_SCROLL -> AutoPageScrollAction(id, parser)
MOUSE_POINTER -> MousePointerSingleAction(id, parser)
FIND_ON_PAGE -> FindOnPageAction(id, parser)
SAVE_SCREENSHOT -> SaveScreenshotSingleAction(id, parser)
SHARE_SCREENSHOT -> ShareScreenshotSingleAction(id, parser)
OPEN_URL -> OpenUrlSingleAction(id, parser)
TRANSLATE_PAGE -> TranslatePageSingleAction(id, parser)
CLOSE_TAB -> CloseTabSingleAction(id, parser)
LEFT_TAB, RIGHT_TAB -> LeftRightTabSingleAction(id, parser)
TAB_LIST -> TabListSingleAction(id, parser)
SHOW_SEARCHBOX -> ShowSearchBoxAction(id, parser)
PASTE_SEARCHBOX -> PasteSearchBoxAction(id, parser)
PASTE_GO -> PasteGoSingleAction(id, parser)
TOGGLE_AD_BLOCK, PRIVATE -> WithToastAction(id, parser)
START_ACTIVITY -> StartActivitySingleAction(id, parser)
OPEN_OPTIONS_MENU -> OpenOptionsMenuAction(id, parser)
CUSTOM_MENU -> CustomMenuSingleAction(id, parser)
FINISH -> FinishSingleAction(id, parser)
CUSTOM_ACTION -> CustomSingleAction(id, parser)
VIBRATION -> VibrationSingleAction(id, parser)
TOAST -> ToastAction(id, parser)
CLOSE_AUTO_SELECT -> CloseAutoSelectAction(id, parser)
else -> SingleAction(id, parser)
}
}
fun checkSubPreference(id: Int): Boolean {
return when (id) {
GO_BACK, PAGE_SCROLL,
PAGE_AUTO_SCROLL,
MOUSE_POINTER,
FIND_ON_PAGE,
SAVE_SCREENSHOT,
SHARE_SCREENSHOT,
OPEN_URL,
TRANSLATE_PAGE,
CLOSE_TAB,
LEFT_TAB,
RIGHT_TAB,
TAB_LIST,
SHOW_SEARCHBOX,
PASTE_SEARCHBOX,
PASTE_GO,
TOGGLE_AD_BLOCK,
START_ACTIVITY,
OPEN_OPTIONS_MENU,
CUSTOM_MENU,
FINISH,
CUSTOM_ACTION,
VIBRATION,
TOAST,
PRIVATE,
CLOSE_AUTO_SELECT -> true
else -> false
}
}
}
}
| apache-2.0 |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKMinecraftProfileProviderImpl.kt | 1 | 4145 | package com.rpkit.players.bukkit.profile
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.database.table.RPKMinecraftProfileLinkRequestTable
import com.rpkit.players.bukkit.database.table.RPKMinecraftProfileTable
import com.rpkit.players.bukkit.database.table.RPKMinecraftProfileTokenTable
import com.rpkit.players.bukkit.event.minecraftprofile.RPKBukkitMinecraftProfileCreateEvent
import com.rpkit.players.bukkit.event.minecraftprofile.RPKBukkitMinecraftProfileDeleteEvent
import com.rpkit.players.bukkit.event.minecraftprofile.RPKBukkitMinecraftProfileUpdateEvent
import org.bukkit.OfflinePlayer
class RPKMinecraftProfileProviderImpl(private val plugin: RPKPlayersBukkit): RPKMinecraftProfileProvider {
override fun getMinecraftProfile(id: Int): RPKMinecraftProfile? {
return plugin.core.database.getTable(RPKMinecraftProfileTable::class)[id]
}
override fun getMinecraftProfile(player: OfflinePlayer): RPKMinecraftProfile? {
return plugin.core.database.getTable(RPKMinecraftProfileTable::class).get(player)
}
override fun getMinecraftProfiles(profile: RPKProfile): List<RPKMinecraftProfile> {
return plugin.core.database.getTable(RPKMinecraftProfileTable::class).get(profile)
}
override fun addMinecraftProfile(profile: RPKMinecraftProfile) {
val event = RPKBukkitMinecraftProfileCreateEvent(profile)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
plugin.core.database.getTable(RPKMinecraftProfileTable::class).insert(event.minecraftProfile)
}
override fun updateMinecraftProfile(profile: RPKMinecraftProfile) {
val event = RPKBukkitMinecraftProfileUpdateEvent(profile)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
plugin.core.database.getTable(RPKMinecraftProfileTable::class).update(event.minecraftProfile)
}
override fun removeMinecraftProfile(profile: RPKMinecraftProfile) {
val event = RPKBukkitMinecraftProfileDeleteEvent(profile)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
plugin.core.database.getTable(RPKMinecraftProfileTable::class).delete(event.minecraftProfile)
}
override fun getMinecraftProfileToken(id: Int): RPKMinecraftProfileToken? {
return plugin.core.database.getTable(RPKMinecraftProfileTokenTable::class)[id]
}
override fun getMinecraftProfileToken(profile: RPKMinecraftProfile): RPKMinecraftProfileToken? {
return plugin.core.database.getTable(RPKMinecraftProfileTokenTable::class).get(profile)
}
override fun addMinecraftProfileToken(token: RPKMinecraftProfileToken) {
plugin.core.database.getTable(RPKMinecraftProfileTokenTable::class).insert(token)
}
override fun updateMinecraftProfileToken(token: RPKMinecraftProfileToken) {
plugin.core.database.getTable(RPKMinecraftProfileTokenTable::class).update(token)
}
override fun removeMinecraftProfileToken(token: RPKMinecraftProfileToken) {
plugin.core.database.getTable(RPKMinecraftProfileTokenTable::class).delete(token)
}
override fun getMinecraftProfileLinkRequests(minecraftProfile: RPKMinecraftProfile): List<RPKMinecraftProfileLinkRequest> {
return plugin.core.database.getTable(RPKMinecraftProfileLinkRequestTable::class).get(minecraftProfile)
}
override fun addMinecraftProfileLinkRequest(minecraftProfileLinkRequest: RPKMinecraftProfileLinkRequest) {
plugin.core.database.getTable(RPKMinecraftProfileLinkRequestTable::class).insert(minecraftProfileLinkRequest)
}
override fun removeMinecraftProfileLinkRequest(minecraftProfileLinkRequest: RPKMinecraftProfileLinkRequest) {
plugin.core.database.getTable(RPKMinecraftProfileLinkRequestTable::class).delete(minecraftProfileLinkRequest)
}
override fun updateMinecraftProfileLinkRequest(minecraftProfileLinkRequest: RPKMinecraftProfileLinkRequest) {
plugin.core.database.getTable(RPKMinecraftProfileLinkRequestTable::class).update(minecraftProfileLinkRequest)
}
} | apache-2.0 |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/functionInReturnedObjectWithReturnPrimitives/resolver/QueryResolver.kt | 1 | 529 | package com.foo.graphql.functionInReturnedObjectWithReturnPrimitives.resolver
import com.foo.graphql.functionInReturnedObjectWithReturnPrimitives.DataRepository
import com.foo.graphql.functionInReturnedObjectWithReturnPrimitives.type.Flower
import graphql.kickstart.tools.GraphQLQueryResolver
import org.springframework.stereotype.Component
@Component
open class QueryResolver(
private val dataRepo: DataRepository
) : GraphQLQueryResolver {
fun flowers(): Flower{
return dataRepo.findFlower()
}
}
| lgpl-3.0 |
fuzhouch/qbranch | core/src/main/kotlin/net/dummydigit/qbranch/protocols/CompactBinaryReader.kt | 1 | 5478 | // Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.protocols
import net.dummydigit.qbranch.*
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.charset.Charset
import net.dummydigit.qbranch.exceptions.EndOfStreamException
import net.dummydigit.qbranch.exceptions.UnsupportedVersionException
import net.dummydigit.qbranch.utils.VariableLength
import net.dummydigit.qbranch.utils.ZigZag
/**
* Reader to process CompactBinary protocols (v1 only)
*/
class CompactBinaryReader(inputStream : InputStream, version : Int, charset: Charset) : TaggedProtocolReader {
private val input = inputStream
private val defaultStringCharset = charset
constructor(inputStream : InputStream) : this(inputStream, 1, Charsets.UTF_8)
constructor(inputStream : InputStream, version : Int) : this(inputStream, version, Charsets.UTF_8)
init {
if (version != 1) {
throw UnsupportedVersionException("protocol=CompactBinary:version=$version")
}
}
override fun readBool() : Boolean = input.read() == 0
override fun readInt8() : Byte = input.read().toByte()
override fun readUInt8() : UnsignedByte = UnsignedByte(input.read().toShort())
override fun readInt16() : Short = ZigZag.unsignedToSigned16(readUInt16())
override fun readUInt16(): UnsignedShort = VariableLength.decodeVarUInt16(input)
override fun readUInt32(): UnsignedInt = VariableLength.decodeVarUInt32(input)
override fun readInt32(): Int = ZigZag.unsignedToSigned32(readUInt32())
override fun readInt64(): Long = ZigZag.unsignedToSigned64(readUInt64())
override fun readUInt64(): UnsignedLong = VariableLength.decodeVarUInt64(input)
override fun readByteString(): ByteString {
val rawBytes = readRawStringBytes(1) ?: return ByteString("", defaultStringCharset)
return ByteString(rawBytes, defaultStringCharset)
}
override fun readUTF16LEString(): String {
// Following C#/Windows convention, we assume
// we read UTF16 bytes. However, it may not be portable
// on non-Windows platforms.
val rawBytes = readRawStringBytes(2) ?: return ""
return String(rawBytes, Charsets.UTF_16LE)
}
override fun readFloat(): Float {
val floatAsBytes = ByteArray(4)
val bytesRead = input.read(floatAsBytes)
if (bytesRead != 4) {
throw EndOfStreamException(4, bytesRead)
}
floatAsBytes.reverse()
return ByteBuffer.wrap(floatAsBytes).float
}
override fun readDouble(): Double {
val doubleAsBytes = ByteArray(8)
val bytesRead = input.read(doubleAsBytes)
if (bytesRead != 8) {
throw EndOfStreamException(8, bytesRead)
}
doubleAsBytes.reverse()
return ByteBuffer.wrap(doubleAsBytes).double
}
override fun readContainerHeader() : ContainerHeaderInfo {
return CompactBinaryFieldInfo.decodeContainerHeaderV1(input)
}
override fun readKvpContainerHeader() : KvpContainerHeaderInfo {
return CompactBinaryFieldInfo.decodeKvpContainerHeaderV1(input)
}
override fun skipField(dataType : BondDataType) {
when (dataType) {
BondDataType.BT_BOOL -> input.read()
BondDataType.BT_UINT8 -> input.read()
BondDataType.BT_UINT16 -> readUInt16()
BondDataType.BT_UINT32 -> readUInt32()
BondDataType.BT_UINT64 -> readUInt64()
BondDataType.BT_FLOAT -> readFloat()
BondDataType.BT_DOUBLE -> readDouble()
BondDataType.BT_STRING -> readByteString()
BondDataType.BT_INT8 -> input.read()
BondDataType.BT_INT16 -> readInt16()
BondDataType.BT_INT32 -> readInt32()
BondDataType.BT_INT64 -> readInt64()
BondDataType.BT_WSTRING -> readUTF16LEString()
// TODO Implement container type in next version.
BondDataType.BT_STRUCT -> skipStruct()
BondDataType.BT_STOP_BASE -> {}
BondDataType.BT_LIST -> skipContainer()
BondDataType.BT_SET -> skipContainer()
BondDataType.BT_MAP -> skipMap()
else -> throw IllegalStateException("skip=$dataType")
}
}
private fun skipMap() {
val header = readKvpContainerHeader()
for (i in 0 until header.kvpCount) {
skipField(header.keyType)
skipField(header.valueType)
}
}
private fun skipContainer() {
val header = readContainerHeader()
for(i in 0 until header.elementCount) {
skipField(header.elementType)
}
}
private fun skipStruct() {
var fieldInfo = parseNextField()
while (fieldInfo.typeId != BondDataType.BT_STOP) {
skipField(fieldInfo.typeId)
fieldInfo = parseNextField()
}
}
private fun readRawStringBytes(charLen : Int) : ByteArray? {
val stringLength = readUInt32().value.toInt()
if (stringLength == 0) {
return null
}
val rawBytes = ByteArray(stringLength * charLen)
val bytesRead = input.read(rawBytes)
if (bytesRead != stringLength * charLen) {
throw EndOfStreamException(stringLength * charLen, bytesRead)
}
return rawBytes
}
override fun parseNextField() = CompactBinaryFieldInfo(input)
} | mit |
michalkowol/kotlin-template | src/main/kotlin/com/michalkowol/cars/module.kt | 1 | 377 | package com.michalkowol.cars
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.singleton
val carsModule = Kodein.Module("carsModule") {
bind<CarsRepository>() with singleton { CarsRepository(instance()) }
bind<CarsController>() with singleton { CarsController(instance(), instance()) }
}
| isc |
proxer/ProxerLibAndroid | library/src/test/kotlin/me/proxer/library/internal/adapter/UnitAdapterTest.kt | 2 | 693 | package me.proxer.library.internal.adapter
import com.squareup.moshi.JsonDataException
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldThrow
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class UnitAdapterTest {
private val adapter = UnitAdapter()
@Test
fun testFromJsonNull() {
adapter.fromJson("null").shouldBeNull()
}
@Test
fun testFromJsonInvalid() {
invoking { adapter.fromJson("value") } shouldThrow JsonDataException::class
}
@Test
fun testToJson() {
adapter.toJson(null) shouldBeEqualTo "null"
}
}
| gpl-3.0 |
javiyt/nftweets | app/src/test/java/yt/javi/nftweets/infrastructure/repositories/inmemory/TeamInMemoryRepositoryTest.kt | 1 | 1874 | package yt.javi.nftweets.infrastructure.repositories.inmemory
import org.junit.Before
import org.junit.Test
import yt.javi.nfltweets.domain.model.team.Team
import yt.javi.nftweets.R.drawable.*
import yt.javi.nftweets.domain.model.Conference.AFC
import yt.javi.nftweets.domain.model.Conference.NFC
import yt.javi.nftweets.domain.model.Division.*
class TeamInMemoryRepositoryTest {
companion object {
val teamsList = listOf(
Team("Bills", "Buffalo", AFC, East, ic_buffalo_bills_logo, "buffalobills", "GoBills"),
Team("Ravens", "Baltimore", AFC, North, ic_baltimore_ravens_logo, "Ravens", "RavensFlock"),
Team("Texans", "Houston", AFC, South, ic_houston_texans_logo, "HoustonTexans", "WeAreTexans"),
Team("Broncos", "Denver", AFC, West, ic_denver_broncos_logo, "Broncos", "Broncos"),
Team("Cowboys", "Dallas", NFC, East, ic_dallas_cowboys, "dallascowboys", "DallasCowboys"),
Team("Bears", "Chicago", NFC, North, ic_chicago_bears_logo, "ChicagoBears", "FeedDaBears"),
Team("Falcons", "Atlanta", NFC, South, ic_atlanta_falcons_logo, "AtlantaFalcons", "RiseUp"),
Team("Cardinals", "Arizona", NFC, West, ic_arizona_cardinals_logo, "AZCardinals", "BeRedSeeRed")
) }
private lateinit var teamRepository: TeamInMemoryRepository
@Before
fun setUp() {
teamRepository = TeamInMemoryRepository(teamsList)
}
@Test
fun shouldReturnTeamsBasedOnGivenConference() {
assert(teamRepository.findTeams(AFC, null).size == 4)
}
@Test
fun shouldReturnAnExistingTeam() {
assert(teamRepository.findTeam("Bills") == teamsList[0])
}
@Test(expected = NoSuchElementException::class)
fun shouldNotReturnAnExistingTeam() {
teamRepository.findTeam("NonExisting")
}
} | apache-2.0 |
rostyslav-y/android-clean-architecture-boilerplate | remote/src/test/java/org/buffer/android/boilerplate/remote/BufferooRemoteImplTest.kt | 1 | 1895 | package org.buffer.android.boilerplate.remote
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.Single
import org.buffer.android.boilerplate.data.model.BufferooEntity
import org.buffer.android.boilerplate.remote.mapper.BufferooEntityMapper
import org.buffer.android.boilerplate.remote.test.factory.BufferooFactory
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class BufferooRemoteImplTest {
private lateinit var entityMapper: BufferooEntityMapper
private lateinit var bufferooService: BufferooService
private lateinit var bufferooRemoteImpl: BufferooRemoteImpl
@Before
fun setup() {
entityMapper = mock()
bufferooService = mock()
bufferooRemoteImpl = BufferooRemoteImpl(bufferooService, entityMapper)
}
//<editor-fold desc="Get Bufferoos">
@Test
fun getBufferoosCompletes() {
stubBufferooServiceGetBufferoos(Single.just(BufferooFactory.makeBufferooResponse()))
val testObserver = bufferooRemoteImpl.getBufferoos().test()
testObserver.assertComplete()
}
@Test
fun getBufferoosReturnsData() {
val bufferooResponse = BufferooFactory.makeBufferooResponse()
stubBufferooServiceGetBufferoos(Single.just(bufferooResponse))
val bufferooEntities = mutableListOf<BufferooEntity>()
bufferooResponse.team.forEach {
bufferooEntities.add(entityMapper.mapFromRemote(it))
}
val testObserver = bufferooRemoteImpl.getBufferoos().test()
testObserver.assertValue(bufferooEntities)
}
//</editor-fold>
private fun stubBufferooServiceGetBufferoos(single: Single<BufferooService.BufferooResponse>) {
whenever(bufferooService.getBufferoos())
.thenReturn(single)
}
} | mit |
duftler/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ContinueParentStageHandlerTest.kt | 1 | 9674 | /*
* Copyright 2017 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.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.q.ContinueParentStage
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.orca.q.buildAfterStages
import com.netflix.spinnaker.orca.q.buildBeforeStages
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.stageWithParallelAfter
import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore
import com.netflix.spinnaker.orca.q.stageWithSyntheticBeforeAndNoTasks
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.subject.SubjectSpek
import java.time.Duration
object ContinueParentStageHandlerTest : SubjectSpek<ContinueParentStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val retryDelay = Duration.ofSeconds(5)
subject(CachingMode.GROUP) {
ContinueParentStageHandler(queue, repository, retryDelay.toMillis())
}
fun resetMocks() = reset(queue, repository)
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its before stages complete with $status") {
given("other before stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another before stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("does not re-queue the message") {
verifyZeroInteractions(queue)
}
}
given("the parent stage has tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
}
and("they have not started yet") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("runs the parent stage's first task") {
verify(queue).push(StartTask(pipeline.stageByRef("1"), "1"))
}
}
and("they have already started") {
beforeGroup {
pipeline.stageByRef("1").tasks.first().status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("ignores the message") {
verifyZeroInteractions(queue)
}
}
}
given("the parent stage has no tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBeforeAndNoTasks.type
stageWithSyntheticBeforeAndNoTasks.buildBeforeStages(this)
stageWithSyntheticBeforeAndNoTasks.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage with $status") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its after stages complete with $status") {
given("other after stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another after stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("tells the stage to complete") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
given("all after stages completed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = SUCCEEDED
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("tells the stage to complete") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
})
| apache-2.0 |
fython/shadowsocks-android | mobile/src/main/java/com/github/shadowsocks/plugin/NativePlugin.kt | 7 | 1947 | /*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[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, see <http://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
package com.github.shadowsocks.plugin
import android.content.pm.ResolveInfo
import android.os.Bundle
class NativePlugin(resolveInfo: ResolveInfo) : ResolvedPlugin(resolveInfo) {
init {
check(resolveInfo.providerInfo != null)
}
override val metaData: Bundle get() = resolveInfo.providerInfo.metaData
override val packageName: String get() = resolveInfo.providerInfo.packageName
}
| gpl-3.0 |
googlecodelabs/android-compose-codelabs | AdaptiveUICodelab/app/src/main/java/com/example/reply/ui/ReplyHomeViewModel.kt | 1 | 1838 | /*
* Copyright 2022 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
*
* 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.example.reply.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.reply.data.Email
import com.example.reply.data.EmailsRepository
import com.example.reply.data.EmailsRepositoryImpl
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
class ReplyHomeViewModel(private val emailsRepository: EmailsRepository = EmailsRepositoryImpl()): ViewModel() {
// UI state exposed to the UI
private val _uiState = MutableStateFlow(ReplyHomeUIState(loading = true))
val uiState: StateFlow<ReplyHomeUIState> = _uiState
init {
observeEmails()
}
private fun observeEmails() {
viewModelScope.launch {
emailsRepository.getAllEmails()
.catch { ex ->
_uiState.value = ReplyHomeUIState(error = ex.message)
}
.collect { emails ->
_uiState.value = ReplyHomeUIState(emails = emails)
}
}
}
}
data class ReplyHomeUIState(
val emails : List<Email> = emptyList(),
val loading: Boolean = false,
val error: String? = null
) | apache-2.0 |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/drawable/DrawableProviderImpl.kt | 1 | 1189 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.drawable
import android.graphics.drawable.Drawable
import androidx.annotation.VisibleForTesting
import com.fondesa.recyclerviewdivider.Divider
import com.fondesa.recyclerviewdivider.Grid
/**
* Implementation of [DrawableProvider] which provides the same [Drawable] for each divider.
*
* @param drawable the [Drawable] of each divider.
*/
internal class DrawableProviderImpl(@VisibleForTesting internal val drawable: Drawable) : DrawableProvider {
override fun getDividerDrawable(grid: Grid, divider: Divider): Drawable = drawable
}
| apache-2.0 |
RP-Kit/RPKit | rpk-core/src/main/kotlin/com/rpkit/core/expression/function/string/SubstringFunction.kt | 1 | 1053 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.core.expression.function.string
import com.rpkit.core.expression.RPKFunction
internal class SubstringFunction : RPKFunction {
override fun invoke(vararg args: Any?): Any? {
val arg1 = args[0].toString()
val arg2 = args[1] as? Int ?: args[1].toString().toIntOrNull() ?: return null
val arg3 = args[2] as? Int ?: args[2].toString().toIntOrNull() ?: arg1.length
return arg1.substring(arg2 until arg3)
}
} | apache-2.0 |
RP-Kit/RPKit | bukkit/rpk-experience-lib-bukkit/src/main/kotlin/com/rpkit/experience/bukkit/RPKExperienceLibBukkit.kt | 1 | 869 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.experience.bukkit
import com.rpkit.core.plugin.RPKPlugin
import org.bstats.bukkit.Metrics
import org.bukkit.plugin.java.JavaPlugin
class RPKExperienceLibBukkit : JavaPlugin(), RPKPlugin {
override fun onEnable() {
Metrics(this, 4394)
}
}
| apache-2.0 |
uber/AutoDispose | sample/src/main/kotlin/autodispose2/sample/DisposingViewModel.kt | 1 | 4289 | /*
* Copyright (C) 2019. Uber Technologies
*
* 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 autodispose2.sample
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import autodispose2.autoDispose
import autodispose2.recipes.AutoDisposeViewModel
import autodispose2.sample.repository.NetworkRepository
import autodispose2.sample.state.DownloadState
import com.jakewharton.rxrelay2.BehaviorRelay
import hu.akarnokd.rxjava3.bridge.RxJavaBridge
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
/**
* Demo AutoDisposing ViewModel.
*
* This ViewModel will subscribe to Rx streams for you and pass along
* the values through the [viewRelay].
*
* Often times, like in the case of network calls, we want our network
* requests to go on even if there are orientation changes. If you subscribe
* to your network Rx stream in the view, the request will be cancelled on
* orientation change (since your streams are disposed) and you will likely
* have to make a new network call.
*
* Since the ViewModel survives configuration changes, it is an ideal place
* to subscribe to network Rx streams and then pass it along to the UI
* using a [BehaviorRelay] or LiveData. Since both of them cache the last
* emitted value, as soon as your Activity/Fragment comes back and resubscribes
* to the [viewRelay] after orientation change, it will safely get the most
* updated value.
*
* AutoDispose will automatically dispose any pending subscriptions when
* the [onCleared] method is called since it extends from [AutoDisposeViewModel].
*/
class DisposingViewModel(private val repository: NetworkRepository) : AutoDisposeViewModel() {
/**
* The relay to communicate state to the UI.
*
* This should be subscribed by the UI to get the latest
* state updates unaffected by config changes.
* This could easily be substituted by a LiveData instance
* since both of them cache the last emitted value.
*/
private val viewRelay = BehaviorRelay.create<DownloadState>()
/**
* Downloads a large image over the network.
*
* This could take some time and we wish to show
* a progress indicator to the user. We setup a
* [DownloadState] which we will pass to the UI to
* show our state.
*
* We subscribe in ViewModel to survive configuration
* changes and keep the download request going. As the
* view will resubscribe to the [viewRelay], it will get
* the most updated [DownloadState].
*
* @see repository
*/
fun downloadLargeImage() {
// Notify UI that we're loading network
viewRelay.accept(DownloadState.Started)
repository.downloadProgress()
.subscribeOn(Schedulers.io())
.doOnDispose { Log.i(TAG, "Disposing subscription from the ViewModel") }
.autoDispose(this)
.subscribe(
{ progress ->
viewRelay.accept(DownloadState.InProgress(progress))
},
{ error ->
error.printStackTrace()
},
{
viewRelay.accept(DownloadState.Completed)
}
)
}
/**
* State representation for our current activity.
*
* For the purposes of this demo, we'll use a [String]
* but you can model your own ViewState with a sealed class
* and expose that.
*/
fun downloadState(): Observable<DownloadState> {
return RxJavaBridge.toV3Observable(viewRelay)
}
companion object {
const val TAG = "DisposingViewModel"
}
class Factory(private val networkRepository: NetworkRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return DisposingViewModel(networkRepository) as T
}
}
}
| apache-2.0 |
yongjhih/rx-hivemq | rx-hivemq/src/test/java/rx/hivemq/MainSpec.kt | 1 | 874 | package rx.hivemq
import com.google.common.base.Optional
import com.hivemq.spi.security.ClientData
import com.hivemq.spi.security.SslClientCertificate
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.*
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.any
//import kotlin.test.assertEquals
//import kotlin.test.todo
import org.mockito.Mockito.mock
import org.mockito.Mockito
import org.mockito.Mockito.verify
/**
* Created by yongjhih on 6/4/17.
*/
@RunWith(JUnitPlatform::class)
class MainSpec : Spek({
var counter = 0
beforeEachTest {
counter++
}
describe("a number") {
it ("should be 1") {
assertThat(counter).isEqualTo(1)
}
}
})
| apache-2.0 |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/widget/TaskListWidgetFactory.kt | 1 | 2991 | package fr.geobert.efficio.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.util.Log
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import fr.geobert.efficio.R
import fr.geobert.efficio.data.Task
import fr.geobert.efficio.db.TaskTable
import fr.geobert.efficio.db.WidgetTable
import fr.geobert.efficio.extensions.map
import java.util.*
import kotlin.properties.Delegates
class TaskListWidgetFactory(val ctx: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory {
val TAG = "TaskListWidgetFactory"
val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID)
var tasksList: MutableList<Task> = LinkedList()
var storeId: Long by Delegates.notNull()
var opacity: Float by Delegates.notNull()
var storeName: String by Delegates.notNull()
override fun getLoadingView(): RemoteViews? {
return null // todo a true loading view?
}
override fun getViewAt(position: Int): RemoteViews? {
val t = tasksList[position]
val rv = RemoteViews(ctx.packageName, R.layout.widget_task_row)
rv.setTextViewText(R.id.name, t.item.name)
rv.setTextViewText(R.id.qty_txt, t.qty.toString())
val intent = Intent()
intent.putExtra("taskId", t.id)
rv.setOnClickFillInIntent(R.id.task_btn, intent)
return rv
}
override fun getViewTypeCount(): Int {
return 1
}
override fun onCreate() {
}
private fun fetchWidgetInfo(widgetId: Int): Boolean {
val cursor = WidgetTable.getWidgetInfo(ctx, widgetId)
if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) {
storeId = cursor.getLong(0)
opacity = cursor.getFloat(1)
storeName = cursor.getString(2)
//Log.d(TAG, "fetchWidgetInfo: storeId:$storeId, opacity:$opacity")
return true
}
Log.e(TAG, "fetchWidgetInfo: failed")
return false
}
private fun fetchStoreTask(storeId: Long) {
val token = Binder.clearCallingIdentity()
try {
val cursor = TaskTable.getAllNotDoneTasksForStore(ctx, storeId)
if (cursor != null && cursor.count > 0) {
tasksList = cursor.map(::Task)
} else {
tasksList = LinkedList()
}
cursor?.close()
} finally {
Binder.restoreCallingIdentity(token)
}
}
override fun getItemId(position: Int): Long {
return tasksList[position].id
}
override fun onDataSetChanged() {
if (fetchWidgetInfo(widgetId))
fetchStoreTask(storeId)
}
override fun hasStableIds(): Boolean {
return false
}
override fun getCount(): Int {
return tasksList.count()
}
override fun onDestroy() {
}
} | gpl-2.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/DrawnMaskWordExecutor.kt | 1 | 1758 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.gabrielaimageserver.data.DrawnMaskWordRequest
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.declarations.SonicCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.gabrielaimageserver.handleExceptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
class DrawnMaskWordExecutor(loritta: LorittaBot, val client: GabrielaImageServerClient) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val text = string("text", SonicCommand.I18N_PREFIX.Maniatitlecard.Options.Line1)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessage() // Defer message because image manipulation is kinda heavy
val text = args[options.text]
val result = client.handleExceptions(context) {
client.images.drawnMaskWord(
DrawnMaskWordRequest(text)
)
}
context.sendMessage {
addFile("drawn_mask_word.png", result.inputStream())
}
}
} | agpl-3.0 |
saru95/DSA | Kotlin/Dijkstra.kt | 1 | 1657 | class Dijkstra {
// Dijkstra's algorithm to find shortest path from s to all other nodes
fun dijkstra(G: WeightedGraph, s: Int): IntArray {
val dist = IntArray(G.size()) // shortest known distance from "s"
val pred = IntArray(G.size()) // preceeding node in path
val visited = BooleanArray(G.size()) // all false initially
for (i in dist.indices) {
dist[i] = Integer.MAX_VALUE
}
dist[s] = 0
for (i in dist.indices) {
val next = minVertex(dist, visited)
visited[next] = true
// The shortest path to next is dist[next] and via pred[next].
val n = G.neighbors(next)
for (j in n.indices) {
val v = n[j]
val d = dist[next] + G.getWeight(next, v)
if (dist[v] > d) {
dist[v] = d
pred[v] = next
}
}
}
return pred // (ignore pred[s]==0!)
}
private fun minVertex(dist: IntArray, v: BooleanArray): Int {
var x = Integer.MAX_VALUE
var y = -1 // graph not connected, or no unvisited vertices
for (i in dist.indices) {
if (!v[i] && dist[i] < x) {
y = i
x = dist[i]
}
}
return y
}
fun printPath(G: WeightedGraph, pred: IntArray, s: Int, e: Int) {
val path = java.util.ArrayList()
var x = e
while (x != s) {
path.add(0, G.getLabel(x))
x = pred[x]
}
path.add(0, G.getLabel(s))
System.out.println(path)
}
} | mit |
MichaelRocks/lightsaber | samples/sample-kotlin/src/main/java/io/michaelrocks/lightsaber/sample/DarthVader.kt | 2 | 666 | /*
* Copyright 2018 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.sample
object DarthVader
| apache-2.0 |
owntracks/android | project/app/src/main/java/org/owntracks/android/ui/welcome/VersionFragment.kt | 1 | 2048 | package org.owntracks.android.ui.welcome
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import org.owntracks.android.R
import org.owntracks.android.databinding.UiWelcomeVersionBinding
import javax.inject.Inject
@AndroidEntryPoint
class VersionFragment @Inject constructor() : WelcomeFragment() {
private val viewModel: WelcomeViewModel by activityViewModels()
private lateinit var binding: UiWelcomeVersionBinding
override fun shouldBeDisplayed(context: Context): Boolean =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
binding = UiWelcomeVersionBinding.inflate(inflater, container, false).apply {
uiFragmentWelcomeVersionButtonLearnMore.setOnClickListener {
try {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.documentationUrlAndroid))
)
)
} catch (e: ActivityNotFoundException) {
Snackbar.make(
root,
getString(R.string.noBrowserInstalled),
Snackbar.LENGTH_SHORT
).show()
}
}
screenDesc.movementMethod = ScrollingMovementMethod()
}
return binding.root
}
override fun onResume() {
super.onResume()
viewModel.setWelcomeCanProceed()
}
}
| epl-1.0 |
Haldir65/AndroidRepo | otherprojects/_013_gridlayoutmanager/app/src/test/java/com/me/harris/gridsample/ExampleUnitTest.kt | 1 | 349 | package com.me.harris.gridsample
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| apache-2.0 |
agilie/SwipeToDelete | app/src/main/java/agilie/example/swipe2delete/kotlin/UsersActivity.kt | 1 | 2393 | package agilie.example.swipe2delete.kotlin
import agilie.example.swipe2delete.prepareContactList
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.Menu
import android.view.MenuItem
import android.widget.LinearLayout.VERTICAL
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_java.*
import kotlinx.android.synthetic.main.recycler_view.*
import test.alexzander.swipetodelete.R
import test.alexzander.swipetodelete.R.layout.activity_main
class UsersActivity : android.support.v7.app.AppCompatActivity() {
var adapter: UserAdapter? = null
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activity_main)
setSupportActionBar(toolbar)
initRecyclerView()
}
fun initRecyclerView() {
adapter = UserAdapter(prepareContactList(60)) {
user ->
Toast.makeText(this, user.toString(), Toast.LENGTH_SHORT).show()
}
adapter?.swipeToDeleteDelegate?.pending = true
recyclerView.adapter = adapter
val dividerItemDecoration = DividerItemDecoration(this, VERTICAL)
recyclerView.addItemDecoration(dividerItemDecoration)
val itemTouchHelper = ItemTouchHelper(adapter?.swipeToDeleteDelegate?.itemTouchCallBack)
itemTouchHelper.attachToRecyclerView(recyclerView)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?) =
when (item?.itemId) {
R.id.action_undo_animation -> {
item.isChecked = !item.isChecked
adapter?.animationEnabled = item.isChecked
true
}
R.id.action_bottom_container -> {
item.isChecked = !item.isChecked
adapter?.bottomContainer = item.isChecked
true
}
R.id.action_pending -> {
item.isChecked = !item.isChecked
adapter?.swipeToDeleteDelegate?.pending = item.isChecked
true
}
else -> super.onOptionsItemSelected(item)
}
}
| mit |
spinnaker/spinnaker-gradle-project | spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/extensions/dsl.kt | 1 | 864 | /*
* Copyright 2020 Armory, 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.gradle.extension.extensions
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.ExtensionContainer
internal fun <T> Any.withExtensions(cb: ExtensionContainer.() -> T) = (this as ExtensionAware).extensions.let(cb)
| apache-2.0 |
shyiko/ktlint | ktlint-core/src/main/kotlin/com/github/shyiko/ktlint/core/RuleSetProvider.kt | 1 | 288 | package com.github.shyiko.ktlint.core
/**
* https://github.com/pinterest/ktlint/issues/481
*
* Keep the RuleSetProvider in the old package so that we can detect it and throw an error.
*/
@Deprecated("RuleSetProvider has moved to com.pinterest.ktlint.core")
interface RuleSetProvider
| mit |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/TerraformParserDefinition.kt | 1 | 1768 | /*
* Copyright 2000-2017 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.intellij.plugins.hcl.terraform.config
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import org.intellij.plugins.hcl.HCLCapability
import org.intellij.plugins.hcl.HCLLexer
import org.intellij.plugins.hcl.HCLParserDefinition
import org.intellij.plugins.hcl.psi.impl.HCLFileImpl
import java.util.*
open class TerraformParserDefinition : HCLParserDefinition() {
companion object {
val LexerCapabilities: EnumSet<HCLCapability> = EnumSet.of(HCLCapability.INTERPOLATION_LANGUAGE, HCLCapability.NUMBERS_WITH_BYTES_POSTFIX)
val FILE: IFileElementType = IFileElementType(TerraformLanguage)
}
// TODO: Add special parser with psi elements in terms of Terraform (resource, provider, etc)
override fun createLexer(project: Project): Lexer {
return HCLLexer(LexerCapabilities)
}
override fun getFileNodeType(): IFileElementType {
return FILE
}
override fun createFile(fileViewProvider: FileViewProvider): PsiFile {
return HCLFileImpl(fileViewProvider, TerraformLanguage)
}
}
| apache-2.0 |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/viewmodels/ExternalBookmarksViewModel.kt | 1 | 1423 | package be.digitalia.fosdem.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import be.digitalia.fosdem.alarms.AppAlarmManager
import be.digitalia.fosdem.db.BookmarksDao
import be.digitalia.fosdem.db.ScheduleDao
import be.digitalia.fosdem.model.StatusEvent
import be.digitalia.fosdem.utils.BackgroundWorkScope
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
class ExternalBookmarksViewModel @AssistedInject constructor(
scheduleDao: ScheduleDao,
private val bookmarksDao: BookmarksDao,
private val alarmManager: AppAlarmManager,
@Assisted private val bookmarkIds: LongArray
) : ViewModel() {
val bookmarks: Flow<PagingData<StatusEvent>> =
Pager(PagingConfig(20)) {
scheduleDao.getEvents(bookmarkIds)
}.flow.cachedIn(viewModelScope)
fun addAll() {
BackgroundWorkScope.launch {
bookmarksDao.addBookmarks(bookmarkIds).let { alarmInfos ->
alarmManager.onBookmarksAdded(alarmInfos)
}
}
}
@AssistedFactory
interface Factory {
fun create(bookmarkIds: LongArray): ExternalBookmarksViewModel
}
} | apache-2.0 |
David-Hackro/AndroidDev | app/src/androidTest/java/hackro/tutorials/com/bazar/ExampleInstrumentedTest.kt | 1 | 654 | package hackro.tutorials.com.bazar
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("hackro.tutorials.com.bazar", appContext.packageName)
}
}
| apache-2.0 |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/goods/types/Omelet.kt | 1 | 2812 | package cn.luo.yuan.maze.model.goods.types
import cn.luo.yuan.maze.model.Parameter
import cn.luo.yuan.maze.model.goods.BatchUseGoods
import cn.luo.yuan.maze.model.goods.GoodsProperties
import cn.luo.yuan.maze.model.goods.UsableGoods
import cn.luo.yuan.maze.service.InfoControlInterface
import cn.luo.yuan.maze.utils.Field
/**
*
* Created by luoyuan on 2017/7/16.
*/
class Omelet() : UsableGoods(), BatchUseGoods {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
override fun perform(properties: GoodsProperties): Boolean {
val context = properties["context"] as InfoControlInterface
val hero = properties.hero
var count = properties[Parameter.COUNT] as Int
var msg = ""
while (getCount() >= count && count > 0) {
count-=1
val index = context.random.nextInt(6)
when (index) {
0 -> {
hero.hp = (hero.maxHp * 0.6).toLong()
msg += "使用煎蛋恢复了60%的生命值。"
}
1 -> {
hero.hp = hero.upperHp
hero.pets.forEach {
it.hp = it.maxHp
}
msg += "使用煎蛋恢复了全部的生命值并且复活了所有宠物。"
}
2 -> {
msg += "使用煎蛋恢复了复活了所有宠物。"
hero.pets.forEach {
it.hp = it.maxHp
}
}
3 -> {
msg += "食用煎蛋肚子疼,导致生命值减少50%。"
hero.hp -= (hero.upperHp * 0.5).toLong()
}
4 -> {
msg += "食用了一个黑乎乎的煎蛋,导致生命值变为1。"
hero.hp = hero.hp - hero.currentHp + 1L
}
5 -> {
msg += "使用煎蛋后掉进了一个洞"
if (context.random.nextInt(100) > 3) {
msg += ",不知道怎么跑到最高层了"
context.maze.level = context.maze.maxLevel
} else {
val level = context.random.nextLong(context.maze.maxLevel - 1000)
msg += ",不知道怎么着就跑到" + level + "层了"
context.maze.level = level
}
}
}
msg += "<br>"
}
context.showPopup(msg)
return true
}
override var desc: String = "传说中的煎蛋。吃下去之后发生随机事件。"
override var name: String = "煎蛋"
override var price: Long = 9000L
} | bsd-3-clause |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/FreeStyleProjectactions.kt | 1 | 741 | 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
*/
data class FreeStyleProjectactions(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
| mit |
skydoves/WaterDrink | app/src/main/java/com/skydoves/waterdays/ui/fragments/main/DailyFragment.kt | 1 | 6984 | /*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.ui.fragments.main
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.res.Configuration
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.skydoves.waterdays.R
import com.skydoves.waterdays.WDApplication
import com.skydoves.waterdays.consts.CapacityDrawable
import com.skydoves.waterdays.events.rx.RxUpdateMainEvent
import com.skydoves.waterdays.models.Drink
import com.skydoves.waterdays.persistence.sqlite.SqliteManager
import com.skydoves.waterdays.ui.adapters.DailyDrinkAdapter
import com.skydoves.waterdays.ui.viewholders.DailyDrinkViewHolder
import com.skydoves.waterdays.utils.DateUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.layout_dailyrecord.*
import javax.inject.Inject
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-08-17.
* Copyright (c) 2017 skydoves rights reserved.
*/
class DailyFragment : Fragment() {
@Inject
lateinit var sqliteManager: SqliteManager
private var rootView: View? = null
private val adapter: DailyDrinkAdapter by lazy { DailyDrinkAdapter(delegate) }
private var dateCount = 0
override fun onAttach(context: Context) {
WDApplication.component.inject(this)
super.onAttach(context)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
this.rootView = inflater.inflate(R.layout.layout_dailyrecord, container, false)
return rootView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initializeUI()
}
@SuppressLint("CheckResult")
private fun initializeUI() {
dailyrecord_listview.adapter = adapter
addItems(DateUtils.getFarDay(0))
previous.setOnClickListener { dateMoveButton(it) }
next.setOnClickListener { dateMoveButton(it) }
RxUpdateMainEvent.getInstance().observable
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
adapter.clear()
addItems(DateUtils.getFarDay(0))
}
}
/**
* daily drink viewHolder delegate
*/
private val delegate = object : DailyDrinkViewHolder.Delegate {
override fun onClick(view: View, drink: Drink) {
val alert = AlertDialog.Builder(context!!)
alert.setTitle(getString(R.string.title_edit_capacity))
val input = EditText(context)
input.inputType = InputType.TYPE_CLASS_NUMBER
input.setRawInputType(Configuration.KEYBOARD_12KEY)
alert.setView(input)
alert.setPositiveButton(getString(R.string.yes)) { _: DialogInterface, _: Int ->
try {
val amount = Integer.parseInt(input.text.toString())
if (amount in 1..2999) {
sqliteManager.updateRecordAmount(drink.index, amount)
val drink_edited = Drink(drink.index, amount.toString() + "ml", drink.date, ContextCompat.getDrawable(context!!, CapacityDrawable.getLayout(amount))!!)
val position = adapter.getPosition(drink)
if (position != -1) {
adapter.updateDrinkItem(position, drink_edited)
RxUpdateMainEvent.getInstance().sendEvent()
Toast.makeText(context, R.string.msg_edited_capacity, Toast.LENGTH_SHORT).show()
}
} else
Toast.makeText(context, R.string.msg_invalid_input, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
}
}
alert.setNegativeButton(getString(R.string.no)) { _: DialogInterface, _: Int -> }
alert.show()
val mgr = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
mgr.showSoftInputFromInputMethod(input.applicationWindowToken, InputMethodManager.SHOW_FORCED)
}
override fun onConfirm(drink: Drink) {
sqliteManager.deleteRecord(drink.index)
adapter.remove(drink)
RxUpdateMainEvent.getInstance().sendEvent()
}
}
private fun dateMoveButton(v: View) {
when (v.id) {
R.id.previous -> {
dateCount--
addItems(DateUtils.getFarDay(dateCount))
}
R.id.next -> if (dateCount < 0) {
dateCount++
addItems(DateUtils.getFarDay(dateCount))
} else
Toast.makeText(context, "내일의 기록은 볼 수 없습니다.", Toast.LENGTH_SHORT).show()
}
}
/**
* add items
* @param date now date value
*/
private fun addItems(date: String) {
val tv_todayDate = rootView!!.findViewById(R.id.dailyrecord_tv_todaydate) as TextView
tv_todayDate.text = date
// append day of week Label
if (dateCount == 0) {
tv_todayDate.append(" (오늘)")
} else {
val dayOfWeek = DateUtils.getDayofWeek(date, DateUtils.dateFormat)
tv_todayDate.append(DateUtils.getIndexofDayNameHead(dayOfWeek))
}
// clear
adapter.clear()
// add items
val cursor = sqliteManager.readableDatabase.rawQuery("select * from RecordList where recorddate >= datetime(date('$date','localtime')) and recorddate < datetime(date('$date', 'localtime', '+1 day'))", null)
if (cursor != null && cursor.count > 0 && cursor.moveToLast()) {
do {
val drinkAmount = cursor.getInt(2)
val mainicon: Int
val datetime = cursor.getString(1).split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
mainicon = CapacityDrawable.getLayout(drinkAmount)
// add listItem
val drink = Drink(cursor.getInt(0), Integer.toString(drinkAmount) + "ml", datetime[0] + ":" + datetime[1], ContextCompat.getDrawable(context!!, mainicon)!!)
adapter.addDrinkItem(drink)
} while (cursor.moveToPrevious())
cursor.close()
}
// if no cursor exist
val tv_message = rootView!!.findViewById(R.id.dailyrecord_tv_message) as TextView
if (cursor!!.count == 0)
tv_message.visibility = View.VISIBLE
else
tv_message.visibility = View.INVISIBLE
}
}
| apache-2.0 |
Bombe/Sone | src/main/kotlin/net/pterodactylus/sone/web/pages/UnfollowSonePage.kt | 1 | 927 | package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.util.template.*
import javax.inject.*
/**
* This page lets the user unfollow another Sone.
*/
@ToadletPath("unfollowSone.html")
class UnfollowSonePage @Inject constructor(webInterface: WebInterface, loaders: Loaders, templateRenderer: TemplateRenderer) :
LoggedInPage("Page.UnfollowSone.Title", webInterface, loaders, templateRenderer) {
override fun handleRequest(soneRequest: SoneRequest, currentSone: Sone, templateContext: TemplateContext) {
if (soneRequest.isPOST) {
soneRequest.parameters["sone"]!!.split(Regex("[ ,]+"))
.forEach { soneRequest.core.unfollowSone(currentSone, it) }
redirectTo(soneRequest.parameters["returnPage", 256])
}
}
}
| gpl-3.0 |
nisrulz/android-examples | UsingStetho/app/src/main/java/github/nisrulz/example/usingstetho/MainActivity.kt | 1 | 579 | package github.nisrulz.example.usingstetho
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import github.nisrulz.example.usingstetho.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
with(binding) {
setContentView(root)
}
}
} | apache-2.0 |
lttng/lttng-scope | javeltrace/src/main/kotlin/com/efficios/jabberwocky/javeltrace/XYChartExample.kt | 2 | 2002 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
@file:JvmName("XYChartExample")
package com.efficios.jabberwocky.javeltrace
import com.efficios.jabberwocky.analysis.eventstats.EventStatsXYChartProvider
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.ctf.trace.CtfTrace
import com.efficios.jabberwocky.project.TraceProject
import com.efficios.jabberwocky.views.xychart.view.json.XYChartJsonOutput
import java.nio.file.Files
import java.nio.file.Paths
/**
* Example of a standalone program generating the JSON for the Threads
* timegraph model for a given trace and time range.
*/
fun main(args: Array<String>) {
/* Parse the command-line parameters */
if (args.size < 2) {
printUsage()
return
}
val tracePath = args[0]
val nbPoints = args[1].toIntOrNull()
if (nbPoints == null) {
printUsage()
return
}
/* Create the trace project */
val projectPath = Files.createTempDirectory("project")
val trace = CtfTrace(Paths.get(tracePath))
val project = TraceProject.ofSingleTrace("MyProject", projectPath, trace)
val range = TimeRange.of(project.startTime, project.endTime)
/* Query for a XY chart render for the whole trace */
val provider = EventStatsXYChartProvider()
provider.traceProject = project
val renders = provider.generateSeriesRenders(range, nbPoints, null)
XYChartJsonOutput.printRenderTo(System.out, renders)
/* Cleanup */
projectPath.toFile().deleteRecursively()
}
private fun printUsage() {
System.err.println("Cannot parse command-line arguments.")
System.err.println("Usage: java -jar <jarname>.jar [TRACE PATH] [NB OF DATA POINTS]")
} | epl-1.0 |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/browser/integration/FullScreenIntegration.kt | 1 | 4001 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.browser.integration
import android.app.Activity
import android.os.Build
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.core.view.isVisible
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.browser.toolbar.BrowserToolbar
import mozilla.components.concept.engine.EngineView
import mozilla.components.feature.session.FullScreenFeature
import mozilla.components.feature.session.SessionUseCases
import mozilla.components.support.base.feature.LifecycleAwareFeature
import mozilla.components.support.base.feature.UserInteractionHandler
import mozilla.components.support.ktx.android.view.enterToImmersiveMode
import mozilla.components.support.ktx.android.view.exitImmersiveMode
import org.mozilla.focus.ext.disableDynamicBehavior
import org.mozilla.focus.ext.enableDynamicBehavior
import org.mozilla.focus.ext.hide
import org.mozilla.focus.ext.showAsFixed
import org.mozilla.focus.utils.Settings
class FullScreenIntegration(
val activity: Activity,
val store: BrowserStore,
tabId: String?,
sessionUseCases: SessionUseCases,
private val settings: Settings,
private val toolbarView: BrowserToolbar,
private val statusBar: View,
private val engineView: EngineView,
) : LifecycleAwareFeature, UserInteractionHandler {
@VisibleForTesting
internal var feature = FullScreenFeature(
store,
sessionUseCases,
tabId,
::viewportFitChanged,
::fullScreenChanged,
)
override fun start() {
feature.start()
}
override fun stop() {
feature.stop()
}
@VisibleForTesting
internal fun fullScreenChanged(enabled: Boolean) {
if (enabled) {
enterBrowserFullscreen()
statusBar.isVisible = false
switchToImmersiveMode()
} else {
// If the video is in PiP, but is not in fullscreen anymore we should move the task containing
// this activity to the back of the activity stack
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && activity.isInPictureInPictureMode) {
activity.moveTaskToBack(false)
}
statusBar.isVisible = true
exitBrowserFullscreen()
exitImmersiveMode()
}
}
override fun onBackPressed(): Boolean {
return feature.onBackPressed()
}
@VisibleForTesting
internal fun viewportFitChanged(viewportFit: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
activity.window.attributes.layoutInDisplayCutoutMode = viewportFit
}
}
/**
* Hide system bars. They can be revealed temporarily with system gestures, such as swiping from
* the top of the screen. These transient system bars will overlay app’s content, may have some
* degree of transparency, and will automatically hide after a short timeout.
*/
@VisibleForTesting
internal fun switchToImmersiveMode() {
activity.enterToImmersiveMode()
}
/**
* Show the system bars again.
*/
fun exitImmersiveMode() {
activity.exitImmersiveMode()
}
@VisibleForTesting
internal fun enterBrowserFullscreen() {
if (settings.isAccessibilityEnabled()) {
toolbarView.hide(engineView)
} else {
toolbarView.collapse()
toolbarView.disableDynamicBehavior(engineView)
}
}
@VisibleForTesting
internal fun exitBrowserFullscreen() {
if (settings.isAccessibilityEnabled()) {
toolbarView.showAsFixed(activity, engineView)
} else {
toolbarView.enableDynamicBehavior(activity, engineView)
toolbarView.expand()
}
}
}
| mpl-2.0 |
ysl3000/PathfindergoalAPI | Pathfinder_1_15/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_15_R1/pathfinding/CraftPathfinderManager.kt | 1 | 1159 | package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_15_R1.pathfinding
import com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_15_R1.entity.CraftInsentient
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderManagerMob
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderPlayer
import org.bukkit.entity.*
class CraftPathfinderManager : PathfinderManagerMob {
override fun getPathfinderGoalEntity(creature: Creature): Insentient = CraftInsentient(creature)
override fun getPathfinderGoalEntity(mob: Mob): Insentient = CraftInsentient(mob)
override fun getPathfinderGoalEntity(flying: Flying): Insentient = CraftInsentient(flying)
override fun getPathfinderGoalEntity(ambient: Ambient): Insentient = CraftInsentient(ambient)
override fun getPathfinderGoalEntity(slime: Slime): Insentient = CraftInsentient(slime)
override fun getPathfinderGoalEntity(enderDragon: EnderDragon): Insentient = CraftInsentient(enderDragon)
override fun getPathfinderPlayer(player: Player): PathfinderPlayer = CraftPathfinderPlayer(player)
} | mit |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/icons/providers/DefaultFolderIconProvider.kt | 1 | 2152 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.icons.providers
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.mallowigi.config.AtomFileIconsConfig
import com.mallowigi.config.select.AtomSelectConfig
import com.mallowigi.icons.associations.SelectedAssociations
import com.mallowigi.models.IconType
import icons.AtomIcons
import javax.swing.Icon
/** Default folder icon provider. */
class DefaultFolderIconProvider : AbstractFileIconProvider() {
override fun getIcon(iconPath: String): Icon =
AtomIcons.loadIconWithFallback(AtomIcons.getFolderIcon(iconPath), iconPath)
override fun getSource(): SelectedAssociations = AtomSelectConfig.instance.selectedFolderAssociations
override fun getType(): IconType = IconType.FOLDER
override fun isDefault(): Boolean = true
override fun isNotApplicable(): Boolean = !AtomFileIconsConfig.instance.isEnabledDirectories
override fun isOfType(element: PsiElement): Boolean = element is PsiDirectory
}
| mit |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/MainActivity.kt | 1 | 2063 | package br.edu.ifce.engcomp.francis.radarpolitico.controllers
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.v4.app.FragmentTabHost
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TabWidget
import android.widget.TextView
import br.edu.ifce.engcomp.francis.radarpolitico.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initToolbar()
initTabHost()
}
private fun initToolbar() {
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
}
private fun initTabHost() {
val mainTabHost = findViewById(R.id.main_tabHost) as FragmentTabHost
mainTabHost.setup(this, supportFragmentManager, android.R.id.tabcontent)
val votacoesTab = mainTabHost.newTabSpec("votacoes")
val politicosTab = mainTabHost.newTabSpec("politicos")
votacoesTab.setIndicator("VOTAÇÕES")
politicosTab.setIndicator("POLÍTICOS")
mainTabHost.addTab(votacoesTab, VotacoesTabFragment::class.java, null)
mainTabHost.addTab(politicosTab, DeputadosSeguidosTabFragment::class.java, null)
mainTabHost.currentTab = 0
stylizeTabs(mainTabHost)
}
private fun stylizeTabs(tabHost: FragmentTabHost) {
val tabTextColors: ColorStateList
val tabWidget: TabWidget
var tabTextView: TextView
var tabView: View
val tabAmount: Int
tabWidget = tabHost.tabWidget
tabTextColors = this.resources.getColorStateList(R.color.tab_text_selector)
tabAmount = tabWidget.tabCount
for (i in 0..tabAmount - 1) {
tabView = tabWidget.getChildTabViewAt(i)
tabTextView = tabView.findViewById(android.R.id.title) as TextView
tabTextView.setTextColor(tabTextColors)
}
}
}
| gpl-2.0 |
chenxyu/android-banner | bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/vo/Margins.kt | 1 | 285 | package com.chenxyu.bannerlibrary.vo
/**
* @Author: ChenXingYu
* @CreateDate: 2021/6/6 21:52
* @Description: 外边距(DP)
* @Version: 1.0
*/
data class Margins(var left: Int = 0, var top: Int = 0,
var right: Int = 0, var bottom: Int = 0) | mit |
IntershopCommunicationsAG/jiraconnector-gradle-plugin | src/main/kotlin/com/intershop/gradle/jiraconnector/task/JiraConnectorParameters.kt | 1 | 1633 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.jiraconnector.task
import org.gradle.api.provider.Property
import org.gradle.workers.WorkParameters
/**
* List of parameters for the workerexecutor of all Jira tasks.
*/
interface JiraConnectorParameters : WorkParameters {
/**
* This is the baseUrl property of the Jira connection.
*
* @property baseUrl
*/
val baseUrl: Property<String>
/**
* This is the userName property of the Jira connection.
*
* @property userName
*/
val userName: Property<String>
/**
* This is the userPassword property of the Jira connection.
*
* @property userPassword
*/
val userPassword: Property<String>
/**
* This is the socketTimeout property of the Jira connection.
*
* @property socketTimeout
*/
val socketTimeout: Property<Int>
/**
* This is the requestTimeout property of the Jira connection.
*
* @property requestTimeout
*/
val requestTimeout: Property<Int>
}
| apache-2.0 |
Ekito/koin | koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/article/ArticleScreen.kt | 1 | 8636 | /*
* Copyright 2020 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.example.jetnews.ui.article
import android.content.Context
import android.content.Intent
import androidx.compose.foundation.Icon
import androidx.compose.foundation.Text
import androidx.compose.foundation.contentColor
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.preferredHeight
import androidx.compose.material.AlertDialog
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.TextButton
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Share
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.savedinstancestate.savedInstanceState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ContextAmbient
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.ui.tooling.preview.Preview
import com.example.jetnews.R
import com.example.jetnews.data.Result
import com.example.jetnews.data.posts.PostsRepository
import com.example.jetnews.data.posts.impl.BlockingFakePostsRepository
import com.example.jetnews.data.posts.impl.post3
import com.example.jetnews.model.Post
import com.example.jetnews.ui.ThemedPreview
import com.example.jetnews.ui.home.BookmarkButton
import com.example.jetnews.utils.launchUiStateProducer
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
* Stateful Article Screen that manages state using [launchUiStateProducer]
*
* @param postId (state) the post to show
* @param postsRepository data source for this screen
* @param onBack (event) request back navigation
*/
@Suppress("DEPRECATION") // allow ViewModelLifecycleScope call
@Composable
fun ArticleScreen(
postId: String,
postsRepository: PostsRepository,
onBack: () -> Unit
) {
val (post) = launchUiStateProducer(postsRepository, postId) {
getPost(postId)
}
// TODO: handle errors when the repository is capable of creating them
val postData = post.value.data ?: return
// [collectAsState] will automatically collect a Flow<T> and return a State<T> object that
// updates whenever the Flow emits a value. Collection is cancelled when [collectAsState] is
// removed from the composition tree.
val favorites by postsRepository.observeFavorites().collectAsState(setOf())
val isFavorite = favorites.contains(postId)
// Returns a [CoroutineScope] that is scoped to the lifecycle of [ArticleScreen]. When this
// screen is removed from composition, the scope will be cancelled.
val coroutineScope = rememberCoroutineScope()
ArticleScreen(
post = postData,
onBack = onBack,
isFavorite = isFavorite,
onToggleFavorite = {
coroutineScope.launch { postsRepository.toggleFavorite(postId) }
}
)
}
/**
* Stateless Article Screen that displays a single post.
*
* @param post (state) item to display
* @param onBack (event) request navigate back
* @param isFavorite (state) is this item currently a favorite
* @param onToggleFavorite (event) request that this post toggle it's favorite state
*/
@Composable
fun ArticleScreen(
post: Post,
onBack: () -> Unit,
isFavorite: Boolean,
onToggleFavorite: () -> Unit
) {
var showDialog by savedInstanceState { false }
if (showDialog) {
FunctionalityNotAvailablePopup { showDialog = false }
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = "Published in: ${post.publication?.name}",
style = MaterialTheme.typography.subtitle2,
color = contentColor()
)
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.Filled.ArrowBack)
}
}
)
},
bodyContent = { innerPadding ->
val modifier = Modifier.padding(innerPadding)
PostContent(post, modifier)
},
bottomBar = {
BottomBar(
post = post,
onUnimplementedAction = { showDialog = true },
isFavorite = isFavorite,
onToggleFavorite = onToggleFavorite
)
}
)
}
/**
* Bottom bar for Article screen
*
* @param post (state) used in share sheet to share the post
* @param onUnimplementedAction (event) called when the user performs an unimplemented action
* @param isFavorite (state) if this post is currently a favorite
* @param onToggleFavorite (event) request this post toggle it's favorite status
*/
@Composable
private fun BottomBar(
post: Post,
onUnimplementedAction: () -> Unit,
isFavorite: Boolean,
onToggleFavorite: () -> Unit
) {
Surface(elevation = 2.dp) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.preferredHeight(56.dp)
.fillMaxWidth()
) {
IconButton(onClick = onUnimplementedAction) {
Icon(Icons.Filled.FavoriteBorder)
}
BookmarkButton(
isBookmarked = isFavorite,
onClick = onToggleFavorite
)
val context = ContextAmbient.current
IconButton(onClick = { sharePost(post, context) }) {
Icon(Icons.Filled.Share)
}
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = onUnimplementedAction) {
Icon(vectorResource(R.drawable.ic_text_settings))
}
}
}
}
/**
* Display a popup explaining functionality not available.
*
* @param onDismiss (event) request the popup be dismissed
*/
@Composable
private fun FunctionalityNotAvailablePopup(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
text = {
Text(
text = "Functionality not available \uD83D\uDE48",
style = MaterialTheme.typography.body2
)
},
confirmButton = {
TextButton(onClick = onDismiss) {
Text(text = "CLOSE")
}
}
)
}
/**
* Show a share sheet for a post
*
* @param post to share
* @param context Android context to show the share sheet in
*/
private fun sharePost(post: Post, context: Context) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, post.title)
putExtra(Intent.EXTRA_TEXT, post.url)
}
context.startActivity(Intent.createChooser(intent, "Share post"))
}
@Preview("Article screen")
@Composable
fun PreviewArticle() {
ThemedPreview {
val post = loadFakePost(post3.id)
ArticleScreen(post, {}, false, {})
}
}
@Preview("Article screen dark theme")
@Composable
fun PreviewArticleDark() {
ThemedPreview(darkTheme = true) {
val post = loadFakePost(post3.id)
ArticleScreen(post, {}, false, {})
}
}
@Composable
private fun loadFakePost(postId: String): Post {
val context = ContextAmbient.current
val post = runBlocking {
(BlockingFakePostsRepository(context).getPost(postId) as Result.Success).data
}
return post
}
| apache-2.0 |
zensum/franz | src/main/kotlin/engine/kafka_one/JobStatuses.kt | 1 | 2518 | package franz.engine.kafka_one
import franz.JobStatus
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.consumer.OffsetAndMetadata
import org.apache.kafka.common.TopicPartition
import java.lang.IllegalStateException
private fun <K, V> Map<K, V>.getOrFail(k: K): V = get(k)
?: throw IllegalStateException("Got null when trying to access value for key $k in map ${this.keys}")
private fun findCommittableOffsets(x: Map<JobId, JobStatus>) = x
.toList()
.groupBy { it.first.first }
.map { (_, values) ->
values.sortedBy { (key, _) -> key.second }
.takeWhile { (_, status) -> status.isDone() }
.lastOrNull()?.first
}
.filterNotNull()
.toMap()
.mapValues { (_, v) -> OffsetAndMetadata(v + 1) }
data class JobStatuses<T, U>(
private val jobStatuses: Map<JobId, JobStatus> = emptyMap<JobId, JobStatus>(),
private val records: Map<JobId, ConsumerRecord<T, U>> = emptyMap()
) {
fun update(updates: Map<JobId, JobStatus>) = copy(jobStatuses = jobStatuses + updates)
fun committableOffsets() = findCommittableOffsets(jobStatuses)
fun removeCommitted(committed: Map<TopicPartition, OffsetAndMetadata>) = if (committed.isEmpty()) this else
copy(
jobStatuses = jobStatuses.filterKeys { (topicPartition, offset) ->
val committedOffset = committed[topicPartition]?.offset() ?: -1
offset >= committedOffset
},
records = records.filterValues {
val committedOffset = committed[it.topicPartition()]?.offset() ?: -1
it.offset() >= committedOffset
}
)
fun stateCounts() = jobStatuses.values.map { it::class.java.name!! }.groupBy { it }.mapValues { it.value.count() }
private fun changeBatch(jobs: Iterable<JobId>, status: JobStatus)
= update(jobs.map { it to status }.toMap())
fun addJobs(jobs: Iterable<ConsumerRecord<T, U>>) =
changeBatch(jobs.map { it.jobId() }, JobStatus.Incomplete)
.copy(records = records + jobs.map { it.jobId() to it })
fun rescheduleTransientFailures(): Pair<JobStatuses<T, U>, List<ConsumerRecord<T, U>>> =
jobStatuses
.filterValues { it.mayRetry() }
.keys.let { jobIds: Set<JobId> ->
changeBatch(jobIds, JobStatus.Retry) to jobIds.map(records::getOrFail)
}
}
| mit |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/appdata/setting/SettingModule.kt | 1 | 931 | package net.yslibrary.monotweety.appdata.setting
import android.content.Context
import com.f2prateek.rx.preferences2.RxSharedPreferences
import dagger.Module
import dagger.Provides
import net.yslibrary.monotweety.base.di.Names
import javax.inject.Named
import javax.inject.Singleton
@Module
class SettingModule {
@Named(Names.FOR_SETTING)
@Singleton
@Provides
fun provideSettingPreferences(context: Context): RxSharedPreferences {
val prefs = context.getSharedPreferences(
"net.yslibrary.monotweety.prefs.settings",
Context.MODE_PRIVATE
)
return RxSharedPreferences.create(prefs)
}
@Singleton
@Provides
fun provideSettingDataManager(@Named(Names.FOR_SETTING) prefs: RxSharedPreferences): SettingDataManager {
return SettingDataManagerImpl(prefs)
}
interface Provider {
fun settingDataManager(): SettingDataManager
}
}
| apache-2.0 |
yshrsmz/monotweety | app2/src/main/java/net/yslibrary/monotweety/domain/setting/GetTwitterAppByPackageName.kt | 1 | 784 | package net.yslibrary.monotweety.domain.setting
import net.yslibrary.monotweety.data.twitterapp.AppInfo
import net.yslibrary.monotweety.data.twitterapp.TwitterApp
import net.yslibrary.monotweety.data.twitterapp.TwitterAppRepository
import javax.inject.Inject
interface GetTwitterAppByPackageName {
suspend operator fun invoke(packageName: String): AppInfo?
}
internal class GetTwitterAppByPackageNameImpl @Inject constructor(
private val twitterAppRepository: TwitterAppRepository,
) : GetTwitterAppByPackageName {
override suspend fun invoke(packageName: String): AppInfo? {
val twitterApp = TwitterApp.fromPackageName(packageName)
if (twitterApp == TwitterApp.NONE) return null
return twitterAppRepository.getByPackageName(twitterApp)
}
}
| apache-2.0 |
mrebollob/LoteriadeNavidad | androidApp/src/main/java/com/mrebollob/loteria/android/presentation/platform/ui/components/LotterySnackbarHost.kt | 1 | 1151 | package com.mrebollob.loteria.android.presentation.platform.ui.components
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.Snackbar
import androidx.compose.material.SnackbarData
import androidx.compose.material.SnackbarHost
import androidx.compose.material.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.systemBarsPadding
import com.mrebollob.loteria.android.presentation.platform.ui.theme.Grey7
@Composable
fun LotterySnackbarHost(
hostState: SnackbarHostState,
modifier: Modifier = Modifier,
snackbar: @Composable (SnackbarData) -> Unit = {
Snackbar(
backgroundColor = Grey7,
snackbarData = it
)
}
) {
SnackbarHost(
hostState = hostState,
modifier = modifier
.systemBarsPadding()
.wrapContentWidth(align = Alignment.Start)
.widthIn(max = 550.dp),
snackbar = snackbar
)
}
| apache-2.0 |
appfoundry/fastlane-android-example | sample/app/src/test/kotlin/be/vergauwen/simon/androidretaindata/ui/MainActivityTest.kt | 1 | 1358 | package be.vergauwen.simon.androidretaindata.ui
import be.vergauwen.simon.androidretaindata.BuildConfig
import be.vergauwen.simon.androidretaindata.core.model.GithubRepo
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertNotNull
import kotlinx.android.synthetic.main.main_activity.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricGradleTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(21))
class MainActivityTest{
@Before
fun setUp(){}
@Test
fun preConditions() {
val activity = Robolectric.buildActivity(MainActivity::class.java).get()
assertNotNull(activity)
}
@Test
fun testAddRepo() {
val activity = Robolectric.buildActivity(MainActivity::class.java).create().start().resume().visible().get()
val textView = activity.text_view
activity.showText("test")
assertEquals(textView.text,"test")
}
@Test
fun testShowError() {
val activity = Robolectric.buildActivity(MainActivity::class.java).create().start().resume().visible().get()
val textView = activity.text_view
activity.showError(Throwable("some error"))
assertEquals(textView.text,"some error")
}
} | mit |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/account/create/helper/UrlFormatter.kt | 1 | 1318 | /*
* Copyright 2019 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.account.create.helper
/**
* Url formatter
*/
interface UrlFormatter {
/**
* Format server url
*
* @param serverUrl - Server url to format
* @return formatted server url
*/
fun formatServerUrl(serverUrl: String): String
/**
* Remove leading slash from url to able load data if server url contains trailing path, teamcity.com/server
*
*
* https://github.com/square/retrofit/issues/907
*
*
* ¯\_(ツ)_/¯
*
*
* /app/rest/buildTypes/id:buildType/builds?locator=locator:any - > app/rest/buildTypes/id:buildType/builds?locator=locator:any
*/
fun formatBasicUrl(url: String): String
}
| apache-2.0 |
notion/Plumb | compiler/src/test/kotlin/rxjoin/internal/codegen/validator/InValidatorTest.kt | 2 | 3440 | package rxjoin.internal.codegen.validator
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.any
import org.mockito.Mockito.mock
import javax.lang.model.element.ElementKind.FIELD
import javax.lang.model.element.ElementKind.METHOD
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeKind.DECLARED
import javax.lang.model.type.TypeMirror
import org.mockito.Mockito.`when` as mockWhen
class InValidatorTest : ValidatorTest() {
private val mockObservableDeclaredType = mock(DeclaredType::class.java)
private val mockStringType = mock(TypeMirror::class.java)
private val mockBehaviorSubjectDeclaredType = mock(DeclaredType::class.java)
private val mockBehaviorSubjectTypeMirror = mock(TypeMirror::class.java)
@Before
override fun setUp() {
super.setUp()
mockWhen(mockBehaviorSubjectTypeMirror.kind).thenReturn(DECLARED)
mockWhen(mockBehaviorSubjectTypeMirror.toString()).thenReturn("rx.subjects.BehaviorSubject")
mockWhen(mockBehaviorSubjectDeclaredType.enclosingType).thenReturn(
mockBehaviorSubjectTypeMirror)
mockWhen(mockBehaviorSubjectDeclaredType.typeArguments).thenReturn(
mutableListOf(mockStringType))
mockWhen(mockBehaviorSubjectDeclaredType.kind).thenReturn(DECLARED)
mockWhen(mockObservableDeclaredType.typeArguments).thenReturn(
mutableListOf(mockStringType, mockStringType))
mockWhen(mockObservableDeclaredType.kind).thenReturn(DECLARED)
}
@Test
fun test_Field_isValid() {
mockWhen(mockedTypes.isAssignable(any(), any())).thenReturn(true)
val field = makeMockedInElement(FIELD, mockBehaviorSubjectDeclaredType, "foo")
val model = getJoinerModelWithEntryIds(arrayOf("foo"))
Assertions.assertThat(InValidator.validate(field, getMockedModelWithJoinerModels(model)))
.isTrue()
}
@Test
fun testMethod_isInvalid() {
val field = makeMockedInElement(METHOD, mockBehaviorSubjectDeclaredType, "foo")
val model = getJoinerModelWithEntryIds(arrayOf("foo"))
Assertions.assertThatThrownBy {
InValidator.validate(field, getMockedModelWithJoinerModels(model))
}
.isInstanceOf(Exception::class.java)
.hasMessage(InValidator.elementNotFieldError(field))
}
@Test
fun test_Observable_isInvalid() {
val field = makeMockedInElement(FIELD, mockObservableDeclaredType, "foo")
val model = getJoinerModelWithEntryIds(arrayOf("bar"))
Assertions.assertThatThrownBy {
InValidator.validate(field, getMockedModelWithJoinerModels(model))
}
.isInstanceOf(Exception::class.java)
.hasMessage(InValidator.fieldNotSubjectError(field))
}
@Test
fun test_inValue_withNoMatchingJoiner_isInvalid() {
mockWhen(mockedTypes.isAssignable(any(), any())).thenReturn(true)
val field = makeMockedInElement(FIELD, mockBehaviorSubjectDeclaredType, "foo")
val model = getJoinerModelWithEntryIds(arrayOf("bar"))
Assertions.assertThatThrownBy {
InValidator.validate(field, getMockedModelWithJoinerModels(model))
}
.isInstanceOf(Exception::class.java)
.hasMessage(InValidator.noCorrespondingRegistryError(field))
}
}
| apache-2.0 |
brunogabriel/SampleAppKotlin | SampleAppKotlin/app/src/main/java/io/github/brunogabriel/sampleappkotlin/register/RegisterActivity.kt | 1 | 1434 | package io.github.brunogabriel.sampleappkotlin.register
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import io.github.brunogabriel.sampleappkotlin.R
import io.github.brunogabriel.sampleappkotlin.commons.textValue
import kotlinx.android.synthetic.main.activity_register.*
/**
* Created by brunogabriel on 16/05/17.
*/
class RegisterActivity : AppCompatActivity(), RegisterView {
/** Variables **/
private val presenter: RegisterPresenter<RegisterView> by lazy {
ImplRegisterPresenter(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
create_button.setOnClickListener { presenter.saveUser(name_edittext.textValue(), surname_edittext.textValue()) }
}
override fun showEmptyNameError() {
name_edittext.error = getString(R.string.name_error)
}
override fun showEmptySurnameError() {
surname_edittext.error = getString(R.string.surname_error)
}
override fun showUserSaved() {
AlertDialog.Builder(this)
.setMessage(getString(R.string.save_user))
.setPositiveButton(getString(R.string.undestood), { dialog, which -> dialog.dismiss() }).show()
}
override fun onDestroy() {
super.onDestroy()
presenter.onDestroy()
}
} | mit |
mazine/infer-hierarchy-type-parameter | src/main/kotlin/org/jetbrains/mazine/infer/type/parameter/InferHierarchyType.kt | 1 | 2847 | package org.jetbrains.mazine.infer.type.parameter
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.TypeVariable
/**
* Calculates types in `inheritedClass` that relate to type parameters of the `baseClass`.
*/
fun <B, T : B> inferTypeParameters(baseClass: Class<B>, inheritedClass: Class<T>): Map<TypeVariable<*>, Type> {
val hierarchy = generateSequence<Class<*>>(inheritedClass) { it.superclass }
val initialMapping = hierarchy.first()
.typeParameters
.map { it to it }.toMap<TypeVariable<*>, Type>()
return hierarchy
.takeWhile { it != baseClass }
.fold(initialMapping) { mapping, type ->
val parameters = type.superclass.typeParameters
val arguments = (type.genericSuperclass as? ParameterizedType)?.actualTypeArguments
if (parameters.isNotEmpty() && arguments != null) {
(parameters zip arguments).map { (parameter, argument) ->
parameter to if (argument is TypeVariable<*> && argument in mapping.keys) {
mapping[argument]!!
} else {
argument
}
}.toMap()
} else {
emptyMap()
}
}
}
/**
* Calculates type argument in `inheritedClass` that relates to a type parameter of the `baseClass` named `typeVariableName`.
*/
fun <B, T : B> inferTypeParameter(baseClass: Class<B>, typeVariableName: String, inheritedClass: Class<T>): Type {
val typeVariable = (baseClass.typeParameters.firstOrNull { it.name == typeVariableName }
?: throw IllegalArgumentException("Class ${baseClass.name} has no type parameter $typeVariableName"))
return inferTypeParameters(baseClass, inheritedClass)[typeVariable]!!
}
/**
* Calculates type argument in `inheritedClass` that relates to a type parameter of the `baseClass` named `typeVariableName`
* and expects it to be an instance of `java.util.Class<V>`.
*/
fun <B, T : B, V : Any> inferTypeParameterClass(baseClass: Class<B>, typeVariableName: String, inheritedClass: Class<T>): Class<V> {
val typeParameter = inferTypeParameter(baseClass, typeVariableName, inheritedClass)
val clazz = when (typeParameter) {
is Class<*> -> typeParameter
is ParameterizedType -> typeParameter.rawType as? Class<*>
else -> null
}
@Suppress("UNCHECKED_CAST")
return ((clazz as? Class<V>) ?:
throw IllegalArgumentException("Cannot infer class for type parameter \"$typeVariableName\" of " +
"${baseClass.canonicalName}<${baseClass.typeParameters.joinToString { it.name }}> " +
"for ${inheritedClass.canonicalName}"))
} | apache-2.0 |
yodle/android-kotlin-demo | app/src/main/kotlin/com/yodle/android/kotlindemo/extension/ImageExtensions.kt | 1 | 1240 | package com.yodle.android.kotlindemo.extension
import android.graphics.drawable.BitmapDrawable
import android.support.v7.graphics.Palette
import android.widget.ImageView
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.squareup.picasso.RequestCreator
fun ImageView.generatePalette(listener: (Palette) -> Unit) {
Palette.from((this.drawable as BitmapDrawable).bitmap).generate(listener)
}
fun ImageView.loadUrl(url: String) {
Picasso.with(this.context).load(url).into(this)
}
inline fun ImageView.loadUrl(url: String, callback: KCallback.() -> Unit) {
Picasso.with(this.context).load(url).intoWithCallback(this, callback)
}
inline fun RequestCreator.intoWithCallback(target: ImageView, callback: KCallback.() -> Unit) {
this.into(target, KCallback().apply(callback))
}
class KCallback : Callback {
private var onSuccess: (() -> Unit)? = null
private var onError: (() -> Unit)? = null
override fun onSuccess() {
onSuccess?.invoke()
}
override fun onError() {
onError?.invoke()
}
fun onSuccess(function: () -> Unit) {
this.onSuccess = function
}
fun onError(function: () -> Unit) {
this.onError = function
}
} | mit |
MylesIsCool/ViaVersion | build-logic/src/main/kotlin/extensions.kt | 1 | 1283 | import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.named
import java.io.ByteArrayOutputStream
fun Project.publishShadowJar() {
configurePublication {
artifact(tasks["shadowJar"])
artifact(tasks["sourcesJar"])
}
}
fun Project.publishJavaComponents() {
configurePublication {
from(components["java"])
}
}
private fun Project.configurePublication(configurer: MavenPublication.() -> Unit) {
extensions.configure<PublishingExtension> {
publications.named<MavenPublication>("mavenJava") {
apply(configurer)
}
}
}
fun Project.latestCommitHash(): String {
val byteOut = ByteArrayOutputStream()
exec {
commandLine = listOf("git", "rev-parse", "--short", "HEAD")
standardOutput = byteOut
}
return byteOut.toString(Charsets.UTF_8.name()).trim()
}
fun JavaPluginExtension.javaTarget(version: Int) {
sourceCompatibility = JavaVersion.toVersion(version)
targetCompatibility = JavaVersion.toVersion(version)
}
| mit |
daemontus/glucose | app/src/main/java/com/github/daemontus/glucose/demo/presentation/App.kt | 2 | 359 | package com.github.daemontus.glucose.demo.presentation
import android.app.Application
import com.glucose.app.RootCompatActivity
import timber.log.Timber
class App : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
}
class PresenterActivity : RootCompatActivity(RootPresenter::class.java) | mit |
dataloom/conductor-client | src/main/kotlin/com/openlattice/hazelcast/serializers/DataExpirationStreamSerializer.kt | 1 | 2075 | package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.data.DataExpiration
import com.openlattice.data.DeleteType
import com.openlattice.edm.set.ExpirationBase
import com.openlattice.hazelcast.StreamSerializerTypeIds
import org.springframework.stereotype.Component
@Component
class DataExpirationStreamSerializer : SelfRegisteringStreamSerializer<DataExpiration> {
companion object {
private val expirationTypes = ExpirationBase.values()
private val deleteTypes = DeleteType.values()
@JvmStatic
fun serialize(out: ObjectDataOutput, obj: DataExpiration) {
out.writeLong(obj.timeToExpiration)
out.writeInt(obj.expirationBase.ordinal)
out.writeInt(obj.deleteType.ordinal)
OptionalStreamSerializers.serialize(out, obj.startDateProperty, UUIDStreamSerializerUtils::serialize)
}
@JvmStatic
fun deserialize(input: ObjectDataInput): DataExpiration {
val timeToExpiration = input.readLong()
val expirationType = expirationTypes[input.readInt()]
val deleteType = deleteTypes[input.readInt()]
val startDateProperty = OptionalStreamSerializers.deserialize(input, UUIDStreamSerializerUtils::deserialize)
return DataExpiration(timeToExpiration, expirationType, deleteType, startDateProperty)
}
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.DATA_EXPIRATION.ordinal
}
override fun destroy() {}
override fun getClazz(): Class<out DataExpiration> {
return DataExpiration::class.java
}
override fun write(out: ObjectDataOutput, obj: DataExpiration) {
serialize(out, obj)
}
override fun read(input: ObjectDataInput): DataExpiration {
return deserialize(input)
}
} | gpl-3.0 |
pyamsoft/zaptorch | app/src/main/java/com/pyamsoft/zaptorch/service/torchoff/TorchOffReceiver.kt | 1 | 908 | /*
* Copyright 2020 Peter Kenji Yamanaka
*
* 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.pyamsoft.zaptorch.service.torchoff
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class TorchOffReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
TorchOffService.enqueue(context)
}
}
| apache-2.0 |
JanYoStudio/WhatAnime | app/src/main/java/pw/janyo/whatanime/base/BaseComposeActivity.kt | 1 | 4981 | package pw.janyo.whatanime.base
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import org.koin.core.component.KoinComponent
import pw.janyo.whatanime.R
import pw.janyo.whatanime.ui.theme.WhatAnimeTheme
import pw.janyo.whatanime.ui.theme.isDarkMode
import kotlin.reflect.KClass
abstract class BaseComposeActivity :
ComponentActivity(), KoinComponent {
private var toast: Toast? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initIntent()
setContent {
BuildContentWindow()
}
}
open fun initIntent() {}
@Composable
open fun BuildContentWindow() {
WhatAnimeTheme {
// Remember a SystemUiController
val systemUiController = rememberSystemUiController()
val systemBarColor = MaterialTheme.colorScheme.background
val useDarkIcons = !isDarkMode()
DisposableEffect(systemUiController, useDarkIcons) {
systemUiController.setSystemBarsColor(
color = systemBarColor,
darkIcons = useDarkIcons
)
onDispose {}
}
BuildContent()
}
}
@Composable
open fun BuildContent() {
}
fun <T : Activity> intentTo(
clazz: KClass<T>,
block: Intent.() -> Unit = {},
) {
startActivity(Intent(this, clazz.java).apply(block))
}
fun String.toast(showLong: Boolean = false) =
newToast(
this@BaseComposeActivity,
this,
if (showLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
)
protected fun String.notBlankToast(showLong: Boolean = false) {
if (this.isNotBlank()) {
newToast(
this@BaseComposeActivity,
this,
if (showLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
)
}
}
fun @receiver:StringRes Int.toast(showLong: Boolean = false) =
asString().toast(showLong)
private fun newToast(context: Context, message: String?, length: Int) {
toast?.cancel()
toast = Toast.makeText(context, message, length)
toast?.show()
}
fun @receiver:StringRes Int.asString(): String = getString(this)
@Composable
protected fun ShowProgressDialog(
show: Boolean,
text: String,
fontSize: TextUnit = TextUnit.Unspecified,
) {
val compositionLoading by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.animation_loading)
)
if (!show) {
return
}
Dialog(
onDismissRequest = { },
DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false,
)
) {
Card(
shape = RoundedCornerShape(16.dp),
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(32.dp),
) {
LottieAnimation(
composition = compositionLoading,
iterations = LottieConstants.IterateForever,
modifier = Modifier.size(196.dp)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = text,
fontSize = fontSize,
color = MaterialTheme.colorScheme.onBackground
)
}
}
}
}
} | apache-2.0 |
VisualDig/visualdig-kotlin | dig/src/main/io/visualdig/element/DigElementQuery.kt | 1 | 451 | package io.visualdig.element
import io.visualdig.actions.TestActionInterface
import java.lang.reflect.Type
interface DigElementQuery {
fun action() : TestActionInterface
}
interface DigChainElementQuery<T : TestActionInterface> : DigElementQuery {
val digId : Int
fun specificAction(prevQueries : List<DigElementQuery>) : T
}
interface DigGenesisElementQuery<T : TestActionInterface> : DigElementQuery {
fun specificAction() : T
} | mit |
defio/Room-experimets-in-kotlin | app/src/main/java/com/nicoladefiorenze/room/database/entity/User.kt | 1 | 360 | package com.nicoladefiorenze.room.database.entity
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Project: Room<br/>
* created on: 2017-05-20
*
* @author Nicola De Fiorenze
*/
@Entity(tableName = "user")
class User {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
var name: String = ""
}
| apache-2.0 |
openhab/openhab.android | mobile/src/full/java/org/openhab/habdroid/core/FcmMessageListenerService.kt | 1 | 2907 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.core
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.runBlocking
import org.openhab.habdroid.model.CloudNotification
import org.openhab.habdroid.model.toOH2IconResource
class FcmMessageListenerService : FirebaseMessagingService() {
private lateinit var notifHelper: NotificationHelper
override fun onCreate() {
Log.d(TAG, "onCreate()")
super.onCreate()
notifHelper = NotificationHelper(this)
}
override fun onNewToken(token: String) {
Log.d(TAG, "onNewToken()")
super.onNewToken(token)
FcmRegistrationWorker.scheduleRegistration(this)
}
override fun onMessageReceived(message: RemoteMessage) {
val data = message.data
Log.d(TAG, "onMessageReceived with data $data")
val messageType = data["type"] ?: return
val notificationId = data["notificationId"]?.toInt() ?: 1
when (messageType) {
"notification" -> {
val cloudNotification = CloudNotification(
data["persistedId"].orEmpty(),
data["message"].orEmpty(),
// Older versions of openhab-cloud didn't send the notification generation
// timestamp, so use the (undocumented) google.sent_time as a time reference
// in that case. If that also isn't present, don't show time at all.
data["timestamp"]?.toLong() ?: message.sentTime,
data["icon"].toOH2IconResource(),
data["severity"]
)
runBlocking {
val context = this@FcmMessageListenerService
notifHelper.showNotification(
notificationId,
cloudNotification,
FcmRegistrationWorker.createHideNotificationIntent(context, notificationId),
FcmRegistrationWorker.createHideNotificationIntent(
context,
NotificationHelper.SUMMARY_NOTIFICATION_ID
)
)
}
}
"hideNotification" -> {
notifHelper.cancelNotification(notificationId)
}
}
}
companion object {
private val TAG = FcmMessageListenerService::class.java.simpleName
}
}
| epl-1.0 |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/TooManyFunctionsSpec.kt | 1 | 7407 | package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class TooManyFunctionsSpec : Spek({
describe("different declarations with one function as threshold") {
val rule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_ENUMS to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.THRESHOLD_IN_INTERFACES to "1",
TooManyFunctions.THRESHOLD_IN_OBJECTS to "1"
)))
it("finds one function in class") {
val code = """
class A {
fun a() = Unit
}
"""
val findings = rule.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(6 to 7)
}
it("finds one function in object") {
val code = """
object O {
fun o() = Unit
}
"""
val findings = rule.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(7 to 8)
}
it("finds one function in interface") {
val code = """
interface I {
fun i()
}
"""
val findings = rule.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(10 to 11)
}
it("finds one function in enum") {
val code = """
enum class E {
A;
fun e() {}
}
"""
val findings = rule.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(11 to 12)
}
it("finds one function in file") {
val code = "fun f() = Unit"
assertThat(rule.compileAndLint(code)).hasSize(1)
}
it("finds one function in file ignoring other declarations") {
val code = """
fun f1() = Unit
class C
object O
fun f2() = Unit
interface I
enum class E
fun f3() = Unit
"""
assertThat(rule.compileAndLint(code)).hasSize(1)
}
it("finds one function in nested class") {
val code = """
class A {
class B {
fun a() = Unit
}
}
"""
val findings = rule.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasTextLocations(20 to 21)
}
describe("different deprecated functions") {
val code = """
@Deprecated("")
fun f() {
}
class A {
@Deprecated("")
fun f() {
}
}
"""
it("finds all deprecated functions per default") {
assertThat(rule.compileAndLint(code)).hasSize(2)
}
it("finds no deprecated functions") {
val configuredRule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.IGNORE_DEPRECATED to "true"
)))
assertThat(configuredRule.compileAndLint(code)).isEmpty()
}
}
describe("different private functions") {
val code = """
class A {
private fun f() {}
}
"""
it("finds the private function per default") {
assertThat(rule.compileAndLint(code)).hasSize(1)
}
it("finds no private functions") {
val configuredRule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.IGNORE_PRIVATE to "true"
)))
assertThat(configuredRule.compileAndLint(code)).isEmpty()
}
}
describe("false negative when private and deprecated functions are ignored - #1439") {
it("should not report when file has no public functions") {
val code = """
class A {
private fun a() = Unit
private fun b() = Unit
@Deprecated("")
private fun c() = Unit
}
interface I {
fun a() = Unit
fun b() = Unit
}
class B : I {
override fun a() = Unit
override fun b() = Unit
}
"""
val configuredRule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.IGNORE_PRIVATE to "true",
TooManyFunctions.IGNORE_DEPRECATED to "true",
TooManyFunctions.IGNORE_OVERRIDDEN to "true"
)))
assertThat(configuredRule.compileAndLint(code)).isEmpty()
}
}
describe("overridden functions") {
val code = """
interface I1 {
fun func1()
fun func2()
}
class Foo : I1 {
override fun func1() = Unit
override fun func2() = Unit
}
"""
it("should not report class with overridden functions, if ignoreOverridden is enabled") {
val configuredRule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.IGNORE_OVERRIDDEN to "true"
)))
assertThat(configuredRule.compileAndLint(code)).isEmpty()
}
it("should count overridden functions, if ignoreOverridden is disabled") {
val configuredRule = TooManyFunctions(TestConfig(mapOf(
TooManyFunctions.THRESHOLD_IN_CLASSES to "1",
TooManyFunctions.THRESHOLD_IN_FILES to "1",
TooManyFunctions.IGNORE_OVERRIDDEN to "false"
)))
assertThat(configuredRule.compileAndLint(code)).hasSize(1)
}
}
}
})
| apache-2.0 |
ankidroid/Anki-Android | api/src/test/java/com/ichi2/anki/api/ApiUtilsTest.kt | 1 | 2056 | //noinspection MissingCopyrightHeader #8659
package com.ichi2.anki.api
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
* Created by rodrigobresan on 19/10/17.
*
*
* In case of any questions, feel free to ask me
*
*
* E-mail: [email protected]
* Slack: bresan
*/
@RunWith(RobolectricTestRunner::class)
internal class ApiUtilsTest {
@Test
fun joinFieldsShouldJoinWhenListIsValid() {
val fieldList = arrayOf<String>("A", "B", "C")
assertEquals("A" + delimiter + "B" + delimiter + "C", Utils.joinFields(fieldList))
}
@Test
fun joinFieldsShouldReturnNullWhenListIsNull() {
assertNull(Utils.joinFields(null))
}
@Test
fun splitFieldsShouldSplitRightWhenStringIsValid() {
val fieldList = "A" + delimiter + "B" + delimiter + "C"
val output = Utils.splitFields(fieldList)
assertEquals("A", output[0])
assertEquals("B", output[1])
assertEquals("C", output[2])
}
@Test
fun joinTagsShouldReturnEmptyStringWhenSetIsValid() {
val tags = setOf("A", "B", "C")
assertEquals("A B C", Utils.joinTags(tags))
}
@Test
fun joinTagsShouldReturnEmptyStringWhenSetIsNull() {
assertEquals("", Utils.joinTags(null))
}
@Test
fun joinTagsShouldReturnEmptyStringWhenSetIsEmpty() {
assertEquals("", Utils.joinTags(emptySet()))
}
@Test
fun splitTagsShouldReturnNullWhenStringIsValid() {
val tags = "A B C"
val output = Utils.splitTags(tags)
assertEquals("A", output[0])
assertEquals("B", output[1])
assertEquals("C", output[2])
}
@Test
fun shouldGenerateProperCheckSum() {
assertEquals(3533307532L, Utils.fieldChecksum("AnkiDroid"))
}
companion object {
// We need to keep a copy because a change to Utils.FIELD_SEPARATOR should break the tests
private const val delimiter = "\u001F"
}
}
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.