content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package org.http4k.format import com.natpryce.hamkrest.assertion.assertThat import org.http4k.core.Body import org.http4k.core.ContentType import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.Status.Companion.BAD_REQUEST import org.http4k.core.with import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.http4k.lens.ContentNegotiation import org.http4k.lens.Header import org.http4k.lens.string import org.junit.jupiter.api.Test class AutoContentNegotiatorTest { private val v1Lens = Body.string(ContentType("v1")) .map({ it.replace("v1-", "") }, { "v1-$it" }) .toLens() private val v2Lens = Body.string(ContentType("v2")) .map({ it.replace("v2-", "") }, { "v2-$it" }) .toLens() private val negotiator = ContentNegotiation.auto(v1Lens, v2Lens) private val returnJohn: HttpHandler = { Response(OK).with(negotiator.outbound(it) of "john") } private val receiveJohn: HttpHandler = { req -> val content = negotiator(req) Response(if (content == "john") OK else BAD_REQUEST) } @Test fun `response body - without accept header`() { val response = Request(GET, "/") .let(returnJohn) assertThat(response, hasBody("v1-john")) } @Test fun `response body - with v1 accept header`() { val response = Request(GET, "/") .header("accept", v1Lens.contentType.toHeaderValue()) .let(returnJohn) assertThat(response, hasBody("v1-john")) } @Test fun `response body - with v2 accept header`() { val response = Request(GET, "/") .header("accept", v2Lens.contentType.toHeaderValue()) .let(returnJohn) assertThat(response, hasBody("v2-john")) } @Test fun `request body - v1 body without content-type header`() { val response = Request(GET, "/") .body("v1-john") .let(receiveJohn) assertThat(response, hasStatus(OK)) } @Test fun `request body - v2 body without content-type header`() { val response = Request(GET, "/") .body("v2-john") .let(receiveJohn) assertThat(response, hasStatus(BAD_REQUEST)) } @Test fun `request body - v1 body`() { val response = Request(GET, "/") .with(v1Lens of "john") .with(Header.CONTENT_TYPE of v1Lens.contentType) .let(receiveJohn) assertThat(response, hasStatus(OK)) } @Test fun `request body - v2 body`() { val response = Request(GET, "/") .with(v2Lens of "john") .let(receiveJohn) assertThat(response, hasStatus(OK)) } @Test fun `request body - v1 body with v2 content-type header`() { val response = Request(GET, "/") .with(v1Lens of "john") .with(Header.CONTENT_TYPE of v2Lens.contentType) .let(receiveJohn) assertThat(response, hasStatus(BAD_REQUEST)) } }
http4k-format/core/src/test/kotlin/org/http4k/format/AutoContentNegotiatorTest.kt
3301240878
package io.visualdig.exceptions import io.visualdig.actions.SpacialSearchAction import io.visualdig.results.CloseResult import io.visualdig.results.Result import io.visualdig.results.SpacialSearchResult import io.visualdig.spacial.Direction import io.visualdig.spacial.SearchPriority import java.lang.Math.abs import java.util.* class DigSpacialException(action: SpacialSearchAction, result: SpacialSearchResult) : Exception(getDetailedMessage(action, result)) { companion object { private fun getDetailedMessage(action: SpacialSearchAction, result: SpacialSearchResult): String { val direction = action.direction.description.toLowerCase(Locale.ENGLISH) val elementType = action.elementType.description.toLowerCase(Locale.ENGLISH) val queryText = action.prevQueries.first().queryDescription() val errorText: String when (result.result) { Result.Failure_NoMatch -> { if (result.closeResults.isEmpty()) { errorText = noCloseMatchesMessage(direction, elementType, queryText) } else { val htmlId = result.closeResults.first().htmlId val spacialDescription = getSpacialDescription(action.direction, result.closeResults.first()) errorText = closeMatchMessage(direction, elementType, htmlId, queryText, spacialDescription) } } Result.Failure_AmbiguousMatch -> { if(action.priority == SearchPriority.DISTANCE) { errorText = ambiguousDistanceMatchMessage(direction, elementType, result.closeResults, queryText) } else if(action.priority == SearchPriority.ALIGNMENT) { errorText = ambiguousAlignmentMatchMessage(direction, elementType, result.closeResults, queryText) } else { throw DigFatalException("Result should not be ambiguous if alignment and distance based") } } Result.Failure_QueryExpired -> { errorText = "Query expired TODO"} Result.Success -> { throw DigFatalException("Result from spacial search should not be successful inside of an exception method") } } return errorText } private fun ambiguousDistanceMatchMessage(direction: String, elementType: String, closeResults: List<CloseResult>, queryText: String): String { val foundString = "$elementType B and $elementType C which both are the same distance from element A." val capitalizeFoundString = foundString.capitalize() val bElementInfoText : String if (closeResults[0].htmlId == null) { bElementInfoText = "First ambiguous element (no HTML id)" } else { val htmlId = closeResults[0].htmlId bElementInfoText = "First ambiguous element with HTML id: $htmlId" } val cElementInfoText : String if (closeResults[1].htmlId == null) { cElementInfoText = "Second ambiguous element (no HTML id)" } else { val htmlId = closeResults[1].htmlId cElementInfoText = "Second ambiguous element with HTML id: $htmlId" } return """ Could not find an unambiguous $elementType element $direction of element A. Expected: ___ ___ | | | | | A | | B | |___| |___| Found: $capitalizeFoundString Suggestions: - Are these elements overlapping on the web page? - Try setting the priority to DistanceThenAlignment or AlignmentThenDistance to resolve which factor matters more in this test: distance or alignment. Additional Info: A = $queryText B = $bElementInfoText C = $cElementInfoText """ } private fun ambiguousAlignmentMatchMessage(direction: String, elementType: String, closeResults: List<CloseResult>, queryText: String): String { val foundString = "$elementType B and $elementType C which both have the same alignment relative to element A." val capitalizeFoundString = foundString.capitalize() val bElementInfoText : String if (closeResults[0].htmlId == null) { bElementInfoText = "First ambiguous element (no HTML id)" } else { val htmlId = closeResults[0].htmlId bElementInfoText = "First ambiguous element with HTML id: $htmlId" } val cElementInfoText : String if (closeResults[1].htmlId == null) { cElementInfoText = "Second ambiguous element (no HTML id)" } else { val htmlId = closeResults[1].htmlId cElementInfoText = "Second ambiguous element with HTML id: $htmlId" } return """ Could not find an unambiguous $elementType element $direction of element A. Expected: ___ ___ | | | | | A | | B | |___| |___| Found: $capitalizeFoundString Suggestions: - Are these elements overlapping on the web page? - Try setting the priority to DistanceThenAlignment or AlignmentThenDistance to resolve which factor matters more in this test: distance or alignment. Additional Info: A = $queryText B = $bElementInfoText C = $cElementInfoText """ } private fun closeMatchMessage(direction: String, elementType: String, htmlId: String?, queryText: String, spacialDescription: String): String { val closestMatchIdText : String if(htmlId == null) { closestMatchIdText = "There was a close match, but it has no HTML id." } else { closestMatchIdText = "The closest match was an element with id: $htmlId." } return """ Unable to find $elementType $direction of $queryText. $closestMatchIdText $spacialDescription """ } private fun noCloseMatchesMessage(direction: String, elementType: String, queryText: String): String { return """ Unable to find $elementType $direction of $queryText. There are no close matches. This is likely because the element isn't visible or it is actually east of $queryText. """ } private fun getSpacialDescription(direction: Direction, result: CloseResult): String { val directionText = direction.description.toLowerCase(Locale.ENGLISH) var offDirection = "" var offAmount = 0 var isAlignmentMessage = true when (direction) { Direction.EAST -> { offAmount = (abs(result.y) - result.tolerance) if (result.y < 0) { offDirection = "south" } else { offDirection = "north" } isAlignmentMessage = result.x > 0 } Direction.WEST -> { offAmount = (abs(result.y) - result.tolerance) if (result.y < 0) { offDirection = "south" } else { offDirection = "north" } isAlignmentMessage = result.x < 0 } Direction.NORTH -> { offAmount = (abs(result.x) - result.tolerance) if (result.x < 0) { offDirection = "west" } else { offDirection = "east" } isAlignmentMessage = result.y > 0 } Direction.SOUTH -> { offAmount = (abs(result.x) - result.tolerance) if (result.x < 0) { offDirection = "west" } else { offDirection = "east" } isAlignmentMessage = result.y < 0 } } if (isAlignmentMessage) { return "The element was $offAmount pixels too far $offDirection to be considered aligned $directionText." } return "TODO WOOPS" } } }
dig/src/main/io/visualdig/exceptions/DigSpacialException.kt
1580558417
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.boot.docs.actuator.metrics.export.jmx import io.micrometer.core.instrument.Clock import io.micrometer.core.instrument.Meter import io.micrometer.core.instrument.config.NamingConvention import io.micrometer.core.instrument.util.HierarchicalNameMapper import io.micrometer.jmx.JmxConfig import io.micrometer.jmx.JmxMeterRegistry import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration(proxyBeanMethods = false) class MyJmxConfiguration { @Bean fun jmxMeterRegistry(config: JmxConfig, clock: Clock): JmxMeterRegistry { return JmxMeterRegistry(config, clock, this::toHierarchicalName) } private fun toHierarchicalName(id: Meter.Id, convention: NamingConvention): String { return /**/ HierarchicalNameMapper.DEFAULT.toHierarchicalName(id, convention) } }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/actuator/metrics/export/jmx/MyJmxConfiguration.kt
790302953
package com.madetech.clean.boundary import com.madetech.clean.usecase.AsynchronousUseCase import kotlin.reflect.KClass interface AsynchronousUseCaseExecutor { fun <U : AsynchronousUseCase<R, P>, R, P> executeUseCase(useCase: KClass<U>, request: R, presenter: P) }
src/main/kotlin/com/madetech/clean/boundary/AsynchronousUseCaseExecutor.kt
2860341741
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.core.upnp.error /** * Notifies a caller about an issue related to the invoked action. * * This exception is typically raised when a given action is not available on the target * device. This error type is provided for completeness and is typically not returned by routers * through the Beacon code as actions are only accessed if exposed by the device via its manifest. * * @author [Johannes Donath](mailto:[email protected]) * @date 06/12/2020 */ class InvalidActionException(message: String? = null, cause: Throwable? = null) : ActionException(message, cause)
core/src/main/kotlin/tv/dotstart/beacon/core/upnp/error/InvalidActionException.kt
762487609
/* Copyright (c) 2021 Tarek Mohamed <[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.ichi2.anki.dialogs.tags import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.RadioGroup import androidx.fragment.app.testing.FragmentScenario import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.recyclerview.widget.RecyclerView import androidx.test.ext.junit.runners.AndroidJUnit4 import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.customview.getCustomView import com.ichi2.anki.R import com.ichi2.testutils.ParametersUtils import com.ichi2.testutils.RecyclerViewUtils import com.ichi2.ui.CheckBoxTriStates import com.ichi2.utils.ListUtil import org.hamcrest.MatcherAssert import org.hamcrest.core.IsNull import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.whenever import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference @RunWith(AndroidJUnit4::class) class TagsDialogTest { @Test fun testTagsDialogCustomStudyOptionInterface() { val type = TagsDialog.DialogType.CUSTOM_STUDY_TAGS val allTags = listOf("1", "2", "3", "4") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, ArrayList(), allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val optionsGroup = body.findViewById<RadioGroup>(R.id.tags_dialog_options_radiogroup) Assert.assertEquals(optionsGroup.visibility.toLong(), View.VISIBLE.toLong()) val expectedOption = 1 optionsGroup.getChildAt(expectedOption).performClick() dialog.getActionButton(WhichButton.POSITIVE).callOnClick() Mockito.verify(mockListener, Mockito.times(1)).onSelectedTags(ArrayList(), ArrayList(), expectedOption) } } @Test fun testTagsDialogCustomStudyOptionFragmentAPI() { val type = TagsDialog.DialogType.CUSTOM_STUDY_TAGS val allTags = listOf("1", "2", "3", "4") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, ArrayList(), allTags) .arguments val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val returnedList = AtomicReference<List<String>?>() val returnedOption = AtomicInteger() f.parentFragmentManager.setFragmentResultListener( TagsDialogListener.ON_SELECTED_TAGS_KEY, mockLifecycleOwner(), { _: String?, bundle: Bundle -> returnedList.set(bundle.getStringArrayList(TagsDialogListener.ON_SELECTED_TAGS__SELECTED_TAGS)) returnedOption.set(bundle.getInt(TagsDialogListener.ON_SELECTED_TAGS__OPTION)) } ) val body = dialog!!.getCustomView() val optionsGroup = body.findViewById<RadioGroup>(R.id.tags_dialog_options_radiogroup) Assert.assertEquals(optionsGroup.visibility.toLong(), View.VISIBLE.toLong()) val expectedOption = 2 optionsGroup.getChildAt(expectedOption).performClick() dialog.getActionButton(WhichButton.POSITIVE).callOnClick() ListUtil.assertListEquals(ArrayList(), returnedList.get()) Assert.assertEquals(expectedOption.toLong(), returnedOption.get().toLong()) } } // regression test #8762 // test for #8763 @Test fun test_AddNewTag_shouldBeVisibleInRecyclerView_andSortedCorrectly() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "zzzz" f.addTag(tag) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val lastItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) val newTagItemItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals(5, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals(tag, newTagItemItem.text) Assert.assertTrue(newTagItemItem.isChecked) Assert.assertNotEquals(tag, lastItem.text) Assert.assertFalse(lastItem.isChecked) } } // test for #8763 @Test fun test_AddNewTag_existingTag_shouldBeSelectedAndSorted() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "e" f.addTag(tag) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val lastItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val newTagItemItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals(4, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals(tag, newTagItemItem.text) Assert.assertTrue(newTagItemItem.isChecked) Assert.assertNotEquals(tag, lastItem.text) Assert.assertFalse(lastItem.isChecked) } } @Test fun test_checked_unchecked_indeterminate() { val type = TagsDialog.DialogType.EDIT_TAGS val expectedAllTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val uncheckedTags = listOf("b", "d") val expectedCheckedTags = listOf("a") val expectedUncheckedTags = listOf("d", "e") val expectedIndeterminate = listOf("b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, uncheckedTags, expectedAllTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val itemCount = recycler.adapter!!.itemCount val foundAllTags: MutableList<String> = ArrayList() val foundCheckedTags: MutableList<String> = ArrayList() val foundUncheckedTags: MutableList<String> = ArrayList() val foundIndeterminate: MutableList<String> = ArrayList() for (i in 0 until itemCount) { val vh = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, i) val tag = vh.text foundAllTags.add(tag) when (vh.checkboxState) { CheckBoxTriStates.State.INDETERMINATE -> foundIndeterminate.add(tag) CheckBoxTriStates.State.UNCHECKED -> foundUncheckedTags.add(tag) CheckBoxTriStates.State.CHECKED -> foundCheckedTags.add(tag) else -> Assert.fail("Unknown CheckBoxTriStates.State? " + vh.checkboxState) } } ListUtil.assertListEquals(expectedAllTags, foundAllTags) ListUtil.assertListEquals(expectedCheckedTags, foundCheckedTags) ListUtil.assertListEquals(expectedUncheckedTags, foundUncheckedTags) ListUtil.assertListEquals(expectedIndeterminate, foundIndeterminate) } } @Test fun test_TagsDialog_expandPathToCheckedTagsUponOpening() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "fruit::apple", "fruit::pear", "fruit::pear::big", "sport::football", "sport::tennis", "book" ) val checkedTags = listOf( "fruit::pear::big", "sport::tennis" ) val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun getItem(index: Int): TagsArrayAdapter.ViewHolder { return RecyclerViewUtils.viewHolderAt(recycler, index) } fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } updateLayout() // v fruit [-] // - apple [ ] // v pear [-] // - big [x] // v sport [-] // - football [ ] // - tennis [x] // - book [ ] Assert.assertEquals(8, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals("fruit", getItem(0).text) Assert.assertEquals("fruit::apple", getItem(1).text) Assert.assertEquals("fruit::pear", getItem(2).text) Assert.assertEquals("fruit::pear::big", getItem(3).text) Assert.assertEquals("sport", getItem(4).text) Assert.assertEquals("sport::football", getItem(5).text) Assert.assertEquals("sport::tennis", getItem(6).text) Assert.assertEquals("book", getItem(7).text) } } @Test fun test_AddNewTag_newHierarchicalTag_pathToItShouldBeExpanded() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("common::speak", "common::speak::daily", "common::sport::tennis", "common::sport::football") val checkedTags = listOf("common::speak::daily", "common::sport::tennis") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "common::sport::football::small" f.addTag(tag) // v common [-] // v speak [-] // - daily [x] // v sport [-] // v football [-] // > small [x] // - tennis [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(7, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) val item3 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val item4 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) val item5 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 5) val item6 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 6) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::speak", item1.text) Assert.assertEquals("common::speak::daily", item2.text) Assert.assertEquals("common::sport", item3.text) Assert.assertEquals("common::sport::football", item4.text) Assert.assertEquals("common::sport::football::small", item5.text) Assert.assertEquals("common::sport::tennis", item6.text) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item0.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item1.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, item2.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item3.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item4.mCheckBoxView.state) Assert.assertTrue(item5.mCheckBoxView.isChecked) Assert.assertTrue(item6.mCheckBoxView.isChecked) } } @Test fun test_AddNewTag_newHierarchicalTag_willUniformHierarchicalTag() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("common") val checkedTags = listOf("common") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "common::::careless" f.addTag(tag) // v common [x] // > blank [-] // - careless [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(3, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::blank", item1.text) Assert.assertEquals("common::blank::careless", item2.text) Assert.assertTrue(item0.mCheckBoxView.isChecked) Assert.assertTrue(item1.mCheckBoxView.state == CheckBoxTriStates.State.INDETERMINATE) Assert.assertTrue(item2.mCheckBoxView.isChecked) } } @Test fun test_SearchTag_showAllRelevantTags() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "common::speak", "common::speak::tennis", "common::sport::tennis", "common::sport::football", "common::sport::football::small" ) val checkedTags = listOf( "common::speak::tennis", "common::sport::tennis", "common::sport::football::small" ) val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val adapter = recycler.adapter!! as TagsArrayAdapter adapter.filter.filter("tennis") // v common [-] // v speak [-] // - tennis [x] // v sport [-] // - tennis [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(5, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) val item3 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val item4 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::speak", item1.text) Assert.assertEquals("common::speak::tennis", item2.text) Assert.assertEquals("common::sport", item3.text) Assert.assertEquals("common::sport::tennis", item4.text) } } @Test fun test_SearchTag_willInheritExpandState() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf("common::speak", "common::sport::tennis") val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } val adapter = recycler.adapter!! as TagsArrayAdapter adapter.filter.filter("sport") updateLayout() // v common [ ] // v sport [ ] // - tennis [ ] Assert.assertEquals(3, recycler.adapter!!.itemCount.toLong()) adapter.filter.filter("") updateLayout() // v common [ ] // - speak [ ] // v sport [ ] // - tennis [ ] Assert.assertEquals(4, recycler.adapter!!.itemCount.toLong()) } } @Test fun test_CheckTags_intermediateTagsShouldToggleDynamically() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "common::speak", "common::speak::tennis", "common::sport::tennis", "common::sport::football", "common::sport::football::small" ) val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun getItem(index: Int): TagsArrayAdapter.ViewHolder { return RecyclerViewUtils.viewHolderAt(recycler, index) } fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } updateLayout() getItem(0).itemView.performClick() updateLayout() getItem(1).itemView.performClick() updateLayout() getItem(3).itemView.performClick() updateLayout() getItem(4).itemView.performClick() updateLayout() // v common [ ] // v speak [ ] // - tennis [ ] // v sport [ ] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(7, recycler.adapter!!.itemCount.toLong()) getItem(2).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [-] // - tennis [x] // v sport [-] // v football [-] // - small [x] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(2).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [ ] // v speak [ ] // - tennis [ ] // v sport [ ] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [ ] // - tennis [ ] // v sport [-] // v football [-] // - small [x] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(3).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [ ] // - tennis [ ] // v sport [x] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) } } @Test // #11089 fun test_SearchTag_spaceWillBeFilteredCorrectly() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf("hello::world") val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val editText = f.getSearchView()!!.findViewById<EditText>(R.id.search_src_text)!! editText.setText("hello ") Assert.assertEquals( "The space should be replaced by '::' without mistakenly clear everything.", "hello::", editText.text.toString() ) editText.setText("hello") editText.text.insert(5, " ") Assert.assertEquals("Should complete 2 colons.", "hello::", editText.text.toString()) editText.setText("hello:") editText.text.insert(6, " ") Assert.assertEquals("Should complete 1 colon.", "hello::", editText.text.toString()) editText.setText("hello::") editText.text.insert(7, " ") Assert.assertEquals("Should do nothing.", "hello::", editText.text.toString()) editText.setText("") editText.text.insert(0, " ") Assert.assertEquals("Should not crash.", "::", editText.text.toString()) } } companion object { private fun mockLifecycleOwner(): LifecycleOwner { val owner = Mockito.mock(LifecycleOwner::class.java) val lifecycle = LifecycleRegistry(owner) lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) whenever(owner.lifecycle).thenReturn(lifecycle) return owner } } }
AnkiDroid/src/test/java/com/ichi2/anki/dialogs/tags/TagsDialogTest.kt
1977790853
package com.samourai.wallet.tor import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Process import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.samourai.wallet.BuildConfig import com.samourai.wallet.MainActivity2 import com.samourai.wallet.R import com.samourai.wallet.SamouraiApplication import com.samourai.wallet.util.PrefsUtil import io.matthewnelson.topl_core_base.TorConfigFiles import io.matthewnelson.topl_service.TorServiceController import io.matthewnelson.topl_service.TorServiceController.* import io.matthewnelson.topl_service.lifecycle.BackgroundManager import io.matthewnelson.topl_service.notification.ServiceNotification import org.json.JSONException import org.json.JSONObject import java.io.File import java.net.InetSocketAddress import java.net.Proxy /** * samourai-wallet-android * */ object TorManager { lateinit var stopTorDelaySettingAtAppStartup: String private set private var proxy: Proxy? = null enum class TorState { WAITING, ON, OFF } var appContext: SamouraiApplication? = null private val torStateLiveData: MutableLiveData<TorState> = MutableLiveData() private val torProgress: MutableLiveData<Int> = MutableLiveData() var torState: TorState = TorState.OFF set(value) { field = value torStateLiveData.postValue(value) } fun startTor() { TorServiceController.startTor() } private fun generateTorServiceNotificationBuilder( ): ServiceNotification.Builder { var contentIntent: PendingIntent? = null appContext?.packageManager?.getLaunchIntentForPackage(appContext!!.packageName)?.let { intent -> contentIntent = PendingIntent.getActivity( appContext, 0, intent, 0 ) } return ServiceNotification.Builder( channelName = "Tor service", channelDescription = "Tor foreground service notification", channelID = SamouraiApplication.TOR_CHANNEL_ID, notificationID = 12 ) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setImageTorNetworkingEnabled(R.drawable.ic_samourai_tor_enabled) .setImageTorDataTransfer(R.drawable.ic_samourai_tor_data_transfer) .setImageTorNetworkingDisabled(R.drawable.ic_samourai_tor_idle) .setCustomColor(R.color.green_ui_2) .enableTorRestartButton(true) .enableTorStopButton(false) .showNotification(true) .also { builder -> contentIntent?.let { builder.setContentIntent(it) } } } /** * for a cleaner * */ private fun generateBackgroundManagerPolicy( ): BackgroundManager.Builder.Policy { val builder = BackgroundManager.Builder() return builder.runServiceInForeground(true) } private fun setupTorServices( application: Application, serviceNotificationBuilder: ServiceNotification.Builder, ): Builder { val installDir = File(application.applicationInfo.nativeLibraryDir) val configDir = application.getDir("torservice", Context.MODE_PRIVATE) val builder = TorConfigFiles.Builder(installDir, configDir) builder.torExecutable(File(installDir, "libTor.so")) return Builder( application = application, torServiceNotificationBuilder = serviceNotificationBuilder, backgroundManagerPolicy = generateBackgroundManagerPolicy(), buildConfigVersionCode = BuildConfig.VERSION_CODE, defaultTorSettings = TorSettings(), geoipAssetPath = "common/geoip", geoip6AssetPath = "common/geoip6", ) .useCustomTorConfigFiles(builder.build()) .setBuildConfigDebug(BuildConfig.DEBUG) .setEventBroadcaster(eventBroadcaster = TorEventBroadcaster()) } fun isRequired(): Boolean { return PrefsUtil.getInstance(appContext).getValue(PrefsUtil.ENABLE_TOR, false); } fun isConnected(): Boolean { return getTorStateLiveData().value == TorState.ON } fun getTorStateLiveData(): LiveData<TorState> { return torStateLiveData } fun getTorBootstrapProgress(): LiveData<Int> { return torProgress } fun getProxy(): Proxy? { return proxy; } fun setUp(context: SamouraiApplication) { appContext = context val builder = setupTorServices( context, generateTorServiceNotificationBuilder(), ) try { builder.build() } catch (e: Exception) { e.message?.let { } } TorServiceController.appEventBroadcaster?.let { (it as TorEventBroadcaster).liveTorState.observeForever { torEventState -> when (torEventState.state) { "Tor: Off" -> { torState = TorState.OFF } "Tor: Starting" -> { torState = TorState.WAITING } "Tor: Stopping" -> { torState = TorState.WAITING } } } it.torLogs.observeForever { log -> if (log.contains("Bootstrapped 100%")) { torState = TorState.ON } if (log.contains("NEWNYM")) { val message = log.substring(log.lastIndexOf("|"), log.length) Toast.makeText(appContext, message.replace("|", ""), Toast.LENGTH_SHORT).show() } } it.torBootStrapProgress.observeForever { log -> torProgress.postValue(log) } it.torPortInfo.observeForever { torInfo -> torInfo.socksPort?.let { port -> createProxy(port) } } } } private fun createProxy(proxyUrl: String) { val host = proxyUrl.split(":")[0].trim() val port = proxyUrl.split(":")[1] proxy = Proxy(Proxy.Type.SOCKS, InetSocketAddress( host, port.trim().toInt())) } fun toJSON(): JSONObject { val jsonPayload = JSONObject(); try { jsonPayload.put("active", PrefsUtil.getInstance(appContext).getValue(PrefsUtil.ENABLE_TOR,false)); } catch (ex: JSONException) { // throw RuntimeException(ex); } catch (ex: ClassCastException) { // throw RuntimeException(ex); } return jsonPayload } fun fromJSON(jsonPayload: JSONObject) { try { if (jsonPayload.has("active")) { PrefsUtil.getInstance(appContext).setValue(PrefsUtil.ENABLE_TOR, jsonPayload.getBoolean("active")); } } catch (ex: JSONException) { } } }
app/src/main/java/com/samourai/wallet/tor/TorManager.kt
1728120748
package de.westnordost.streetcomplete.quests.validator import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class DeprecateFIXME() : OsmFilterQuestType<Boolean>() { override val elementFilter = "nodes, ways, relations with FIXME and !fixme" override val commitMessage = "convert FIXME to fixme" override val icon = R.drawable.ic_quest_power override fun getTitle(tags: Map<String, String>) = R.string.quest_convert_FIXME_to_fixme override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> { val name = tags["FIXME"] return if (name != null) arrayOf(name) else arrayOf() } override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { if (answer){ val fixme = changes.getPreviousValue("FIXME")!! changes.delete("FIXME") changes.add("fixme", fixme) } } override val wikiLink = "Key:fixme" override val questTypeAchievements: List<QuestTypeAchievement> get() = listOf() }
app/src/main/java/de/westnordost/streetcomplete/quests/validator/DeprecateFIXME.kt
4262476462
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.manager.chat import com.toshi.BuildConfig import com.toshi.R import com.toshi.crypto.HDWallet import com.toshi.crypto.signal.ChatService import com.toshi.crypto.signal.store.ProtocolStore import com.toshi.crypto.signal.store.SignalTrustStore import com.toshi.manager.UserManager import com.toshi.manager.model.SofaMessageTask import com.toshi.manager.store.ConversationStore import com.toshi.model.local.Conversation import com.toshi.model.local.Group import com.toshi.model.local.IncomingMessage import com.toshi.model.local.Recipient import com.toshi.model.local.User import com.toshi.model.sofa.Init import com.toshi.model.sofa.SofaAdapters import com.toshi.model.sofa.SofaMessage import com.toshi.util.LocaleUtil import com.toshi.util.logging.LogUtil import com.toshi.util.sharedPrefs.SignalPrefs import com.toshi.view.BaseApplication import org.whispersystems.signalservice.internal.configuration.SignalServiceUrl import rx.Completable import rx.Observable import rx.Scheduler import rx.Single import rx.Subscription import rx.schedulers.Schedulers class SofaMessageManager( private val conversationStore: ConversationStore, private val userManager: UserManager, private val baseApplication: BaseApplication = BaseApplication.get(), private val protocolStore: ProtocolStore = ProtocolStore().init(), private val trustStore: SignalTrustStore = SignalTrustStore(), private val signalServiceUrl: SignalServiceUrl = SignalServiceUrl(baseApplication.getString(R.string.chat_url), trustStore), private val signalServiceUrls: Array<SignalServiceUrl> = Array(1, { signalServiceUrl }), private val signalPrefs: SignalPrefs = SignalPrefs, private val walletObservable: Observable<HDWallet>, private val userAgent: String = "Android " + BuildConfig.APPLICATION_ID + " - " + BuildConfig.VERSION_NAME + ":" + BuildConfig.VERSION_CODE, private val scheduler: Scheduler = Schedulers.io() ) { private var chatService: ChatService? = null private var messageRegister: SofaMessageRegistration? = null private var messageReceiver: SofaMessageReceiver? = null private var messageSender: SofaMessageSender? = null private var groupManager: SofaGroupManager? = null private var connectivitySub: Subscription? = null fun initEverything(wallet: HDWallet): Completable { initChatService(wallet) initSenderAndReceiver(wallet) return initRegistrationTask() .doOnCompleted { attachConnectivityObserver() } } private fun initChatService(wallet: HDWallet) { chatService = ChatService(signalServiceUrls, wallet.ownerAddress, protocolStore, userAgent) } private fun initSenderAndReceiver(wallet: HDWallet) { val messageSender = initMessageSender(wallet, protocolStore, conversationStore, signalServiceUrls) this.messageReceiver = initMessageReceiver(wallet, protocolStore, conversationStore, signalServiceUrls, messageSender) this.groupManager = SofaGroupManager(messageSender, conversationStore, userManager) this.messageSender = messageSender } private fun initMessageSender(wallet: HDWallet, protocolStore: ProtocolStore, conversationStore: ConversationStore, signalServiceUrls: Array<SignalServiceUrl>): SofaMessageSender { return messageSender ?: SofaMessageSender( wallet.ownerAddress, protocolStore, conversationStore, signalServiceUrls ) } private fun initMessageReceiver(wallet: HDWallet, protocolStore: ProtocolStore, conversationStore: ConversationStore, signalServiceUrls: Array<SignalServiceUrl>, messageSender: SofaMessageSender): SofaMessageReceiver { return messageReceiver ?: SofaMessageReceiver( wallet.ownerAddress, walletObservable, protocolStore, conversationStore, signalServiceUrls, messageSender ) } private fun attachConnectivityObserver() { clearConnectivitySubscription() connectivitySub = baseApplication .isConnectedSubject .subscribeOn(scheduler) .filter { isConnected -> isConnected } .subscribe( { handleConnectivity() }, { LogUtil.exception("Error checking connection state", it) } ) } private fun handleConnectivity() { redoRegistrationTask() .subscribeOn(scheduler) .subscribe( { }, { LogUtil.exception("Error during registration task", it) } ) } private fun initRegistrationTask(): Completable { return if (messageRegister != null) return Completable.complete() else initSofaMessageRegistration() } private fun initSofaMessageRegistration(): Completable { val messageRegister = SofaMessageRegistration(chatService, protocolStore) this.messageRegister = messageRegister return messageRegister .registerIfNeeded() .doOnCompleted { messageReceiver?.receiveMessagesAsync() } } private fun redoRegistrationTask(): Completable { val messageRegister = messageRegister ?: SofaMessageRegistration(chatService, protocolStore) this.messageRegister = messageRegister return messageRegister .registerIfNeededWithOnboarding() .doOnCompleted { messageReceiver?.receiveMessagesAsync() } } // Will send the message to a remote peer // and store the message in the local database fun sendAndSaveMessage(receiver: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(receiver, message, SofaMessageTask.SEND_AND_SAVE) messageSender?.addNewTask(messageTask) } // Will send the message to a remote peer // but not store the message in the local database fun sendMessage(recipient: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.SEND_ONLY) messageSender?.addNewTask(messageTask) } // Will send an init message to remote peer fun sendInitMessage(sender: User, recipient: Recipient) { val initMessage = Init() .setPaymentAddress(sender.paymentAddress) .setLanguage(LocaleUtil.getLocale().language) val messageBody = SofaAdapters.get().toJson(initMessage) val sofaMessage = SofaMessage().makeNew(sender, messageBody) val messageTask = SofaMessageTask(recipient, sofaMessage, SofaMessageTask.SEND_ONLY) messageSender?.addNewTask(messageTask) } // Will store a transaction in the local database // but not send the message to a remote peer. It will also save the state as "SENDING". fun saveTransaction(user: User, message: SofaMessage) { val recipient = Recipient(user) val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.SAVE_TRANSACTION) messageSender?.addNewTask(messageTask) } // Updates a pre-existing message. fun updateMessage(recipient: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.UPDATE_MESSAGE) messageSender?.addNewTask(messageTask) } fun resendPendingMessage(sofaMessage: SofaMessage) = messageSender?.sendPendingMessage(sofaMessage) fun createConversationFromGroup(group: Group): Single<Conversation> { return groupManager ?.createConversationFromGroup(group) ?.subscribeOn(scheduler) ?: Single.error(IllegalStateException("SofaGroupManager is null while createConversationFromGroup")) } fun updateConversationFromGroup(group: Group): Completable { return groupManager ?.updateConversationFromGroup(group) ?.subscribeOn(scheduler) ?: Completable.error(IllegalStateException("SofaGroupManager is null while updateConversationFromGroup")) } fun leaveGroup(group: Group): Completable { return groupManager ?.leaveGroup(group) ?.subscribeOn(scheduler) ?: Completable.error(IllegalStateException("SofaGroupManager is null while leaveGroup")) } fun resumeMessageReceiving() { val registeredWithServer = signalPrefs.getRegisteredWithServer() if (registeredWithServer) messageReceiver?.receiveMessagesAsync() } fun tryUnregisterGcm(): Completable { return messageRegister ?.tryUnregisterGcm() ?: Completable.error(IllegalStateException("Unable to register as class hasn't been initialised yet.")) } fun forceRegisterChatGcm(): Completable { return messageRegister ?.registerChatGcm() ?: Completable.error(IllegalStateException("Unable to register as class hasn't been initialised yet.")) } fun fetchLatestMessage(): Single<IncomingMessage> { return messageReceiver ?.fetchLatestMessage() ?: Single.error(IllegalStateException("SofaMessageReceiver is null while fetchLatestMessage")) } fun clear() { clearMessageReceiver() clearMessageSender() clearConnectivitySubscription() } private fun clearMessageReceiver() { messageReceiver?.shutdown() messageReceiver = null } private fun clearMessageSender() { messageSender?.clear() messageSender = null } private fun clearConnectivitySubscription() = connectivitySub?.unsubscribe() fun deleteSession() = protocolStore.deleteAllSessions() fun disconnect() = messageReceiver?.shutdown() }
app/src/main/java/com/toshi/manager/chat/SofaMessageManager.kt
3587318379
package org.wordpress.android.fluxc.store import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult import org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox.InboxNoteDto import org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox.InboxRestClient import org.wordpress.android.fluxc.persistence.dao.InboxNotesDao import org.wordpress.android.fluxc.persistence.entity.InboxNoteWithActions import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.util.AppLog.T.API import javax.inject.Inject import javax.inject.Singleton @Singleton class WCInboxStore @Inject constructor( private val restClient: InboxRestClient, private val coroutineEngine: CoroutineEngine, private val inboxNotesDao: InboxNotesDao ) { companion object { // API has a restriction were no more than 25 notes can be deleted at once so when deleting all notes // for site we have to calculate the number of "pages" to be deleted. This only applies for deletion. const val MAX_PAGE_SIZE_FOR_DELETING_NOTES = 25 const val DEFAULT_PAGE_SIZE = 100 const val DEFAULT_PAGE = 1 val INBOX_NOTE_TYPES_FOR_APPS = arrayOf( "info", "survey", "marketing", "warning" ) } suspend fun fetchInboxNotes( site: SiteModel, page: Int = DEFAULT_PAGE, pageSize: Int = DEFAULT_PAGE_SIZE, inboxNoteTypes: Array<String> = INBOX_NOTE_TYPES_FOR_APPS ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.fetchInboxNotes(site, page, pageSize, inboxNoteTypes) when { response.isError -> WooResult(response.error) response.result != null -> { saveInboxNotes(response.result, site.siteId) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } fun observeInboxNotes(siteId: Long): Flow<List<InboxNoteWithActions>> = inboxNotesDao.observeInboxNotes(siteId) .distinctUntilChanged() suspend fun markInboxNoteAsActioned( site: SiteModel, noteId: Long, actionId: Long ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.markInboxNoteAsActioned(site, noteId, actionId) when { response.isError -> WooResult(response.error) response.result != null -> { markNoteAsActionedLocally(site.siteId, response.result) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } suspend fun deleteNote( site: SiteModel, noteId: Long ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.deleteNote(site, noteId) when { response.isError -> WooResult(response.error) response.result != null -> { inboxNotesDao.deleteInboxNote(noteId, site.siteId) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } suspend fun deleteNotesForSite( site: SiteModel, pageSize: Int = MAX_PAGE_SIZE_FOR_DELETING_NOTES, inboxNoteTypes: Array<String> = INBOX_NOTE_TYPES_FOR_APPS ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { var latestResult = WooResult(Unit) for (page in 1..getNumberOfPagesToDelete(site)) { latestResult = restClient .deleteAllNotesForSite(site, page, pageSize, inboxNoteTypes) .asWooResult() if (latestResult.isError) break } if (!latestResult.isError) { inboxNotesDao.deleteInboxNotesForSite(site.siteId) } latestResult } private fun getNumberOfPagesToDelete(site: SiteModel): Int { val sizeOfCachedNotesForSite = inboxNotesDao.getInboxNotesForSite(site.siteId).size var numberOfPagesToDelete = sizeOfCachedNotesForSite / MAX_PAGE_SIZE_FOR_DELETING_NOTES if (sizeOfCachedNotesForSite % MAX_PAGE_SIZE_FOR_DELETING_NOTES > 0) { numberOfPagesToDelete++ } return numberOfPagesToDelete } @Suppress("SpreadOperator") private suspend fun saveInboxNotes(result: Array<InboxNoteDto>, siteId: Long) { val notesWithActions = result.map { it.toInboxNoteWithActionsEntity(siteId) } inboxNotesDao.deleteAllAndInsertInboxNotes(siteId, *notesWithActions.toTypedArray()) } private suspend fun markNoteAsActionedLocally(siteId: Long, updatedNote: InboxNoteDto) { val noteWithActionsEntity = updatedNote.toInboxNoteWithActionsEntity(siteId) inboxNotesDao.updateNote(siteId, noteWithActionsEntity) } }
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCInboxStore.kt
4263643093
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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 me.raatiniemi.worker.domain.repository import me.raatiniemi.worker.domain.comparator.TimesheetDateComparator import me.raatiniemi.worker.domain.comparator.TimesheetItemComparator import me.raatiniemi.worker.domain.model.TimeInterval import me.raatiniemi.worker.domain.model.TimesheetItem import java.util.* class TimesheetInMemoryRepository(private val timeIntervals: List<TimeInterval>) : TimesheetRepository { private fun resetToStartOfDay(timeInMilliseconds: Long): Date { val calendar = Calendar.getInstance() calendar.timeInMillis = timeInMilliseconds calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) return calendar.time } // TODO: Implement proper support for pagination. private fun filterAndBuildResult(predicate: (TimeInterval) -> Boolean) : TreeMap<Date, Set<TimesheetItem>> { val matchingTimeIntervals = timeIntervals.filter { predicate(it) } .groupBy { resetToStartOfDay(it.startInMilliseconds) } val timeIntervals = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()) matchingTimeIntervals.forEach { timeIntervals[it.key] = it.value .map { timeInterval -> TimesheetItem(timeInterval) } .toSortedSet(TimesheetItemComparator()) } return timeIntervals } override fun getTimesheet( projectId: Long, pageRequest: PageRequest ): Map<Date, Set<TimesheetItem>> { return filterAndBuildResult { it.projectId == projectId } } override fun getTimesheetWithoutRegisteredEntries( projectId: Long, pageRequest: PageRequest ): Map<Date, Set<TimesheetItem>> { return filterAndBuildResult { it.projectId == projectId && !it.isRegistered } } }
core-test/src/main/java/me/raatiniemi/worker/domain/repository/TimesheetInMemoryRepository.kt
3524014775
package kotlinx.serialization.test import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.json.* import java.io.ByteArrayOutputStream actual fun <T> Json.encodeViaStream( serializer: SerializationStrategy<T>, value: T ): String { val output = ByteArrayOutputStream() encodeToStream(serializer, value, output) return output.toString(Charsets.UTF_8.name()) } actual fun <T> Json.decodeViaStream( serializer: DeserializationStrategy<T>, input: String ): T = decodeFromStream(serializer, input.byteInputStream())
formats/json-tests/jvmTest/src/kotlinx/serialization/test/JsonHelpers.kt
4114177721
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.modules import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlin.test.* open class ContextualGenericsTest { // This is a 3rd party class that we can't annotate as @Serializable data class ThirdPartyBox<T>(val contents: T) // This is the item that we put in the ThirdPartyBox, we control it, so can annotate it @Serializable data class Item(val name: String) // This is the another item that we put in the ThirdPartyBox, we control it, so can annotate it @Serializable data class AnotherItem(val value: Int) // The serializer for the ThirdPartyBox<T> class ThirdPartyBoxSerializer<T>(dataSerializer: KSerializer<T>) : KSerializer<ThirdPartyBox<T>> { @Serializable data class BoxSurrogate<T>(val contents: T) private val strategy = BoxSurrogate.serializer(dataSerializer) override val descriptor: SerialDescriptor = strategy.descriptor override fun deserialize(decoder: Decoder): ThirdPartyBox<T> { return ThirdPartyBox(decoder.decodeSerializableValue(strategy).contents) } override fun serialize(encoder: Encoder, value: ThirdPartyBox<T>) { encoder.encodeSerializableValue(strategy, BoxSurrogate(value.contents)) } } // Register contextual serializer for ThirdPartyBox<Item> protected val boxWithItemSerializer = ThirdPartyBoxSerializer(Item.serializer()) protected val serializersModuleStatic = SerializersModule { contextual(boxWithItemSerializer) } protected val serializersModuleWithProvider = SerializersModule { contextual(ThirdPartyBox::class) { args -> ThirdPartyBoxSerializer(args[0]) } } @Test fun testSurrogateSerializerFoundForGenericWithKotlinType() { val serializer = serializersModuleStatic.serializer<ThirdPartyBox<Item>>() assertEquals(boxWithItemSerializer.descriptor, serializer.descriptor) } @Test fun testSerializerFoundForContextualGeneric() { val serializerA = serializersModuleWithProvider.serializer<ThirdPartyBox<Item>>() assertEquals(Item.serializer().descriptor, serializerA.descriptor.getElementDescriptor(0)) val serializerB = serializersModuleWithProvider.serializer<ThirdPartyBox<AnotherItem>>() assertEquals(AnotherItem.serializer().descriptor, serializerB.descriptor.getElementDescriptor(0)) } @Test fun testModuleProvidesMultipleGenericSerializers() { fun checkFor(serial: KSerializer<*>) { val serializer = serializersModuleWithProvider.getContextual(ThirdPartyBox::class, listOf(serial))?.descriptor assertEquals(serial.descriptor, serializer?.getElementDescriptor(0)) } checkFor(Item.serializer()) checkFor(AnotherItem.serializer()) } }
core/commonTest/src/kotlinx/serialization/modules/ContextualGenericsTest.kt
323630673
package com.song.general.gossip.net.codec.encoder import com.song.general.gossip.net.Message import io.netty.buffer.ByteBuf import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.MessageToByteEncoder /** * Created by song on 2017/8/20. */ class MessageEncoder : MessageToByteEncoder<Message>() { @Throws(Exception::class) override fun encode(channelHandlerContext: ChannelHandlerContext, message: Message, byteBuf: ByteBuf) { } }
general-gossip/src/main/java/com/song/general/gossip/net/codec/encoder/MessageEncoder.kt
612265674
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.descriptors import kotlinx.serialization.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlin.reflect.* /** * Builder for [SerialDescriptor]. * The resulting descriptor will be uniquely identified by the given [serialName], [typeParameters] and * elements structure described in [builderAction] function. * * Example: * ``` * // Class with custom serializer and custom serial descriptor * class Data( * val intField: Int, // This field is ignored by custom serializer * val longField: Long, // This field is written as long, but in serialized form is named as "_longField" * val stringList: List<String> // This field is written as regular list of strings * val nullableInt: Int? * ) * // Descriptor for such class: * SerialDescriptor("my.package.Data") { * // intField is deliberately ignored by serializer -- not present in the descriptor as well * element<Long>("_longField") // longField is named as _longField * element("stringField", listSerialDescriptor<String>()) * element("nullableInt", serialDescriptor<Int>().nullable) * } * ``` * * Example for generic classes: * ``` * @Serializable(CustomSerializer::class) * class BoxedList<T>(val list: List<T>) * * class CustomSerializer<T>(tSerializer: KSerializer<T>): KSerializer<BoxedList<T>> { * // here we use tSerializer.descriptor because it represents T * override val descriptor = SerialDescriptor("pkg.BoxedList", CLASS, tSerializer.descriptor) { * // here we have to wrap it with List first, because property has type List<T> * element("list", ListSerializer(tSerializer).descriptor) // or listSerialDescriptor(tSerializer.descriptor) * } * } * ``` */ @Suppress("FunctionName") @OptIn(ExperimentalSerializationApi::class) public fun buildClassSerialDescriptor( serialName: String, vararg typeParameters: SerialDescriptor, builderAction: ClassSerialDescriptorBuilder.() -> Unit = {} ): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } val sdBuilder = ClassSerialDescriptorBuilder(serialName) sdBuilder.builderAction() return SerialDescriptorImpl( serialName, StructureKind.CLASS, sdBuilder.elementNames.size, typeParameters.toList(), sdBuilder ) } /** * Factory to create a trivial primitive descriptors. * Primitive descriptors should be used when the serialized form of the data has a primitive form, for example: * ``` * object LongAsStringSerializer : KSerializer<Long> { * override val descriptor: SerialDescriptor = * PrimitiveDescriptor("kotlinx.serialization.LongAsStringSerializer", PrimitiveKind.STRING) * * override fun serialize(encoder: Encoder, value: Long) { * encoder.encodeString(value.toString()) * } * * override fun deserialize(decoder: Decoder): Long { * return decoder.decodeString().toLong() * } * } * ``` */ public fun PrimitiveSerialDescriptor(serialName: String, kind: PrimitiveKind): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } return PrimitiveDescriptorSafe(serialName, kind) } /** * Factory to create a new descriptor that is identical to [original] except that the name is equal to [serialName]. * Should be used when you want to serialize a type as another non-primitive type. * Don't use this if you want to serialize a type as a primitive value, use [PrimitiveSerialDescriptor] instead. * * Example: * ``` * @Serializable(CustomSerializer::class) * class CustomType(val a: Int, val b: Int, val c: Int) * * class CustomSerializer: KSerializer<CustomType> { * override val descriptor = SerialDescriptor("CustomType", IntArraySerializer().descriptor) * * override fun serialize(encoder: Encoder, value: CustomType) { * encoder.encodeSerializableValue(IntArraySerializer(), intArrayOf(value.a, value.b, value.c)) * } * * override fun deserialize(decoder: Decoder): CustomType { * val array = decoder.decodeSerializableValue(IntArraySerializer()) * return CustomType(array[0], array[1], array[2]) * } * } * ``` */ @ExperimentalSerializationApi public fun SerialDescriptor(serialName: String, original: SerialDescriptor): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } require(original.kind !is PrimitiveKind) { "For primitive descriptors please use 'PrimitiveSerialDescriptor' instead" } require(serialName != original.serialName) { "The name of the wrapped descriptor ($serialName) cannot be the same as the name of the original descriptor (${original.serialName})" } return WrappedSerialDescriptor(serialName, original) } @OptIn(ExperimentalSerializationApi::class) internal class WrappedSerialDescriptor(override val serialName: String, original: SerialDescriptor) : SerialDescriptor by original /** * An unsafe alternative to [buildClassSerialDescriptor] that supports an arbitrary [SerialKind]. * This function is left public only for migration of pre-release users and is not intended to be used * as generally-safe and stable mechanism. Beware that it can produce inconsistent or non spec-compliant instances. * * If you end up using this builder, please file an issue with your use-case in kotlinx.serialization */ @InternalSerializationApi @OptIn(ExperimentalSerializationApi::class) public fun buildSerialDescriptor( serialName: String, kind: SerialKind, vararg typeParameters: SerialDescriptor, builder: ClassSerialDescriptorBuilder.() -> Unit = {} ): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } require(kind != StructureKind.CLASS) { "For StructureKind.CLASS please use 'buildClassSerialDescriptor' instead" } val sdBuilder = ClassSerialDescriptorBuilder(serialName) sdBuilder.builder() return SerialDescriptorImpl(serialName, kind, sdBuilder.elementNames.size, typeParameters.toList(), sdBuilder) } /** * Retrieves descriptor of type [T] using reified [serializer] function. */ public inline fun <reified T> serialDescriptor(): SerialDescriptor = serializer<T>().descriptor /** * Retrieves descriptor of type associated with the given [KType][type] */ public fun serialDescriptor(type: KType): SerialDescriptor = serializer(type).descriptor /** * Creates a descriptor for the type `List<T>` where `T` is the type associated with [elementDescriptor]. */ @ExperimentalSerializationApi public fun listSerialDescriptor(elementDescriptor: SerialDescriptor): SerialDescriptor { return ArrayListClassDesc(elementDescriptor) } /** * Creates a descriptor for the type `List<T>`. */ @ExperimentalSerializationApi public inline fun <reified T> listSerialDescriptor(): SerialDescriptor { return listSerialDescriptor(serializer<T>().descriptor) } /** * Creates a descriptor for the type `Map<K, V>` where `K` and `V` are types * associated with [keyDescriptor] and [valueDescriptor] respectively. */ @ExperimentalSerializationApi public fun mapSerialDescriptor( keyDescriptor: SerialDescriptor, valueDescriptor: SerialDescriptor ): SerialDescriptor { return HashMapClassDesc(keyDescriptor, valueDescriptor) } /** * Creates a descriptor for the type `Map<K, V>`. */ @ExperimentalSerializationApi public inline fun <reified K, reified V> mapSerialDescriptor(): SerialDescriptor { return mapSerialDescriptor(serializer<K>().descriptor, serializer<V>().descriptor) } /** * Creates a descriptor for the type `Set<T>` where `T` is the type associated with [elementDescriptor]. */ @ExperimentalSerializationApi public fun setSerialDescriptor(elementDescriptor: SerialDescriptor): SerialDescriptor { return HashSetClassDesc(elementDescriptor) } /** * Creates a descriptor for the type `Set<T>`. */ @ExperimentalSerializationApi public inline fun <reified T> setSerialDescriptor(): SerialDescriptor { return setSerialDescriptor(serializer<T>().descriptor) } /** * Returns new serial descriptor for the same type with [isNullable][SerialDescriptor.isNullable] * property set to `true`. */ @OptIn(ExperimentalSerializationApi::class) public val SerialDescriptor.nullable: SerialDescriptor get() { if (this.isNullable) return this return SerialDescriptorForNullable(this) } /** * Builder for [SerialDescriptor] for user-defined serializers. * * Both explicit builder functions and implicit (using reified type-parameters) are present and are equivalent. * For example, `element<Int?>("nullableIntField")` is indistinguishable from * `element("nullableIntField", IntSerializer.descriptor.nullable)` and * from `element("nullableIntField", descriptor<Int?>)`. * * Please refer to [SerialDescriptor] builder function for a complete example. */ public class ClassSerialDescriptorBuilder internal constructor( public val serialName: String ) { /** * Indicates that serializer associated with the current serial descriptor * support nullable types, meaning that it should declare nullable type * in its [KSerializer] type parameter and handle nulls during encoding and decoding. */ @ExperimentalSerializationApi @Deprecated("isNullable inside buildSerialDescriptor is deprecated. Please use SerialDescriptor.nullable extension on a builder result.", level = DeprecationLevel.ERROR) public var isNullable: Boolean = false /** * [Serial][SerialInfo] annotations on a target type. */ @ExperimentalSerializationApi public var annotations: List<Annotation> = emptyList() internal val elementNames: MutableList<String> = ArrayList() private val uniqueNames: MutableSet<String> = HashSet() internal val elementDescriptors: MutableList<SerialDescriptor> = ArrayList() internal val elementAnnotations: MutableList<List<Annotation>> = ArrayList() internal val elementOptionality: MutableList<Boolean> = ArrayList() /** * Add an element with a given [name][elementName], [descriptor], * type annotations and optionality the resulting descriptor. * * Example of usage: * ``` * class Data( * val intField: Int? = null, // Optional, has default value * @ProtoNumber(1) val longField: Long * ) * * // Corresponding descriptor * SerialDescriptor("package.Data") { * element<Int?>("intField", isOptional = true) * element<Long>("longField", annotations = listOf(protoIdAnnotationInstance)) * } * ``` */ public fun element( elementName: String, descriptor: SerialDescriptor, annotations: List<Annotation> = emptyList(), isOptional: Boolean = false ) { require(uniqueNames.add(elementName)) { "Element with name '$elementName' is already registered" } elementNames += elementName elementDescriptors += descriptor elementAnnotations += annotations elementOptionality += isOptional } } /** * A reified version of [element] function that * extract descriptor using `serializer<T>().descriptor` call with all the restrictions of `serializer<T>().descriptor`. */ public inline fun <reified T> ClassSerialDescriptorBuilder.element( elementName: String, annotations: List<Annotation> = emptyList(), isOptional: Boolean = false ) { val descriptor = serializer<T>().descriptor element(elementName, descriptor, annotations, isOptional) } @OptIn(ExperimentalSerializationApi::class) internal class SerialDescriptorImpl( override val serialName: String, override val kind: SerialKind, override val elementsCount: Int, typeParameters: List<SerialDescriptor>, builder: ClassSerialDescriptorBuilder ) : SerialDescriptor, CachedNames { override val annotations: List<Annotation> = builder.annotations override val serialNames: Set<String> = builder.elementNames.toHashSet() private val elementNames: Array<String> = builder.elementNames.toTypedArray() private val elementDescriptors: Array<SerialDescriptor> = builder.elementDescriptors.compactArray() private val elementAnnotations: Array<List<Annotation>> = builder.elementAnnotations.toTypedArray() private val elementOptionality: BooleanArray = builder.elementOptionality.toBooleanArray() private val name2Index: Map<String, Int> = elementNames.withIndex().map { it.value to it.index }.toMap() private val typeParametersDescriptors: Array<SerialDescriptor> = typeParameters.compactArray() private val _hashCode: Int by lazy { hashCodeImpl(typeParametersDescriptors) } override fun getElementName(index: Int): String = elementNames.getChecked(index) override fun getElementIndex(name: String): Int = name2Index[name] ?: CompositeDecoder.UNKNOWN_NAME override fun getElementAnnotations(index: Int): List<Annotation> = elementAnnotations.getChecked(index) override fun getElementDescriptor(index: Int): SerialDescriptor = elementDescriptors.getChecked(index) override fun isElementOptional(index: Int): Boolean = elementOptionality.getChecked(index) override fun equals(other: Any?): Boolean = equalsImpl(other) { otherDescriptor: SerialDescriptorImpl -> typeParametersDescriptors.contentEquals( otherDescriptor.typeParametersDescriptors ) } override fun hashCode(): Int = _hashCode override fun toString(): String { return (0 until elementsCount).joinToString(", ", prefix = "$serialName(", postfix = ")") { getElementName(it) + ": " + getElementDescriptor(it).serialName } } }
core/commonMain/src/kotlinx/serialization/descriptors/SerialDescriptors.kt
467184985
package me.raino.faucet.api.region import com.flowpowered.math.vector.Vector3d class Sphere(val center: Vector3d, val radius: Double) : Region { override fun contains(point: Vector3d): Boolean = center.distanceSquared(point) <= radius.sqrd() }
src/main/kotlin/me/raino/faucet/api/region/Sphere.kt
3046758329
package pref.impl import android.content.Context import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.not import org.junit.Test import pref.BasePrefTest import pref.SimplePref import pref.ext.booleanPref import pref.ext.floatPref import pref.ext.intPref import pref.ext.longPref import pref.ext.stringPref import pref.ext.stringSetPref internal class GenericPrefTest : BasePrefTest<GenericPrefTest.TestGenericPref>() { override fun setupTestPref(context: Context) = TestGenericPref(context) companion object { internal const val DEFAULT_VALUE_BOOLEAN = true internal const val DEFAULT_VALUE_FLOAT = 1.0F internal const val DEFAULT_VALUE_INT = 1 internal const val DEFAULT_VALUE_LONG = 1L internal const val DEFAULT_VALUE_STRING = "Ok" internal val DEFAULT_VALUE_STRING_SET = setOf("Ok", "Set") } internal class TestGenericPref(context: Context) : SimplePref(context, "TestGenericPref") { var defaultBoolean by booleanPref(default = DEFAULT_VALUE_BOOLEAN) var defaultFloat by floatPref(default = DEFAULT_VALUE_FLOAT) var defaultInt by intPref(default = DEFAULT_VALUE_INT) var defaultLong by longPref(default = DEFAULT_VALUE_LONG) var defaultString by stringPref(default = DEFAULT_VALUE_STRING) var defaultStringSet by stringSetPref(default = DEFAULT_VALUE_STRING_SET) } @Test fun `Test booleanPref default value and set new value`() { assertThat(testPref.defaultBoolean, `is`(DEFAULT_VALUE_BOOLEAN)) testPref.defaultBoolean = DEFAULT_VALUE_BOOLEAN.not() assertThat(testPref.defaultBoolean, `is`(not(DEFAULT_VALUE_BOOLEAN))) } @Test fun `Test floatPref default value and set new value`() { assertThat(testPref.defaultFloat, `is`(DEFAULT_VALUE_FLOAT)) testPref.defaultFloat += DEFAULT_VALUE_FLOAT assertThat(testPref.defaultFloat, `is`(not(DEFAULT_VALUE_FLOAT))) } @Test fun `Test intPref default value and set new value`() { assertThat(testPref.defaultInt, `is`(DEFAULT_VALUE_INT)) testPref.defaultInt += DEFAULT_VALUE_INT assertThat(testPref.defaultInt, `is`(not(DEFAULT_VALUE_INT))) } @Test fun `Test longPref default value and set new value`() { assertThat(testPref.defaultLong, `is`(DEFAULT_VALUE_LONG)) testPref.defaultLong += DEFAULT_VALUE_LONG assertThat(testPref.defaultLong, `is`(not(DEFAULT_VALUE_LONG))) } @Test fun `Test stringPref default value and set new value`() { assertThat(testPref.defaultString, `is`(DEFAULT_VALUE_STRING)) testPref.defaultString = "New Value" assertThat(testPref.defaultString, `is`(not(DEFAULT_VALUE_STRING))) } @Test fun `Test stringSetPref default value and set new value`() { assertThat(testPref.defaultStringSet, `is`(DEFAULT_VALUE_STRING_SET)) testPref.defaultStringSet += "New Item" assertThat(testPref.defaultStringSet, `is`(not(DEFAULT_VALUE_STRING_SET))) } }
pref/src/test/java/pref/impl/GenericPrefTest.kt
476056795
package name.kropp.intellij.makefile.toolWindow import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.* import com.intellij.psi.search.* import com.intellij.ui.treeStructure.* import name.kropp.intellij.makefile.* class MakefileToolWindowGoToTargetAction(private val tree: Tree, private val project: Project) : AnAction("Go to target", "Go to target", MakefileTargetIcon) { override fun actionPerformed(event: AnActionEvent) { val selectedNodes = tree.getSelectedNodes(MakefileTargetNode::class.java, {true}) if (selectedNodes.any()) { val selected = selectedNodes.first() val elements = MakefileTargetIndex.get(selected.name, project, GlobalSearchScope.fileScope(selected.parent.psiFile)) elements.first().navigate(true) } } }
src/main/kotlin/name/kropp/intellij/makefile/toolWindow/MakefileToolWindowGoToTargetAction.kt
413244501
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.actionSystem.ex import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.configurationStore.SchemeDataHolder import com.intellij.ide.IdeBundle import com.intellij.ide.actions.QuickSwitchSchemeAction import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.BundledQuickListsProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import gnu.trove.THashSet import java.util.function.Function class QuickListsManager(private val myActionManager: ActionManager, schemeManagerFactory: SchemeManagerFactory) : ApplicationComponent { private val mySchemeManager: SchemeManager<QuickList> init { mySchemeManager = schemeManagerFactory.create("quicklists", object : LazySchemeProcessor<QuickList, QuickList>(QuickList.DISPLAY_NAME_TAG) { override fun createScheme(dataHolder: SchemeDataHolder<QuickList>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): QuickList { val item = QuickList() item.readExternal(dataHolder.read()) dataHolder.updateDigest(item) return item } }, presentableName = IdeBundle.message("quick.lists.presentable.name")) } companion object { @JvmStatic val instance: QuickListsManager get() = ApplicationManager.getApplication().getComponent(QuickListsManager::class.java) } override fun initComponent() { for (provider in BundledQuickListsProvider.EP_NAME.extensionList) { for (path in provider.bundledListsRelativePaths) { mySchemeManager.loadBundledScheme(path, provider) } } mySchemeManager.loadSchemes() registerActions() } val schemeManager: SchemeManager<QuickList> get() = mySchemeManager val allQuickLists: Array<QuickList> get() { return mySchemeManager.allSchemes.toTypedArray() } private fun registerActions() { // to prevent exception if 2 or more targets have the same name val registeredIds = THashSet<String>() for (scheme in mySchemeManager.allSchemes) { val actionId = scheme.actionId if (registeredIds.add(actionId)) { myActionManager.registerAction(actionId, InvokeQuickListAction(scheme)) } } } private fun unregisterActions() { for (oldId in myActionManager.getActionIds(QuickList.QUICK_LIST_PREFIX)) { myActionManager.unregisterAction(oldId) } } // used by external plugin fun setQuickLists(quickLists: List<QuickList>) { unregisterActions() mySchemeManager.setSchemes(quickLists) registerActions() } } private class InvokeQuickListAction(private val myQuickList: QuickList) : QuickSwitchSchemeAction() { init { myActionPlace = ActionPlaces.ACTION_PLACE_QUICK_LIST_POPUP_ACTION templatePresentation.description = myQuickList.description templatePresentation.setText(myQuickList.name, false) } override fun fillActions(project: Project, group: DefaultActionGroup, dataContext: DataContext) { val actionManager = ActionManager.getInstance() for (actionId in myQuickList.actionIds) { if (QuickList.SEPARATOR_ID == actionId) { group.addSeparator() } else { val action = actionManager.getAction(actionId) if (action != null) { group.add(action) } } } } }
platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.kt
436214474
/* * 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 com.intellij.vcs.log.history import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Pair import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.history.VcsCachingHistory import com.intellij.openapi.vcs.history.VcsFileRevision import com.intellij.openapi.vcs.history.VcsFileRevisionEx import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.data.* import com.intellij.vcs.log.data.index.VcsLogModifiableIndex import com.intellij.vcs.log.graph.GraphCommit import com.intellij.vcs.log.graph.GraphCommitImpl import com.intellij.vcs.log.graph.PermanentGraph import com.intellij.vcs.log.graph.VisibleGraph import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.graph.impl.facade.VisibleGraphImpl import com.intellij.vcs.log.graph.utils.LinearGraphUtils import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.impl.VcsLogFilterCollectionImpl import com.intellij.vcs.log.impl.VcsLogRevisionFilterImpl import com.intellij.vcs.log.util.StopWatch import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.CommitCountStage import com.intellij.vcs.log.visible.VcsLogFilterer import com.intellij.vcs.log.visible.VcsLogFiltererImpl import com.intellij.vcs.log.visible.VcsLogFiltererImpl.matchesNothing import com.intellij.vcs.log.visible.VisiblePack import com.intellij.vcsUtil.VcsUtil internal class FileHistoryFilterer(logData: VcsLogData) : VcsLogFilterer { private val project = logData.project private val logProviders = logData.logProviders private val storage = logData.storage private val index = logData.index private val indexDataGetter = index.dataGetter!! private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache, logData.commitDetailsGetter, index) override fun filter(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> { val filePath = getFilePath(filters) ?: return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) val root = VcsUtil.getVcsRootFor(project, filePath)!! return MyWorker(root, filePath, getHash(filters)).filter(dataPack, sortType, filters, commitCount) } override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean { return getFilePath(filters)?.run { !isDirectory } ?: false } private inner class MyWorker constructor(private val root: VirtualFile, private val filePath: FilePath, private val hash: Hash?) { fun filter(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> { val start = System.currentTimeMillis() if (index.isIndexed(root) && (dataPack.isFull || filePath.isDirectory)) { val visiblePack = filterWithIndex(dataPack, sortType, filters) LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index") checkNotEmpty(dataPack, visiblePack, true) return Pair.create(visiblePack, commitCount) } if (filePath.isDirectory) { return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs -> if (vcs.vcsHistoryProvider != null) { return@filter try { val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters) LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with history provider") checkNotEmpty(dataPack, visiblePack, false) Pair.create(visiblePack, commitCount) } catch (e: VcsException) { LOG.error(e) vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } } } LOG.warn("Could not find vcs or history provider for file $filePath") return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean) { if (!dataPack.isFull) { LOG.debug("Data pack is not full while computing file history for $filePath\n" + "Found ${visiblePack.visibleGraph.visibleCommitCount} commits") } else if (visiblePack.visibleGraph.visibleCommitCount == 0) { LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath") } } @Throws(VcsException::class) private fun filterWithProvider(vcs: AbstractVcs<*>, dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection): VisiblePack { val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null val revisions = VcsCachingHistory.collect(vcs, filePath, revisionNumber) if (revisions.isEmpty()) return VisiblePack.EMPTY if (dataPack.isFull) { val pathsMap = ContainerUtil.newHashMap<Int, FilePath>() for (revision in revisions) { pathsMap[getIndex(revision)] = (revision as VcsFileRevisionEx).path } val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, null, pathsMap.keys) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, pathsMap) } val commits = ContainerUtil.newArrayListWithCapacity<GraphCommit<Int>>(revisions.size) val pathsMap = ContainerUtil.newHashMap<Int, FilePath>() for (revision in revisions) { val index = getIndex(revision) pathsMap[index] = (revision as VcsFileRevisionEx).path commits.add(GraphCommitImpl.createCommit(index, emptyList(), revision.getRevisionDate().time)) } val refs = getFilteredRefs(dataPack) val providers = ContainerUtil.newHashMap(Pair.create<VirtualFile, VcsLogProvider>(root, logProviders[root])) val fakeDataPack = DataPack.build(commits, refs, providers, storage, false) val visibleGraph = vcsLogFilterer.createVisibleGraph(fakeDataPack, sortType, null, null/*no need to filter here, since we do not have any extra commits in this pack*/) return FileHistoryVisiblePack(fakeDataPack, visibleGraph, false, filters, pathsMap) } private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> { val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage) return mapOf(kotlin.Pair(root, compressedRefs)) } private fun getIndex(revision: VcsFileRevision): Int { return storage.getCommitIndex(HashImpl.build(revision.revisionNumber.asString()), root) } private fun filterWithIndex(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection): VisiblePack { val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters) val data = indexDataGetter.buildFileNamesData(filePath) val permanentGraph = dataPack.permanentGraph if (permanentGraph !is PermanentGraphImpl) { val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, matchingHeads, data.commits) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, data.buildPathsMap()) } if (matchesNothing(matchingHeads) || data.isEmpty) { return VisiblePack.EMPTY } val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) } val historyBuilder = FileHistoryBuilder(commit, filePath, data) val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.commits, historyBuilder) if (!filePath.isDirectory) reindexFirstCommitsIfNeeded(visibleGraph) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, historyBuilder.pathsMap) } private fun reindexFirstCommitsIfNeeded(graph: VisibleGraph<Int>) { // we may not have renames big commits, may need to reindex them if (graph is VisibleGraphImpl<*>) { val liteLinearGraph = LinearGraphUtils.asLiteLinearGraph((graph as VisibleGraphImpl<*>).linearGraph) for (row in 0 until liteLinearGraph.nodesCount()) { // checking if commit is a root commit (which means file was added or renamed there) if (liteLinearGraph.getNodes(row, LiteLinearGraph.NodeFilter.DOWN).isEmpty() && index is VcsLogModifiableIndex) { index.reindexWithRenames(graph.getRowInfo(row).commit, root) } } } } private fun getHead(pack: DataPack): Hash? { val refs = pack.refsModel.allRefsByRoot[root] val headOptional = refs!!.streamBranches().filter { br -> br.name == "HEAD" }.findFirst() if (headOptional.isPresent) { val head = headOptional.get() assert(head.root == root) return head.commitHash } return null } } private fun getFilePath(filters: VcsLogFilterCollection): FilePath? { val filter = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter ?: return null return filter.files.singleOrNull() } private fun getHash(filters: VcsLogFilterCollection): Hash? { val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER) ?: return null return revisionFilter.heads.singleOrNull()?.hash } companion object { private val LOG = Logger.getInstance(FileHistoryFilterer::class.java) @JvmStatic fun createFilters(path: FilePath, revision: Hash?, root: VirtualFile, showAllBranches: Boolean): VcsLogFilterCollection { val fileFilter = VcsLogStructureFilterImpl(setOf(path)) if (revision != null) { val revisionFilter = VcsLogRevisionFilterImpl.fromCommit(CommitId(revision, root)) return VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder(fileFilter, revisionFilter).build() } val branchFilter = if (showAllBranches) null else VcsLogBranchFilterImpl.fromBranch("HEAD") return VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder(fileFilter, branchFilter).build() } } }
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt
436166967
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sarangnamu.common.arch.viewmodel import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/> */ open class DismissViewModel: ViewModel() { protected lateinit var dismiss: MutableLiveData<Boolean> open fun init() { dismiss = MutableLiveData() } open fun positiveClose() { dismiss.value = true } open fun negativeClose() { dismiss.value = false } } open class DismissAndroidViewModel(app: Application) : AndroidViewModel(app) { protected lateinit var dismiss: MutableLiveData<Boolean> open fun init() { dismiss = MutableLiveData() } open fun positiveClose() { dismiss.value = true } open fun negativeClose() { dismiss.value = false } }
library/src/main/java/net/sarangnamu/common/arch/viewmodel/DismissViewModel.kt
165278389
/* * Copyright 2020-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.TransactionResult import io.lettuce.core.api.reactive.RedisTransactionalReactiveCommands import kotlinx.coroutines.reactive.awaitLast /** * Coroutine executed commands (based on reactive commands) for Transactions. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisTransactionalCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisTransactionalReactiveCommands<K, V>) : RedisTransactionalCoroutinesCommands<K, V> { override suspend fun discard(): String = ops.discard().awaitLast() override suspend fun exec(): TransactionResult = ops.exec().awaitLast() override suspend fun multi(): String = ops.multi().awaitLast() override suspend fun watch(vararg keys: K): String = ops.watch(*keys).awaitLast() override suspend fun unwatch(): String = ops.unwatch().awaitLast() }
src/main/kotlin/io/lettuce/core/api/coroutines/RedisTransactionalCoroutinesCommandsImpl.kt
4272912801
package io.clappr.player.components import android.os.Bundle import android.view.View import android.widget.FrameLayout import io.clappr.player.base.InternalEvent import io.clappr.player.base.Options import io.clappr.player.base.UIObject import io.clappr.player.log.Logger import io.clappr.player.plugin.Loader import io.clappr.player.plugin.Plugin import io.clappr.player.plugin.core.UICorePlugin import io.clappr.player.shared.SharedData import io.clappr.player.utils.Environment class Core(options: Options) : UIObject() { enum class FullscreenState { EMBEDDED, FULLSCREEN } var fullscreenState: FullscreenState = FullscreenState.EMBEDDED set(value) { if (value != fullscreenState) { val beforeEvent: InternalEvent val afterEvent: InternalEvent if (value == FullscreenState.FULLSCREEN) { beforeEvent = InternalEvent.WILL_ENTER_FULLSCREEN afterEvent = InternalEvent.DID_ENTER_FULLSCREEN } else { beforeEvent = InternalEvent.WILL_EXIT_FULLSCREEN afterEvent = InternalEvent.DID_EXIT_FULLSCREEN } trigger(beforeEvent.value) field = value trigger(afterEvent.value) } } val plugins: List<Plugin> get() = internalPlugins private val internalPlugins: MutableList<Plugin> val containers: MutableList<Container> = mutableListOf() var activeContainer: Container? = null set(value) { if (activeContainer != value) { activeContainer?.stopListening() trigger(InternalEvent.WILL_CHANGE_ACTIVE_CONTAINER.value) field = value activeContainer?.on(InternalEvent.WILL_CHANGE_PLAYBACK.value ) { bundle: Bundle? -> trigger( InternalEvent.WILL_CHANGE_ACTIVE_PLAYBACK.value, bundle) } activeContainer?.on(InternalEvent.DID_CHANGE_PLAYBACK.value ) { bundle: Bundle? -> trigger( InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value, bundle) } trigger(InternalEvent.DID_CHANGE_ACTIVE_CONTAINER.value) } } val activePlayback: Playback? get() = activeContainer?.playback private val frameLayout: FrameLayout get() = view as FrameLayout var options: Options = options set(options) { field = options trigger(InternalEvent.DID_UPDATE_OPTIONS.value) updateContainerOptions(options) } val environment = Environment() val sharedData = SharedData() private fun updateContainerOptions(options: Options) { containers.forEach { it.options = options } } override val viewClass: Class<*> get() = FrameLayout::class.java private val layoutChangeListener = View.OnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> val horizontalChange = (right - left) != (oldRight - oldLeft) val verticalChange = (bottom - top) != (oldBottom - oldTop) if (horizontalChange || verticalChange) { trigger(InternalEvent.DID_RESIZE.value) } } private val orientationChangeListener = OrientationChangeListener(this) init { internalPlugins = Loader.loadPlugins(this).toMutableList() val container = Container(options) containers.add(container) } fun load() { activeContainer = containers.first() trigger(InternalEvent.WILL_LOAD_SOURCE.value) options.source?.let { activeContainer?.load(it, options.mimeType) } trigger(InternalEvent.DID_LOAD_SOURCE.value) } fun destroy() { trigger(InternalEvent.WILL_DESTROY.value) containers.forEach { it.destroy() } containers.clear() internalPlugins.forEach { handlePluginAction( { it.destroy() }, "Plugin ${it.javaClass.simpleName} crashed during destroy") } internalPlugins.clear() stopListening() frameLayout.removeOnLayoutChangeListener(layoutChangeListener) orientationChangeListener.disable() trigger(InternalEvent.DID_DESTROY.value) } override fun render(): Core { frameLayout.removeAllViews() containers.forEach { frameLayout.addView(it.view) it.render() } internalPlugins.filterIsInstance(UICorePlugin::class.java).forEach { frameLayout.addView(it.view) handlePluginAction( { it.render() }, "Plugin ${it.javaClass.simpleName} crashed during render") } frameLayout.removeOnLayoutChangeListener(layoutChangeListener) frameLayout.addOnLayoutChangeListener(layoutChangeListener) orientationChangeListener.enable() return this } private fun handlePluginAction(action: () -> Unit, errorMessage: String) { try { action.invoke() } catch (error: Exception) { Logger.error(Core::class.java.simpleName, errorMessage, error) } } }
clappr/src/main/kotlin/io/clappr/player/components/Core.kt
3793330343
/* * Copyright 2019 Ericsson Research and others. * * 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 eu.scott.warehouse.lib.trs import org.apache.jena.rdf.model.Model import org.eclipse.lyo.core.trs.Creation import org.eclipse.lyo.core.trs.Deletion import org.eclipse.lyo.core.trs.Modification import java.net.URI interface ITrsLogAppender { fun appendCreationEvent(changed: URI, model: Model, twinKind: String, twinId: String): Creation fun appendModificationEvent(changed: URI, twinKind: String, twinId: String, model: Model): Modification fun appendDeletionEvent(changed: URI, twinKind: String, twinId: String, model: Model): Deletion companion object { val pageSize = 200 fun logGraphFor(twinKind: String, twinId: String, orderId: Int): URI { val page = pageNo(orderId) return URI.create("http://twins.svc/ng/trs/log/$twinKind/$twinId/$page") } private fun pageNo(orderId: Int) = orderId / pageSize + 1 } }
lyo-services/lib-common/src/main/java/eu/scott/warehouse/lib/trs/ITrsLogAppender.kt
1921727781
package com.task.ui.component.news import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import androidx.annotation.VisibleForTesting import androidx.recyclerview.widget.LinearLayoutManager import androidx.test.espresso.IdlingResource import butterknife.OnClick import com.task.App import com.task.R import com.task.data.remote.dto.NewsItem import com.task.ui.base.BaseActivity import com.task.ui.component.details.DetailsActivity import com.task.utils.Constants import com.task.utils.EspressoIdlingResource import kotlinx.android.synthetic.main.home_activity.* import org.jetbrains.anko.design.snackbar import org.jetbrains.anko.intentFor import javax.inject.Inject /** * Created by AhmedEltaher on 5/12/2016 */ class HomeActivity : BaseActivity(), HomeContract.View { @Inject lateinit var homePresenter: HomePresenter override val layoutId: Int get() = R.layout.home_activity val countingIdlingResource: IdlingResource @VisibleForTesting get() = EspressoIdlingResource.idlingResource override fun initializeDagger() { val app = applicationContext as App app.mainComponent?.inject(this@HomeActivity) } override fun initializePresenter() { homePresenter.setView(this) super.presenter = homePresenter } override fun initializeNewsList(news: List<NewsItem>) { val newsAdapter = NewsAdapter(homePresenter.getRecyclerItemListener(), news) val layoutManager = LinearLayoutManager(this) rv_news_list.layoutManager = layoutManager rv_news_list.setHasFixedSize(true) rv_news_list.adapter = newsAdapter } override fun setLoaderVisibility(isVisible: Boolean) { pb_loading.visibility = if (isVisible) VISIBLE else GONE } override fun navigateToDetailsScreen(news: NewsItem) { startActivity(intentFor<DetailsActivity>(Constants.NEWS_ITEM_KEY to news)) } override fun setNoDataVisibility(isVisible: Boolean) { tv_no_data.visibility = if (isVisible) VISIBLE else GONE } override fun setListVisibility(isVisible: Boolean) { rl_news_list.visibility = if (isVisible) VISIBLE else GONE } override fun showSearchError() { rl_news_list.snackbar(R.string.search_error) } override fun showNoNewsError() { rl_news_list.snackbar(R.string.news_error) } override fun incrementCountingIdlingResource() { EspressoIdlingResource.increment() } override fun decrementCountingIdlingResource() { EspressoIdlingResource.decrement() } @OnClick(R.id.ic_toolbar_setting, R.id.ic_toolbar_refresh, R.id.btn_search) fun onClick(view: View) { when (view.id) { R.id.ic_toolbar_refresh -> homePresenter.getNews() R.id.btn_search -> homePresenter.onSearchClick(et_search.text.toString()) } } override fun onDestroy() { super.onDestroy() homePresenter.unSubscribe() } }
app/src/main/java/com/task/ui/component/news/HomeActivity.kt
1690291586
package com.didichuxing.doraemonkit.kit.test.widget import android.content.Context import android.util.AttributeSet import android.view.View import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn /** * didi Create on 2022/4/14 . * * Copyright (c) 2022/4/14 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/14 4:24 下午 * @Description 用一句话说明文件功能 */ class FlashImageView : androidx.appcompat.widget.AppCompatImageView { private val flashViewScope = MainScope() + CoroutineName(this.toString()) private var flashFlow = flow { while (true) { emit(0) delay(500) emit(1) delay(500) } } private var flashEnable: Boolean = false constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun isFlashEnable(): Boolean { return flashEnable } fun cancelFlash() { flashViewScope.cancel() flashEnable = false } fun startFlash() { if (!flashEnable) { flashEnable = true flashViewScope.launch { flashFlow.flowOn(Dispatchers.IO) .collect { when (it) { 0 -> visibility = View.VISIBLE 1 -> visibility = View.INVISIBLE else -> { } } } } } } }
Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/widget/FlashImageView.kt
583674108
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.test_suites import org.junit.runner.RunWith import org.junit.runners.Suite @RunWith(Suite::class) @Suite.SuiteClasses() class TestCodeTestSuite
project/pcComponents/core/src/test/kotlin/org/droidmate/test_suites/TestCodeTestSuite.kt
830056996
package com.chrisprime.primestationonecontrol import android.app.Application import android.content.Context import android.util.Log import com.chrisprime.primestationonecontrol.dagger.Injector import com.chrisprime.primestationonecontrol.model.PrimeStationOne import com.chrisprime.primestationonecontrol.utilities.FileUtilities import com.squareup.leakcanary.LeakCanary import com.squareup.otto.Bus import timber.log.Timber class PrimeStationOneControlApplication : Application() { var currentPrimeStationOne: PrimeStationOne? = null companion object { val ID_EVENT_BUS_MAIN = "main" lateinit var instance: PrimeStationOneControlApplication lateinit var eventBus: Bus val appResourcesContext: Context get() = instance.applicationContext } init { instance = this eventBus = Bus(ID_EVENT_BUS_MAIN) } override fun onCreate() { super.onCreate() if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } LeakCanary.install(this) Injector.initializeApplicationComponent(this) // if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) /* } else { Timber.plant(CrashReportingTree()) } */ val buildType = if (BuildConfig.DEBUG) "debug" else "production" Timber.d("Launching " + buildType + " build version " + BuildConfig.VERSION_NAME + ", which is version code " + BuildConfig.VERSION_CODE) updateCurrentPrimeStationFromJson() } fun updateCurrentPrimeStationFromJson() { currentPrimeStationOne = FileUtilities.readJsonCurrentPrimestation(this) } /** * A tree which logs important information for crash reporting. */ private class CrashReportingTree : Timber.Tree() { override fun log(priority: Int, tag: String, message: String, t: Throwable) { if (priority == Log.VERBOSE || priority == Log.DEBUG) { return } // FakeCrashLibrary.log(priority, tag, message); // // if (t != null) { // if (priority == Log.ERROR) { // FakeCrashLibrary.logError(t); // } else if (priority == Log.WARN) { // FakeCrashLibrary.logWarning(t); // } // } } } }
app/src/main/java/com/chrisprime/primestationonecontrol/PrimeStationOneControlApplication.kt
3077536567
package com.adrianfaciu.teamcity.flowdockPlugin.notifications /** * Threads represent entities in external services */ class NotificationThread { var body: String? = null var title: String? = null var status: NotificationStatus? = null var external_url: String? = null var fields: Array<NotificationFields>? = null var source: NotificationSource? = null override fun toString(): String { return "[body = $body, title = $title, status = $status, external_url = $external_url, fields = $fields]" } }
flowdock-teamcity-plugin-server/src/main/kotlin/com/adrianfaciu/teamcity/flowdockPlugin/notifications/NotificationThread.kt
1980796170
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison import com.intellij.diff.DiffTestCase class MergeResolveUtilTest : DiffTestCase() { fun testSimple() { test( "", "", "", "" ); test( "x x x", "x x x", "x x x", "x x x" ); test( "x x x", "x Y x", "x x x", "x Y x" ); test( "x x", "x x", "x Y x", "x Y x" ); test( "x X x", "x x", "x X x", "x x" ); } fun testSameModification() { test( "x x x", "x Y x", "x Y x", "x Y x" ); test( "x x", "x Y x", "x Y x", "x Y x" ); test( "x X x", "x x", "x x", "x x" ); } fun testNonConflictingChanges() { test( "x x x", "x Y x x", "x x Z x", "x Y x Z x" ); test( "x", "x Y", "Z x", "Z x Y" ); test( "x x", "x", "Z x x", "Z x" ); } fun testFailure() { test( "x x x", "x Y x", "x Z x", null ); test( "x x", "x Y x", "x Z x", null ); } fun testNonFailureConflicts() { test( "x X x", "x x", "x X Y x", "x Y x" ); test( "x X x", "x x", "x Y X x", "x Y x" ); test( "x X Y x", "x X x", "x Y x", "x x" ); test( "x X Y Z x", "x X x", "x Z x", "x x" ); test( "x A B C D E F G H K x", "x C F K x", "x A D H x", "x x" ); } fun testConfusingConflicts() { // these cases might be a failure as well test( "x X x", "x x", "x Z x", "xZ x" ); test( "x X X x", "x X Y X x", "x x", "x Y x" ); test( "x X x", "x x", "x Y x", "xY x" ); test( "x X X x", "x Y x", "x X Y x", "x Y x" ); } private fun test(base: String, left: String, right: String, expected: String?) { val actual = MergeResolveUtil.tryResolveConflict(left, base, right); assertEquals(expected, actual?.toString()) } }
platform/diff-impl/tests/com/intellij/diff/comparison/MergeResolveUtilTest.kt
4190825345
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlinx.cli internal actual fun exitProcess(status: Int): Nothing { kotlin.system.exitProcess(status) }
core/jvmMain/src/Utils.kt
2396771560
/* * Copyright 2010-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.jetbrains.kotlin.gradle.plugin.konan import org.gradle.api.* import org.gradle.api.component.ComponentWithVariants import org.gradle.api.component.SoftwareComponent import org.gradle.api.file.FileCollection import org.gradle.api.internal.FeaturePreviews import org.gradle.api.internal.component.SoftwareComponentInternal import org.gradle.api.internal.component.UsageContext import org.gradle.api.internal.project.ProjectInternal import org.gradle.api.plugins.BasePlugin import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.publish.maven.internal.publication.MavenPublicationInternal import org.gradle.language.cpp.internal.NativeVariantIdentity import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.plugin.konan.KonanPlugin.Companion.COMPILE_ALL_TASK_NAME import org.jetbrains.kotlin.gradle.plugin.model.KonanToolingModelBuilder import org.jetbrains.kotlin.gradle.plugin.tasks.* import org.jetbrains.kotlin.konan.CURRENT import org.jetbrains.kotlin.konan.CompilerVersion import org.jetbrains.kotlin.konan.parseCompilerVersion import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.buildDistribution import org.jetbrains.kotlin.konan.target.customerDistribution import org.jetbrains.kotlin.konan.util.DependencyProcessor import java.io.File import javax.inject.Inject /** * We use the following properties: * org.jetbrains.kotlin.native.home - directory where compiler is located (aka dist in konan project output). * org.jetbrains.kotlin.native.version - a konan compiler version for downloading. * konan.build.targets - list of targets to build (by default all the declared targets are built). * konan.jvmArgs - additional args to be passed to a JVM executing the compiler/cinterop tool. */ internal fun Project.warnAboutDeprecatedProperty(property: KonanPlugin.ProjectProperty) = property.deprecatedPropertyName?.let { deprecated -> if (project.hasProperty(deprecated)) { logger.warn("Project property '$deprecated' is deprecated. Use '${property.propertyName}' instead.") } } internal fun Project.hasProperty(property: KonanPlugin.ProjectProperty) = with(property) { when { hasProperty(propertyName) -> true deprecatedPropertyName != null && hasProperty(deprecatedPropertyName) -> true else -> false } } internal fun Project.findProperty(property: KonanPlugin.ProjectProperty): Any? = with(property) { return findProperty(propertyName) ?: deprecatedPropertyName?.let { findProperty(it) } } internal fun Project.getProperty(property: KonanPlugin.ProjectProperty) = findProperty(property) ?: throw IllegalArgumentException("No such property in the project: ${property.propertyName}") internal fun Project.getProperty(property: KonanPlugin.ProjectProperty, defaultValue: Any) = findProperty(property) ?: defaultValue internal fun Project.setProperty(property: KonanPlugin.ProjectProperty, value: Any) { extensions.extraProperties.set(property.propertyName, value) } // konanHome extension is set by downloadKonanCompiler task. internal val Project.konanHome: String get() { assert(hasProperty(KonanPlugin.ProjectProperty.KONAN_HOME)) return project.file(getProperty(KonanPlugin.ProjectProperty.KONAN_HOME)).canonicalPath } internal val Project.konanVersion: CompilerVersion get() = project.findProperty(KonanPlugin.ProjectProperty.KONAN_VERSION) ?.toString()?.let { CompilerVersion.fromString(it) } ?: CompilerVersion.CURRENT internal val Project.konanBuildRoot get() = buildDir.resolve("konan") internal val Project.konanBinBaseDir get() = konanBuildRoot.resolve("bin") internal val Project.konanLibsBaseDir get() = konanBuildRoot.resolve("libs") internal val Project.konanBitcodeBaseDir get() = konanBuildRoot.resolve("bitcode") internal fun File.targetSubdir(target: KonanTarget) = resolve(target.visibleName) internal val Project.konanDefaultSrcFiles get() = fileTree("${projectDir.canonicalPath}/src/main/kotlin") internal fun Project.konanDefaultDefFile(libName: String) = file("${projectDir.canonicalPath}/src/main/c_interop/$libName.def") @Suppress("UNCHECKED_CAST") internal val Project.konanArtifactsContainer: KonanArtifactContainer get() = extensions.getByName(KonanPlugin.ARTIFACTS_CONTAINER_NAME) as KonanArtifactContainer // TODO: The Kotlin/Native compiler is downloaded manually by a special task so the compilation tasks // are configured without the compile distribution. After target management refactoring // we need .properties files from the distribution to configure targets. This is worked around here // by using HostManager instead of PlatformManager. But we need to download the compiler at the configuration // stage (e.g. by getting it from maven as a plugin dependency) and bring back the PlatformManager here. internal val Project.hostManager: HostManager get() = findProperty("hostManager") as HostManager? ?: if (hasProperty("org.jetbrains.kotlin.native.experimentalTargets")) HostManager(buildDistribution(rootProject.rootDir.absolutePath), true) else HostManager(customerDistribution(konanHome)) internal val Project.konanTargets: List<KonanTarget> get() = hostManager.toKonanTargets(konanExtension.targets) .filter{ hostManager.isEnabled(it) } .distinct() @Suppress("UNCHECKED_CAST") internal val Project.konanExtension: KonanExtension get() = extensions.getByName(KonanPlugin.KONAN_EXTENSION_NAME) as KonanExtension internal val Project.konanCompilerDownloadTask get() = tasks.getByName(KonanPlugin.KONAN_DOWNLOAD_TASK_NAME) internal val Project.requestedTargets get() = findProperty(KonanPlugin.ProjectProperty.KONAN_BUILD_TARGETS)?.let { it.toString().trim().split("\\s+".toRegex()) }.orEmpty() internal val Project.jvmArgs get() = (findProperty(KonanPlugin.ProjectProperty.KONAN_JVM_ARGS) as String?)?.split("\\s+".toRegex()).orEmpty() internal val Project.compileAllTask get() = getOrCreateTask(COMPILE_ALL_TASK_NAME) internal fun Project.targetIsRequested(target: KonanTarget): Boolean { val targets = requestedTargets return (targets.isEmpty() || targets.contains(target.visibleName) || targets.contains("all")) } /** Looks for task with given name in the given project. Throws [UnknownTaskException] if there's not such task. */ private fun Project.getTask(name: String): Task = tasks.getByPath(name) /** * Looks for task with given name in the given project. * If such task isn't found, will create it. Returns created/found task. */ private fun Project.getOrCreateTask(name: String): Task = with(tasks) { findByPath(name) ?: create(name, DefaultTask::class.java) } internal fun Project.konanCompilerName(): String = "kotlin-native-${project.simpleOsName}-${project.konanVersion}" internal fun Project.konanCompilerDownloadDir(): String = DependencyProcessor.localKonanDir.resolve(project.konanCompilerName()).absolutePath // region Useful extensions and functions --------------------------------------- internal fun MutableList<String>.addArg(parameter: String, value: String) { add(parameter) add(value) } internal fun MutableList<String>.addArgs(parameter: String, values: Iterable<String>) { values.forEach { addArg(parameter, it) } } internal fun MutableList<String>.addArgIfNotNull(parameter: String, value: String?) { if (value != null) { addArg(parameter, value) } } internal fun MutableList<String>.addKey(key: String, enabled: Boolean) { if (enabled) { add(key) } } internal fun MutableList<String>.addFileArgs(parameter: String, values: FileCollection) { values.files.forEach { addArg(parameter, it.canonicalPath) } } internal fun MutableList<String>.addFileArgs(parameter: String, values: Collection<FileCollection>) { values.forEach { addFileArgs(parameter, it) } } // endregion internal fun dumpProperties(task: Task) { fun Iterable<String>.dump() = joinToString(prefix = "[", separator = ",\n${" ".repeat(22)}", postfix = "]") fun Collection<FileCollection>.dump() = flatMap { it.files }.map { it.canonicalPath }.dump() when (task) { is KonanCompileTask -> with(task) { println() println("Compilation task: $name") println("destinationDir : $destinationDir") println("artifact : ${artifact.canonicalPath}") println("srcFiles : ${srcFiles.dump()}") println("produce : $produce") println("libraries : ${libraries.files.dump()}") println(" : ${libraries.artifacts.map { it.artifact.canonicalPath }.dump()}") println(" : ${libraries.namedKlibs.dump()}") println("nativeLibraries : ${nativeLibraries.dump()}") println("linkerOpts : $linkerOpts") println("enableDebug : $enableDebug") println("noStdLib : $noStdLib") println("noMain : $noMain") println("enableOptimization : $enableOptimizations") println("enableAssertions : $enableAssertions") println("noDefaultLibs : $noDefaultLibs") println("noEndorsedLibs : $noEndorsedLibs") println("target : $target") println("languageVersion : $languageVersion") println("apiVersion : $apiVersion") println("konanVersion : ${CompilerVersion.CURRENT}") println("konanHome : $konanHome") println() } is KonanInteropTask -> with(task) { println() println("Stub generation task: $name") println("destinationDir : $destinationDir") println("artifact : $artifact") println("libraries : ${libraries.files.dump()}") println(" : ${libraries.artifacts.map { it.artifact.canonicalPath }.dump()}") println(" : ${libraries.namedKlibs.dump()}") println("defFile : $defFile") println("target : $target") println("packageName : $packageName") println("compilerOpts : $compilerOpts") println("linkerOpts : $linkerOpts") println("headers : ${headers.dump()}") println("linkFiles : ${linkFiles.dump()}") println("konanVersion : ${CompilerVersion.CURRENT}") println("konanHome : $konanHome") println() } else -> { println("Unsupported task.") } } } open class KonanExtension { var targets = mutableListOf("host") var languageVersion: String? = null var apiVersion: String? = null var jvmArgs = mutableListOf<String>() } open class KonanSoftwareComponent(val project: ProjectInternal?): SoftwareComponentInternal, ComponentWithVariants { private val usages = mutableSetOf<UsageContext>() override fun getUsages(): MutableSet<out UsageContext> = usages private val variants = mutableSetOf<SoftwareComponent>() override fun getName() = "main" override fun getVariants(): Set<SoftwareComponent> = variants fun addVariant(component: SoftwareComponent) = variants.add(component) } class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderRegistry) : Plugin<ProjectInternal> { enum class ProjectProperty(val propertyName: String, val deprecatedPropertyName: String? = null) { KONAN_HOME ("org.jetbrains.kotlin.native.home", "konan.home"), KONAN_VERSION ("org.jetbrains.kotlin.native.version"), KONAN_BUILD_TARGETS ("konan.build.targets"), KONAN_JVM_ARGS ("konan.jvmArgs"), KONAN_USE_ENVIRONMENT_VARIABLES("konan.useEnvironmentVariables"), DOWNLOAD_COMPILER ("download.compiler"), // Properties used instead of env vars until https://github.com/gradle/gradle/issues/3468 is fixed. // TODO: Remove them when an API for env vars is provided. KONAN_CONFIGURATION_BUILD_DIR ("konan.configuration.build.dir"), KONAN_DEBUGGING_SYMBOLS ("konan.debugging.symbols"), KONAN_OPTIMIZATIONS_ENABLE ("konan.optimizations.enable"), } companion object { internal const val ARTIFACTS_CONTAINER_NAME = "konanArtifacts" internal const val KONAN_DOWNLOAD_TASK_NAME = "checkKonanCompiler" internal const val KONAN_GENERATE_CMAKE_TASK_NAME = "generateCMake" internal const val COMPILE_ALL_TASK_NAME = "compileKonan" internal const val KONAN_EXTENSION_NAME = "konan" internal val REQUIRED_GRADLE_VERSION = GradleVersion.version("4.7") } private fun Project.cleanKonan() = project.tasks.withType(KonanBuildingTask::class.java).forEach { project.delete(it.artifact) } private fun checkGradleVersion() = GradleVersion.current().let { current -> check(current >= REQUIRED_GRADLE_VERSION) { "Kotlin/Native Gradle plugin is incompatible with this version of Gradle.\n" + "The minimal required version is $REQUIRED_GRADLE_VERSION\n" + "Current version is ${current}" } } override fun apply(project: ProjectInternal?) { if (project == null) { return } checkGradleVersion() registry.register(KonanToolingModelBuilder) project.plugins.apply("base") // Create necessary tasks and extensions. project.tasks.create(KONAN_DOWNLOAD_TASK_NAME, KonanCompilerDownloadTask::class.java) project.tasks.create(KONAN_GENERATE_CMAKE_TASK_NAME, KonanGenerateCMakeTask::class.java) project.extensions.create(KONAN_EXTENSION_NAME, KonanExtension::class.java) val container = project.extensions.create( KonanArtifactContainer::class.java, ARTIFACTS_CONTAINER_NAME, KonanArtifactContainer::class.java, project ) project.warnAboutDeprecatedProperty(ProjectProperty.KONAN_HOME) // Set additional project properties like org.jetbrains.kotlin.native.home, konan.build.targets etc. if (!project.hasProperty(ProjectProperty.KONAN_HOME)) { project.setProperty(ProjectProperty.KONAN_HOME, project.konanCompilerDownloadDir()) project.setProperty(ProjectProperty.DOWNLOAD_COMPILER, true) } // Create and set up aggregate building tasks. val compileKonanTask = project.getOrCreateTask(COMPILE_ALL_TASK_NAME).apply { group = BasePlugin.BUILD_GROUP description = "Compiles all the Kotlin/Native artifacts" } project.getTask("build").apply { dependsOn(compileKonanTask) } project.getTask("clean").apply { doLast { project.cleanKonan() } } val runTask = project.getOrCreateTask("run") project.afterEvaluate { project.konanArtifactsContainer .filterIsInstance(KonanProgram::class.java) .forEach { program -> program.forEach { compile -> compile.runTask?.let { runTask.dependsOn(it) } } } } // Enable multiplatform support project.pluginManager.apply(KotlinNativePlatformPlugin::class.java) project.afterEvaluate { project.pluginManager.withPlugin("maven-publish") { container.all { buildingConfig -> val konanSoftwareComponent = buildingConfig.mainVariant project.extensions.configure(PublishingExtension::class.java) { val builtArtifact = buildingConfig.name val mavenPublication = it.publications.maybeCreate(builtArtifact, MavenPublication::class.java) mavenPublication.apply { artifactId = builtArtifact groupId = project.group.toString() from(konanSoftwareComponent) } (mavenPublication as MavenPublicationInternal).publishWithOriginalFileName() buildingConfig.pomActions.forEach { mavenPublication.pom(it) } } project.extensions.configure(PublishingExtension::class.java) { val publishing = it for (v in konanSoftwareComponent.variants) { publishing.publications.create(v.name, MavenPublication::class.java) { mavenPublication -> val coordinates = (v as NativeVariantIdentity).coordinates project.logger.info("variant with coordinates($coordinates) and module: ${coordinates.module}") mavenPublication.artifactId = coordinates.module.name mavenPublication.groupId = coordinates.group mavenPublication.version = coordinates.version mavenPublication.from(v) (mavenPublication as MavenPublicationInternal).publishWithOriginalFileName() buildingConfig.pomActions.forEach { mavenPublication.pom(it) } } } } } } } } }
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanPlugin.kt
2720038924
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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.thomas.needham.neurophidea.designer.editor.tset import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.EditorMarkupModel import com.intellij.openapi.editor.highlighter.EditorHighlighter import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.fileEditor.impl.text.FileDropHandler import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.messages.MessageBusConnection import org.jetbrains.annotations.NotNull import java.awt.BorderLayout /** * Created by thoma on 09/10/2016. */ class TsetEditorComponent : JBLoadingPanel, DataProvider { val project: Project? @NotNull val file: VirtualFile? val tsetEditor: TsetEditorImpl? val editor: Editor? val document: Document? val documentListener: TsetDocumentListener? var isComponentModified: Boolean var isComponentValid: Boolean val fileListener: TsetVirtualFileListener? val busConnection: MessageBusConnection? companion object Log { @JvmStatic val LOG: Logger = Logger.getInstance("#com.thomas.needham.neurophidea.designer.editor.tset.TsetEditorComponent") @JvmStatic val assertThread: () -> Unit = { ApplicationManager.getApplication().assertIsDispatchThread() } } constructor(@NotNull project: Project?, @NotNull file: VirtualFile?, @NotNull editor: TsetEditorImpl?) : super(BorderLayout(), editor as Disposable) { this.project = project this.file = file this.tsetEditor = editor this.document = TsetDocumentManager.getInstance().getDocument(file!!) LOG.assertTrue(this.document != null) documentListener = TsetDocumentListener(this) document?.addDocumentListener(documentListener) this.editor = createEditor() this.add(this, BorderLayout.CENTER) isComponentModified = isModifiedImpl() isComponentValid = isEditorValidImpl() LOG.assertTrue(isComponentValid) fileListener = TsetVirtualFileListener(this) this.file?.fileSystem?.addVirtualFileListener(fileListener) busConnection = project?.messageBus?.connect() busConnection?.subscribe(FileTypeManager.TOPIC, TsetFileTypeListener(this)) busConnection?.subscribe(DumbService.DUMB_MODE, TsetDumbModeListener(this)) } @NotNull private fun createEditor(): Editor? { val e: Editor? = EditorFactory.getInstance().createEditor(document!!, project) (e?.markupModel as EditorMarkupModel).isErrorStripeVisible = true (e as EditorEx).gutterComponentEx.setForceShowRightFreePaintersArea(true) e.setFile(file) e.contextMenuGroupId = IdeActions.GROUP_EDITOR_POPUP (e as EditorImpl).setDropHandler(FileDropHandler(e)) TsetFileEditorProvider.putTsetEditor(e, tsetEditor) return e } private fun isEditorValidImpl(): Boolean { return TsetDocumentManager.getInstance().getDocument(file!!) != null } override fun getData(p0: String): Any? { throw UnsupportedOperationException() } fun updateModifiedProperty() { val oldModified = isComponentModified isComponentModified = isModifiedImpl() tsetEditor?.firePropertyChange(FileEditor.PROP_MODIFIED, oldModified, isComponentModified) } private fun isModifiedImpl(): Boolean { return TsetDocumentManager.getInstance().isFileModified(file!!); } fun updateValidProperty() { val oldValid = isComponentValid isComponentValid = isEditorValidImpl() tsetEditor?.firePropertyChange(FileEditor.PROP_VALID, oldValid, isComponentValid) } fun updateHighlighters() { if (!project?.isDisposed!! && !editor?.isDisposed!!) { val highlighter: EditorHighlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, file!!) (editor as EditorEx).highlighter = highlighter } } fun dispose() { document?.removeDocumentListener(documentListener!!) if (!project?.isDefault!!) { EditorHistoryManager.getInstance(project!!).updateHistoryEntry(file, false) } disposeEditor() busConnection?.disconnect() file?.fileSystem?.removeVirtualFileListener(fileListener!!) } private fun disposeEditor() { EditorFactory.getInstance().releaseEditor(editor!!) } fun selectNotify() { updateStatusBar() } private fun updateStatusBar() { val statusBar: StatusBarEx? = WindowManager.getInstance().getStatusBar(project) as StatusBarEx statusBar?.updateWidgets() } }
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/tset/TsetEditorComponent.kt
2179959403
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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.thomas.needham.neurophidea.project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.ui.ProjectJdksEditor import java.awt.event.ActionEvent import java.awt.event.ActionListener /** * Created by Thomas Needham on 06/06/2016. */ class NeurophSDKComboBoxActionListener : ActionListener { var instance: NeurophSDKComboBox? = null companion object Data { val project = ProjectManager.getInstance().defaultProject } override fun actionPerformed(e: ActionEvent?) { var sdk: Sdk? = instance?.getSelectedSdk() var editor = ProjectJdksEditor(sdk, NeurophSDKComboBoxActionListener.project, instance?.rootPane) editor.show() if (editor.isOK) { sdk = editor.selectedJdk instance?.updateSDKList(sdk, false) } } }
neuroph-plugin/src/com/thomas/needham/neurophidea/project/NeurophSDKComboBoxActionListener.kt
3121057432
package net.nemerosa.ontrack.extension.git.graphql import graphql.Scalars.GraphQLString import graphql.schema.DataFetchingEnvironment import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.api.model.IssueChangeLogExportRequest import net.nemerosa.ontrack.extension.git.model.GitChangeLog import net.nemerosa.ontrack.extension.git.model.GitProjectNotConfiguredException import net.nemerosa.ontrack.extension.git.service.GitService import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.listType import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.stereotype.Component /** * GraphQL type for a change log * @see net.nemerosa.ontrack.extension.git.model.GitChangeLog */ @Component class GitChangeLogGQLType( private val gitUICommitGQLType: GitUICommitGQLType, private val gitChangeLogIssuesGQLType: GitChangeLogIssuesGQLType, private val issueChangeLogExportRequestGQLInputType: IssueChangeLogExportRequestGQLInputType, private val gitService: GitService, ) : GQLType { override fun getTypeName(): String = GIT_CHANGE_LOG override fun createType(cache: GQLTypeCache): GraphQLObjectType { return GraphQLObjectType.newObject() .name(GIT_CHANGE_LOG) // Commits .field { f -> f.name("commits") .description("List of commits in the change log") .type(listType(gitUICommitGQLType.typeRef)) .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() gitService.getChangeLogCommits(gitChangeLog).commits } } // Issues .field { f -> f.name("issues") .description("List of issues in the change log") .type(gitChangeLogIssuesGQLType.typeRef) .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() gitService.getChangeLogIssues(gitChangeLog) } } // Export of change log .field { f -> f.name("export") .description("Export of the change log according to some specifications") .type(GraphQLString) .argument { it.name("request") .description("Export specifications") .type(issueChangeLogExportRequestGQLInputType.typeRef) } .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() // Parses the request val request = parseExportRequest(env) // Build boundaries request.from = gitChangeLog.from.build.id request.to = gitChangeLog.to.build.id // Gets the associated project val project = gitChangeLog.project // Gets the configuration for the project val gitConfiguration = gitService.getProjectConfiguration(project) ?: return@dataFetcher null // Gets the issue service val configuredIssueService = gitConfiguration.configuredIssueService ?: return@dataFetcher null // Gets the issue change log val changeLogIssues = gitService.getChangeLogIssues(gitChangeLog) // List of issues val issues = changeLogIssues.list.map { it.issue } // Exports the change log using the given format val exportedChangeLogIssues = configuredIssueService.issueServiceExtension .exportIssues( configuredIssueService.issueServiceConfiguration, issues, request ) // Returns the content exportedChangeLogIssues.content } } // OK .build() } private fun parseExportRequest(env: DataFetchingEnvironment): IssueChangeLogExportRequest { val requestArg: Any? = env.getArgument<Any>("request") return issueChangeLogExportRequestGQLInputType.convert(requestArg) ?: IssueChangeLogExportRequest() } companion object { const val GIT_CHANGE_LOG = "GitChangeLog" } }
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/graphql/GitChangeLogGQLType.kt
885791123
/* * Copyright 2017 Yonghoon Kim * * 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.pickth.gachi.base import com.pickth.gachi.view.custom.AddInfoViewPager abstract class BaseAddInfoFragment : BaseFragment() { var mListener: AddInfoViewPager.ChangeFragmentListener? = null fun setChangeFragmentListener(listener: AddInfoViewPager.ChangeFragmentListener) { mListener = listener } /** * @param isSkip if click skip button, isSkip is true. */ abstract fun clickNextButton(isSkip: Boolean) }
Gachi/app/src/main/kotlin/com/pickth/gachi/base/BaseAddInfoFragment.kt
3959490959
package tornadofx import javafx.beans.property.ObjectProperty import javafx.beans.property.ReadOnlyIntegerProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import javafx.scene.layout.BorderPane import tornadofx.ViewTransition.Direction.RIGHT import kotlin.reflect.KClass class Slideshow(val scope: Scope = DefaultScope) : BorderPane() { val slides: ObservableList<Slide> = FXCollections.observableArrayList<Slide>() val defaultTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds)) var defaultTransition: ViewTransition? by defaultTransitionProperty val defaultBackTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds, RIGHT)) var defaultBackTransition: ViewTransition? by defaultBackTransitionProperty val currentSlideProperty: ObjectProperty<Slide?> = SimpleObjectProperty() var currentSlide: Slide? by currentSlideProperty val nextKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Right")) var nextKey: KeyCombination by nextKeyProperty val previousKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Left")) var previousKey: KeyCombination by previousKeyProperty private val realIndexProperty = SimpleIntegerProperty(-1) val indexProperty: ReadOnlyIntegerProperty = ReadOnlyIntegerProperty.readOnlyIntegerProperty(realIndexProperty) val index by indexProperty inline fun <reified T:UIComponent> slide(transition: ViewTransition? = null) = slide(T::class,transition) fun slide(view: KClass<out UIComponent>, transition: ViewTransition? = null) = slides.addAll(Slide(view, transition)) fun next(): Boolean { if (index + 1 >= slides.size) return false goto(slides[index + 1], true) return true } fun previous(): Boolean { if (index <= 0) return false goto(slides[index - 1], false) return true } init { showFirstSlideWhenAvailable() hookNavigationShortcuts() } private fun hookNavigationShortcuts() { sceneProperty().onChange { scene?.addEventHandler(KeyEvent.KEY_PRESSED) { if (!it.isConsumed) { if (nextKey.match(it)) next() else if (previousKey.match(it)) previous() } } } } private fun showFirstSlideWhenAvailable() { slides.addListener { change: ListChangeListener.Change<out Slide> -> while (change.next()) { if (change.wasAdded() && currentSlide == null) next() } } } private fun goto(slide: Slide, forward: Boolean) { val nextUI = slide.getUI(scope) // Avoid race conditions if last transition is still in progress val centerRightNow = center if (centerRightNow == null) { center = nextUI.root } else { val transition = if (forward) slide.transition ?: defaultTransition else defaultBackTransition nextUI.root.removeFromParent() centerRightNow.replaceWith(nextUI.root, transition) } val delta = if (forward) 1 else -1 val newIndex = index + delta currentSlide = slides[newIndex] realIndexProperty.value = newIndex } class Slide(val view: KClass<out UIComponent>, val transition: ViewTransition? = null) { private var ui: UIComponent? = null fun getUI(scope: Scope): UIComponent { if (ui == null) ui = find(view, scope) return ui!! } } }
src/main/java/tornadofx/Slideshow.kt
2865092983
package com.xiaojinzi.component.impl.interceptor import android.app.Application import com.xiaojinzi.component.interceptor.IComponentHostInterceptor import com.xiaojinzi.component.impl.RouterInterceptor import androidx.annotation.UiThread import androidx.annotation.CallSuper import com.xiaojinzi.component.support.RouterInterceptorCache import java.util.HashMap /** * 拦截器的代码生成类的基本实现 * time : 2018/12/26 * * @author : xiaojinzi */ internal abstract class ModuleInterceptorImpl : IComponentHostInterceptor { private var isInitMap = false protected val realInterceptorMap: Map<String, Class<out RouterInterceptor>> = mutableMapOf() override val interceptorMap: Map<String, Class<out RouterInterceptor>> get() { if (!isInitMap) { initInterceptorMap() } return HashMap(realInterceptorMap) } override val interceptorNames: Set<String> get() { if (!isInitMap) { initInterceptorMap() } return realInterceptorMap.keys } /** * 初始化拦截器的集合 */ @CallSuper @UiThread protected open fun initInterceptorMap() { isInitMap = true } /** * 用作销毁一些缓存 * * @param app [Application] */ override fun onCreate(app: Application) { // empty } /** * 用作销毁一些缓存 */ override fun onDestroy() { // empty } @UiThread override fun globalInterceptorList(): List<InterceptorBean> { return emptyList() } @UiThread override fun getByName(name: String): RouterInterceptor? { if (!isInitMap) { initInterceptorMap() } val interceptorClass = interceptorMap[name] ?: return null return RouterInterceptorCache.getInterceptorByClass(interceptorClass) } }
ComponentImpl/src/main/java/com/xiaojinzi/component/impl/interceptor/ModuleInterceptorImpl.kt
2651757949
package t.masahide.android.croudia.presenter import android.content.Context import android.support.v7.app.AppCompatActivity import android.util.Log import t.masahide.android.croudia.api.ServiceCreatable import t.masahide.android.croudia.extensions.onNext import t.masahide.android.croudia.service.AccessTokenService import t.masahide.android.croudia.ui.activity.AuthActivity import t.masahide.android.croudia.api.ServiceCreator import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import t.masahide.android.croudia.entitiy.User import t.masahide.android.croudia.service.PreferenceService import t.masahide.android.croudia.ui.activity.MainActivity /** * Created by Masahide on 2016/03/13. */ class AuthPresenter(val activity: AuthActivity, val preferenceService: PreferenceService = PreferenceService()) : APIExecutePresenterBase() { fun auth(code: String) { croudiaAPI.createToken(code) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doOnError { } .onNext { accessTokenService.saveAccessToken(it) verifyCredential() }.subscribe() } fun verifyCredential() { croudiaAPI.verifyCredentials(accessToken) .compose(activity.bindToLifecycle<User>()) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .onNext { preferenceService.applyUser(it) activity.setResult(AppCompatActivity.RESULT_OK) activity.finish() } .onError { accessTokenService.logout() } .subscribe() } }
app/src/main/kotlin/t/masahide/android/croudia/presenter/AuthPresenter.kt
3585304149
/* * Copyright 2013 Maurício Linhares * Copyright 2013 Dylan Simon * * Maurício Linhares 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: * * 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.mauricio.async.db.postgresql.column import org.specs2.mutable.Specification class IntervalSpec extends Specification { "interval encoder/decoder" should { fun decode(s : String) : Any = PostgreSQLIntervalEncoderDecoder.decode(s) fun encode(i : Any) : String = PostgreSQLIntervalEncoderDecoder.encode(i) fun both(s : String) : String = encode(decode(s)) "parse and encode example intervals" in { Seq("1-2", "1 year 2 mons", "@ 1 year 2 mons", "@ 1 year 2 mons", "P1Y2M") forall { both(_) === "P1Y2M" } Seq("3 4:05:06", "3 days 04:05:06", "@ 3 days 4 hours 5 mins 6 secs", "P3DT4H5M6S") forall { both(_) === "P3DT4H5M6S" } Seq("1-2 +3 4:05:06", "1 year 2 mons +3 days 04:05:06", "@ 1 year 2 mons 3 days 4 hours 5 mins 6 secs", "P1Y2M3DT4H5M6S") forall { both(_) === "P1Y2M3DT4H5M6S" } Seq("@ 1 year 2 mons -3 days 4 hours 5 mins 6 secs ago", "P-1Y-2M3DT-4H-5M-6S") forall { both(_) === "P-1Y-2M3DT-4H-5M-6S" } both("-1.234") === "PT-1.234S" both("-4:05:06") === "PT-4H-5M-6S" } "parse and encode example intervals" in { Seq("-1-2 +3 -4:05:06", "-1 year -2 mons +3 days -04:05:06") forall { both(_) === "P-1Y-2M3DT-4H-5M-6S" } }.pendingUntilFixed("with mixed/grouped negations") } }
postgresql-async/src/test/kotlin/com/github/mauricio/async/db/postgresql/column/IntervalSpec.kt
3293752680
package edu.cs4730.drawdemo1_kt import android.graphics.* import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.util.Log import android.view.View.OnTouchListener import android.view.MotionEvent import android.view.View import android.widget.* import androidx.fragment.app.Fragment /** * This is a simple example to show how each of the canvas drawing works. * */ class MainFragment : Fragment() { lateinit var theboardfield: ImageView lateinit var theboard: Bitmap lateinit var theboardc: Canvas lateinit var btnClear: Button lateinit var btnNColor: Button lateinit var mySpinner: Spinner var which = 1 val boardsize = 480 //for drawing var firstx = 0f var firsty = 0f var first = true var myRecF = RectF() var myColor: Paint? = null var myColorList = ColorList() lateinit var alien: Bitmap override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_main, container, false) //Simple clear button, reset the image to white. btnClear = myView.findViewById<View>(R.id.button2) as Button btnClear.setOnClickListener { theboardc.drawColor(Color.WHITE) //background color for the board. refreshBmp() } //changes to the next color in the list btnNColor = myView.findViewById<View>(R.id.button3) as Button btnNColor.setOnClickListener { myColorList.next() myColor!!.color = myColorList.getNum() } //setup the spinner val list = arrayOf("Point", "Line", "Rect", "Circle", "Arc", "Oval", "Pic", "Text") //first we will work on the spinner1 (which controls the seekbar) mySpinner = myView.findViewById<View>(R.id.spinner) as Spinner //create the ArrayAdapter of strings from my List. val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, list) //set the dropdown layout adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) //finally set the adapter to the spinner mySpinner.adapter = adapter //set the selected listener as well mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { which = position first = true } override fun onNothingSelected(parent: AdapterView<*>?) { which = 1 //point first = true } } //get the imageview and create a bitmap to put in the imageview. //also create the canvas to draw on. theboardfield = myView.findViewById<View>(R.id.boardfield) as ImageView theboard = Bitmap.createBitmap(boardsize, boardsize, Bitmap.Config.ARGB_8888) theboardc = Canvas(theboard) theboardc.drawColor(Color.WHITE) //background color for the board. theboardfield.setImageBitmap(theboard) theboardfield.invalidate() theboardfield.setOnTouchListener(myTouchListener()) //For drawing myColor = Paint() //default black myColor!!.color = myColorList.getNum() myColor!!.style = Paint.Style.FILL myColor!!.strokeWidth = 10f myColor!!.textSize = myColor!!.textSize * 4 //load a picture and draw it onto the screen. alien = BitmapFactory.decodeResource(resources, R.drawable.alien) //draw it on the screen. //theboardc.drawBitmap(alien, null, new Rect(0, 0, 300, 300), myColor); return myView } /* * TouchListener will draw a square on the image where "touched". * If doing an animated clear, it will return without doing anything. */ internal inner class myTouchListener : OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { //We just need the x and y position, to draw on the canvas //so, retrieve the new x and y touch positions if (event.action == MotionEvent.ACTION_UP) { //fake it for tap. drawBmp(event.x, event.y) v.performClick() return true } return false } } fun drawBmp(x: Float, y: Float) { //"Point", "Line", "Rect", "Circle", "Arc", "Oval", "Pic", "Text" when (which) { 0 -> theboardc.drawPoint(x, y, myColor!!) 1 -> if (first) { //store the point for later firstx = x firsty = y first = false } else { theboardc.drawLine(firstx, firsty, x, y, myColor!!) first = true } 2 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawRect(myRecF, myColor!!) first = true } 3 -> theboardc.drawCircle(x, y, 20.0f, myColor!!) 4 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawArc(myRecF, 0.0f, 45.0f, true, myColor!!) first = true } 5 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawOval(myRecF, myColor!!) first = true } 6 -> theboardc.drawBitmap(alien, x, y, myColor) 7 -> theboardc.drawText("Hi there", x, y, myColor!!) else -> Log.v("hi", "NOT working? $which") } theboardfield.setImageBitmap(theboard) theboardfield.invalidate() } fun refreshBmp() { theboardfield.setImageBitmap(theboard) theboardfield.invalidate() } }
DrawDemo1_kt/app/src/main/java/edu/cs4730/drawdemo1_kt/MainFragment.kt
3098478287
/* * 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 com.intellij.psi.stubs import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileTypes.FileTypeExtension import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.util.indexing.FileContent import com.intellij.util.indexing.IndexInfrastructure import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.KeyDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.io.DataInput import java.io.DataOutput import java.io.File import java.io.IOException /** * @author traff */ val EP_NAME = "com.intellij.filetype.prebuiltStubsProvider" object PrebuiltStubsProviders : FileTypeExtension<PrebuiltStubsProvider>(EP_NAME) @ApiStatus.Experimental interface PrebuiltStubsProvider { fun findStub(fileContent: FileContent): Stub? } class FileContentHashing { private val hashing = Hashing.sha256() fun hashString(fileContent: FileContent) = hashing.hashBytes(fileContent.content) } class HashCodeDescriptor : HashCodeExternalizers(), KeyDescriptor<HashCode> { override fun getHashCode(value: HashCode): Int = value.hashCode() override fun isEqual(val1: HashCode, val2: HashCode): Boolean = val1 == val2 companion object { val instance = HashCodeDescriptor() } } open class HashCodeExternalizers : DataExternalizer<HashCode> { override fun save(out: DataOutput, value: HashCode) { val bytes = value.asBytes() DataInputOutputUtil.writeINT(out, bytes.size) out.write(bytes, 0, bytes.size) } override fun read(`in`: DataInput): HashCode { val len = DataInputOutputUtil.readINT(`in`) val bytes = ByteArray(len) `in`.readFully(bytes) return HashCode.fromBytes(bytes) } } class StubTreeExternalizer : DataExternalizer<SerializedStubTree> { override fun save(out: DataOutput, value: SerializedStubTree) { value.write(out) } override fun read(`in`: DataInput) = SerializedStubTree(`in`) } abstract class PrebuiltStubsProviderBase : PrebuiltStubsProvider, Disposable { private val myFileContentHashing = FileContentHashing() private var myPrebuiltStubsStorage: PersistentHashMap<HashCode, SerializedStubTree>? = null private var mySerializationManager: SerializationManagerImpl? = null protected abstract val stubVersion: Int protected abstract val name: String init { init() } companion object { val PREBUILT_INDICES_PATH_PROPERTY = "prebuilt_indices_path" val SDK_STUBS_STORAGE_NAME = "sdk-stubs" private val LOG = Logger.getInstance("#com.intellij.psi.stubs.PrebuiltStubsProviderBase") } internal fun init() { var indexesRoot = findPrebuiltIndicesRoot() try { if (indexesRoot != null) { // we should copy prebuilt indexes to a writable folder indexesRoot = copyPrebuiltIndicesToIndexRoot(indexesRoot) // otherwise we can get access denied error, because persistent hash map opens file for read and write val versionInFile = FileUtil.loadFile(File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".version")) if (Integer.parseInt(versionInFile) == stubVersion) { myPrebuiltStubsStorage = object : PersistentHashMap<HashCode, SerializedStubTree>( File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".input"), HashCodeDescriptor.instance, StubTreeExternalizer()) { override fun isReadOnly(): Boolean { return true } } mySerializationManager = SerializationManagerImpl(File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".names")) Disposer.register(ApplicationManager.getApplication(), mySerializationManager!!) LOG.info("Using prebuilt stubs from " + myPrebuiltStubsStorage!!.baseFile.absolutePath) } else { LOG.error("Prebuilt stubs version mismatch: $versionInFile, current version is $stubVersion") } } } catch (e: Exception) { myPrebuiltStubsStorage = null LOG.warn("Prebuilt stubs can't be loaded at " + indexesRoot!!, e) } } override fun findStub(fileContent: FileContent): Stub? { if (myPrebuiltStubsStorage != null) { val hashCode = myFileContentHashing.hashString(fileContent) var stub: Stub? = null try { val stubTree = myPrebuiltStubsStorage!!.get(hashCode) if (stubTree != null) { stub = stubTree.getStub(false, mySerializationManager!!) } } catch (e: SerializerNotFoundException) { LOG.error("Can't deserialize stub tree", e) } catch (e: Exception) { LOG.error("Error reading prebuilt stubs from " + myPrebuiltStubsStorage!!.baseFile.path, e) myPrebuiltStubsStorage = null stub = null } if (stub != null) { return stub } } return null } override fun dispose() { if (myPrebuiltStubsStorage != null) { try { myPrebuiltStubsStorage!!.close() } catch (e: IOException) { LOG.error(e) } } } @Throws(IOException::class) private fun copyPrebuiltIndicesToIndexRoot(prebuiltIndicesRoot: File): File { val indexRoot = File(IndexInfrastructure.getPersistentIndexRoot(), "prebuilt/" + name) FileUtil.copyDir(prebuiltIndicesRoot, indexRoot) return indexRoot } private fun findPrebuiltIndicesRoot(): File? { val path: String? = System.getProperty(PREBUILT_INDICES_PATH_PROPERTY) if (path != null && File(path).exists()) { return File(path) } val f = indexRoot() return if (f.exists()) f else null } open fun indexRoot():File = File(PathManager.getHomePath(), "index/$name") // compiled binary } @TestOnly fun PrebuiltStubsProviderBase.reset() { this.init() }
platform/lang-impl/src/com/intellij/psi/stubs/PrebuiltStubs.kt
585607596
package com.example.andretortolano.githubsearch.ui.screens.showrepository import com.example.andretortolano.githubsearch.api.github.responses.Repository import com.example.andretortolano.githubsearch.ui.screens.BasePresenter import com.example.andretortolano.githubsearch.ui.screens.BaseView interface ShowRepositoryContract { interface View : BaseView<Presenter> { fun showProgress() fun hideProgress() fun showRepository(repository: Repository) } interface Presenter : BasePresenter { } }
app/src/main/java/com/example/andretortolano/githubsearch/ui/screens/showrepository/ShowRepositoryContract.kt
3353274789
package OpenSourceProjects_Storybook.buildTypes import jetbrains.buildServer.configs.kotlin.v2017_2.* import jetbrains.buildServer.configs.kotlin.v2017_2.buildFeatures.commitStatusPublisher import jetbrains.buildServer.configs.kotlin.v2017_2.buildSteps.script import jetbrains.buildServer.configs.kotlin.v2017_2.failureConditions.BuildFailureOnMetric import jetbrains.buildServer.configs.kotlin.v2017_2.failureConditions.failOnMetricChange import jetbrains.buildServer.configs.kotlin.v2017_2.triggers.VcsTrigger import jetbrains.buildServer.configs.kotlin.v2017_2.triggers.vcs object OpenSourceProjects_Storybook_SBNext : BuildType({ uuid = "dc66f07a-281f-4434-97ca-f1480b7cfc51" id = "OpenSourceProjects_Storybook_SBNext" name = "SBNext" artifactRules = "ui/out => demo.zip" vcs { root("OpenSourceProjects_Storybook_SBNext") } steps { script { name = "Install" scriptContent = "yarn" dockerImage = "node:latest" } script { name = "Lint" scriptContent = "yarn lint" dockerImage = "node:latest" } script { name = "Test" enabled = false scriptContent = "yarn test" dockerImage = "node:latest" } script { name = "Build" workingDir = "server" scriptContent = "yarn build" dockerImage = "node:latest" } script { name = "Export" workingDir = "demo" scriptContent = "yarn export" dockerImage = "node:latest" } } triggers { vcs { } } requirements { doesNotContain("env.OS", "Windows") } })
.teamcity/OpenSourceProjects_Storybook/buildTypes/OpenSourceProjects_Storybook_SBNext.kt
3789846975
import common.hadoop.extensions.split import org.apache.hadoop.io.Text import org.apache.hadoop.mapreduce.Mapper import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs /* Input format is of type: <s#id>\t<date>,<temp> */ class SensorsMapperType1: Mapper<Text, Text, Text, SensorData>() { lateinit var multipleOutputs: MultipleOutputs<Text, SensorData> override fun setup(context: Context) { multipleOutputs = MultipleOutputs(context) } override fun map(key: Text, value: Text, context: Context) { val values = value.split(",") val date = values[0] val temp = values[1].toFloat() val sensorData = SensorData(date, temp) val threshold = context.configuration.get(THRESHOLD).toFloat() if (temp >= threshold) { multipleOutputs.write(HIGH_TEMP, key, sensorData) } else { multipleOutputs.write(LOW_TEMP, key, sensorData) } } override fun cleanup(context: Context?) { multipleOutputs.close() } }
03_sensors-analysis/src/main/kotlin/SensorsMapperType1.kt
2729455533
package com.vanniktech.code.quality.tools open class DetektExtension { /** * Ability to enable or disable only detekt for every subproject that is not ignored. * @since 0.6.0 */ var enabled: Boolean = true /** @since 0.6.0 */ var toolVersion: String = "1.0.0" /** @since 0.6.0 */ var config: String = "code_quality_tools/detekt.yml" /** * Optional baseline file. If one is present it will be used in the detektCheck task. * If this name is specified however the file is not present it will be generated. * This mirrors the baseline mechanism from Android Lint. * * @since 0.11.0 */ var baselineFileName: String? = null /** * Whether to failFast or not. This will be forwarded to the CLI starting with Detekt 1.0.0 RC13 * @since 0.18.0 */ var failFast: Boolean = true /** * Whether to use preconfigured defaults. Allows provided configurations to override them. * @since 0.19.0 */ var buildUponDefaultConfig: Boolean = false /** * Enables parallel compilation of source files. * Should only be used if the analyzing project has more than ~200 Kotlin files. * @since 0.19.0 */ var parallel: Boolean = false /** * Directories to look for source files. * Defaults to current directory. * * @since 0.21.0 */ var input: String = "." }
src/main/kotlin/com/vanniktech/code/quality/tools/DetektExtension.kt
1995999721
package de.sudoq.persistence.game import de.sudoq.model.game.Assistances import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes import de.sudoq.persistence.sudoku.sudokuTypes.SudokuTypesListBE import de.sudoq.persistence.XmlAttribute import de.sudoq.persistence.XmlTree import de.sudoq.persistence.Xmlable import java.util.* import kotlin.math.pow class GameSettingsBE(val assistances: BitSet = BitSet(), var isLefthandModeSet: Boolean = false, var isHelperSet: Boolean = false, var isGesturesSet: Boolean = false, val wantedTypesList: SudokuTypesListBE = SudokuTypesListBE(listOf(*SudokuTypes.values())) ) : Xmlable { /** * Sets an assistance to true * * @param assistance The assistance to set */ fun setAssistance(assistance: Assistances) { assistances.set( 2.0.pow((assistance.ordinal + 1).toDouble()).toInt() ) //TODO that looks wrong... } /* to and from string */ override fun toXmlTree(): XmlTree { val representation = XmlTree("gameSettings") representation.addAttribute( XmlAttribute( "assistances", convertAssistancesToString() ) ) //TODO scrap that, representation as 0,1 is ugly -> save all with name, then make all of the boolean assistances enums representation.addAttribute(XmlAttribute("gestures", isGesturesSet)) representation.addAttribute(XmlAttribute("left", isLefthandModeSet)) representation.addAttribute(XmlAttribute("helper", isHelperSet)) representation.addChild(wantedTypesList.toXmlTree()) return representation } @Throws(IllegalArgumentException::class) override fun fillFromXml(xmlTreeRepresentation: XmlTree) { assistancesfromString(xmlTreeRepresentation.getAttributeValue("assistances")!!) isGesturesSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("gestures")) isLefthandModeSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("left")) isHelperSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("helper")) for (xt in xmlTreeRepresentation) if (xt.name == SudokuTypesListBE.ROOT_NAME) wantedTypesList.fillFromXml( xt ) } /** * Generates a String of "0" and "1" from the AssistanceSet. * The String car be parsed again with [assistancesfromString]. * * @return String representation of the AssistanceSet */ private fun convertAssistancesToString(): String { val bitstring = StringBuilder() for (assist in Assistances.values()) bitstring.append(if (getAssistance(assist)) "1" else "0") return bitstring.toString() } /** * Checks if an assistance is set * * @param assistance [Assistances] to check * @return true, if assistance is set, false otherwise */ open fun getAssistance(assistance: Assistances): Boolean { return assistances[2.0.pow((assistance.ordinal + 1).toDouble()).toInt()] } /** * Reads the Assistance set from a String of "0" and "1"s * * @param representation String representation of the assistances * * @throws IllegalArgumentException on parse error */ @Throws(IllegalArgumentException::class) private fun assistancesfromString(representation: String) { for ((i, assist) in Assistances.values().withIndex()) { try { if (representation[i] == '1') { setAssistance(assist) } } catch (exc: Exception) { throw IllegalArgumentException() } } } }
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/game/GameSettingsBE.kt
3385674242
/* * Copyright (C) 2017 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.navigation import android.app.Activity import android.os.Bundle import android.view.View import androidx.annotation.IdRes import androidx.core.app.ActivityCompat import java.lang.ref.WeakReference /** * Entry point for navigation operations. * * This class provides utilities for finding a relevant [NavController] instance from * various common places in your application, or for performing navigation in response to * UI events. */ public object Navigation { /** * Find a [NavController] given the id of a View and its containing * [Activity]. This is a convenience wrapper around [findNavController]. * * This method will locate the [NavController] associated with this view. * This is automatically populated for the id of a [NavHost] and its children. * * @param activity The Activity hosting the view * @param viewId The id of the view to search from * @return the [NavController] associated with the view referenced by id * @throws IllegalStateException if the given viewId does not correspond with a * [NavHost] or is not within a NavHost. */ @JvmStatic public fun findNavController(activity: Activity, @IdRes viewId: Int): NavController { val view = ActivityCompat.requireViewById<View>(activity, viewId) return findViewNavController(view) ?: throw IllegalStateException( "Activity $activity does not have a NavController set on $viewId" ) } /** * Find a [NavController] given a local [View]. * * This method will locate the [NavController] associated with this view. * This is automatically populated for views that are managed by a [NavHost] * and is intended for use by various [listener][android.view.View.OnClickListener] * interfaces. * * @param view the view to search from * @return the locally scoped [NavController] to the given view * @throws IllegalStateException if the given view does not correspond with a * [NavHost] or is not within a NavHost. */ @JvmStatic public fun findNavController(view: View): NavController { return findViewNavController(view) ?: throw IllegalStateException("View $view does not have a NavController set") } /** * Create an [android.view.View.OnClickListener] for navigating * to a destination. This supports both navigating via an * [action][NavDestination.getAction] and directly navigating to a destination. * * @param resId an [action][NavDestination.getAction] id or a destination id to * navigate to when the view is clicked * @param args arguments to pass to the final destination * @return a new click listener for setting on an arbitrary view */ @JvmStatic @JvmOverloads public fun createNavigateOnClickListener( @IdRes resId: Int, args: Bundle? = null ): View.OnClickListener { return View.OnClickListener { view -> findNavController(view).navigate(resId, args) } } /** * Create an [android.view.View.OnClickListener] for navigating * to a destination via a generated [NavDirections]. * * @param directions directions that describe this navigation operation * @return a new click listener for setting on an arbitrary view */ @JvmStatic public fun createNavigateOnClickListener(directions: NavDirections): View.OnClickListener { return View.OnClickListener { view -> findNavController(view).navigate(directions) } } /** * Associates a NavController with the given View, allowing developers to use * [findNavController] and [findNavController] with that * View or any of its children to retrieve the NavController. * * This is generally called for you by the hosting [NavHost]. * @param view View that should be associated with the given NavController * @param controller The controller you wish to later retrieve via * [findNavController] */ @JvmStatic public fun setViewNavController(view: View, controller: NavController?) { view.setTag(R.id.nav_controller_view_tag, controller) } /** * Recurse up the view hierarchy, looking for the NavController * @param view the view to search from * @return the locally scoped [NavController] to the given view, if found */ private fun findViewNavController(view: View): NavController? = generateSequence(view) { it.parent as? View? }.mapNotNull { getViewNavController(it) }.firstOrNull() @Suppress("UNCHECKED_CAST") private fun getViewNavController(view: View): NavController? { val tag = view.getTag(R.id.nav_controller_view_tag) var controller: NavController? = null if (tag is WeakReference<*>) { controller = (tag as WeakReference<NavController>).get() } else if (tag is NavController) { controller = tag } return controller } }
navigation/navigation-runtime/src/main/java/androidx/navigation/Navigation.kt
623557156
package de.reiss.bible2net.theword.main.content import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.util.Date @RunWith(JUnit4::class) class TheWordViewModelTest { @get:Rule var instantExecutorRule = InstantTaskExecutorRule() private lateinit var viewModel: TheWordViewModel private val repository: TheWordRepository = mock() @Before fun setUp() { viewModel = TheWordViewModel(repository) } @Test fun loadTheWord() { val date = Date() viewModel.loadTheWord(date) argumentCaptor<Date>().apply { verify(repository).getTheWordFor(capture(), any()) assertEquals(date, allValues[0]) } } @Test fun loadNote() { val date = Date() viewModel.loadNote(date) argumentCaptor<Date>().apply { verify(repository).getNoteFor(capture(), any()) assertEquals(date, allValues[0]) } } }
app/src/test/java/de/reiss/bible2net/theword/main/content/TheWordViewModelTest.kt
3757038002
package abi43_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.fragment.app.Fragment import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.stripe.android.googlepaylauncher.GooglePayEnvironment import com.stripe.android.googlepaylauncher.GooglePayLauncher import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher class GooglePayFragment : Fragment() { private var googlePayLauncher: GooglePayLauncher? = null private var googlePayMethodLauncher: GooglePayPaymentMethodLauncher? = null private var isGooglePayMethodLauncherReady: Boolean = false private var isGooglePayLauncherReady: Boolean = false private lateinit var localBroadcastManager: LocalBroadcastManager private fun onGooglePayMethodLauncherReady(isReady: Boolean) { isGooglePayMethodLauncherReady = true if (isGooglePayLauncherReady) { onGooglePayReady(isReady) } } private fun onGooglePayLauncherReady(isReady: Boolean) { isGooglePayLauncherReady = true if (isGooglePayMethodLauncherReady) { onGooglePayReady(isReady) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { localBroadcastManager = LocalBroadcastManager.getInstance(requireContext()) return FrameLayout(requireActivity()).also { it.visibility = View.GONE } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val testEnv = arguments?.getBoolean("testEnv") val merchantName = arguments?.getString("merchantName").orEmpty() val countryCode = arguments?.getString("countryCode").orEmpty() val isEmailRequired = arguments?.getBoolean("isEmailRequired") ?: false val existingPaymentMethodRequired = arguments?.getBoolean("existingPaymentMethodRequired") ?: false val billingAddressConfigBundle = arguments?.getBundle("billingAddressConfig") ?: Bundle() val isRequired = billingAddressConfigBundle.getBoolean("isRequired") val formatString = billingAddressConfigBundle.getString("format").orEmpty() val isPhoneNumberRequired = billingAddressConfigBundle.getBoolean("isPhoneNumberRequired") val billingAddressConfig = mapToGooglePayPaymentMethodLauncherBillingAddressConfig(formatString, isRequired, isPhoneNumberRequired) googlePayMethodLauncher = GooglePayPaymentMethodLauncher( fragment = this, config = GooglePayPaymentMethodLauncher.Config( environment = if (testEnv == true) GooglePayEnvironment.Test else GooglePayEnvironment.Production, merchantCountryCode = countryCode, merchantName = merchantName, billingAddressConfig = billingAddressConfig, isEmailRequired = isEmailRequired, existingPaymentMethodRequired = existingPaymentMethodRequired ), readyCallback = ::onGooglePayMethodLauncherReady, resultCallback = ::onGooglePayResult ) val paymentMethodBillingAddressConfig = mapToGooglePayLauncherBillingAddressConfig(formatString, isRequired, isPhoneNumberRequired) googlePayLauncher = GooglePayLauncher( fragment = this, config = GooglePayLauncher.Config( environment = if (testEnv == true) GooglePayEnvironment.Test else GooglePayEnvironment.Production, merchantCountryCode = countryCode, merchantName = merchantName, billingAddressConfig = paymentMethodBillingAddressConfig, isEmailRequired = isEmailRequired, existingPaymentMethodRequired = existingPaymentMethodRequired ), readyCallback = ::onGooglePayLauncherReady, resultCallback = ::onGooglePayResult ) val intent = Intent(ON_GOOGLE_PAY_FRAGMENT_CREATED) localBroadcastManager.sendBroadcast(intent) } fun presentForPaymentIntent(clientSecret: String) { val launcher = googlePayLauncher ?: run { val intent = Intent(ON_GOOGLE_PAY_RESULT) intent.putExtra("error", "GooglePayLauncher is not initialized.") localBroadcastManager.sendBroadcast(intent) return } runCatching { launcher.presentForPaymentIntent(clientSecret) }.onFailure { val intent = Intent(ON_GOOGLE_PAY_RESULT) intent.putExtra("error", it.localizedMessage) localBroadcastManager.sendBroadcast(intent) } } fun presentForSetupIntent(clientSecret: String, currencyCode: String) { val launcher = googlePayLauncher ?: run { val intent = Intent(ON_GOOGLE_PAY_RESULT) intent.putExtra("error", "GooglePayLauncher is not initialized.") localBroadcastManager.sendBroadcast(intent) return } runCatching { launcher.presentForSetupIntent(clientSecret, currencyCode) }.onFailure { val intent = Intent(ON_GOOGLE_PAY_RESULT) intent.putExtra("error", it.localizedMessage) localBroadcastManager.sendBroadcast(intent) } } fun createPaymentMethod(currencyCode: String, amount: Int) { val launcher = googlePayMethodLauncher ?: run { val intent = Intent(ON_GOOGLE_PAYMENT_METHOD_RESULT) intent.putExtra("error", "GooglePayPaymentMethodLauncher is not initialized.") localBroadcastManager.sendBroadcast(intent) return } runCatching { launcher.present( currencyCode = currencyCode, amount = amount ) }.onFailure { val intent = Intent(ON_GOOGLE_PAYMENT_METHOD_RESULT) intent.putExtra("error", it.localizedMessage) localBroadcastManager.sendBroadcast(intent) } } private fun onGooglePayReady(isReady: Boolean) { val intent = Intent(ON_INIT_GOOGLE_PAY) intent.putExtra("isReady", isReady) localBroadcastManager.sendBroadcast(intent) } private fun onGooglePayResult(result: GooglePayLauncher.Result) { val intent = Intent(ON_GOOGLE_PAY_RESULT) intent.putExtra("paymentResult", result) localBroadcastManager.sendBroadcast(intent) } private fun onGooglePayResult(result: GooglePayPaymentMethodLauncher.Result) { val intent = Intent(ON_GOOGLE_PAYMENT_METHOD_RESULT) intent.putExtra("paymentResult", result) localBroadcastManager.sendBroadcast(intent) } private fun mapToGooglePayLauncherBillingAddressConfig(formatString: String, isRequired: Boolean, isPhoneNumberRequired: Boolean): GooglePayLauncher.BillingAddressConfig { val format = when (formatString) { "FULL" -> GooglePayLauncher.BillingAddressConfig.Format.Full "MIN" -> GooglePayLauncher.BillingAddressConfig.Format.Min else -> GooglePayLauncher.BillingAddressConfig.Format.Min } return GooglePayLauncher.BillingAddressConfig( isRequired = isRequired, format = format, isPhoneNumberRequired = isPhoneNumberRequired ) } private fun mapToGooglePayPaymentMethodLauncherBillingAddressConfig(formatString: String, isRequired: Boolean, isPhoneNumberRequired: Boolean): GooglePayPaymentMethodLauncher.BillingAddressConfig { val format = when (formatString) { "FULL" -> GooglePayPaymentMethodLauncher.BillingAddressConfig.Format.Full "MIN" -> GooglePayPaymentMethodLauncher.BillingAddressConfig.Format.Min else -> GooglePayPaymentMethodLauncher.BillingAddressConfig.Format.Min } return GooglePayPaymentMethodLauncher.BillingAddressConfig( isRequired = isRequired, format = format, isPhoneNumberRequired = isPhoneNumberRequired ) } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/GooglePayFragment.kt
1898939768
package com.xenoage.zong.core.position import com.xenoage.utils.math.Fraction import com.xenoage.utils.math._0 /** * Time in a score. * Like a [MP], but consists only of measure and beat. */ data class Time( /** The measure index */ val measure: Int, /** The beat within the measure */ val beat: Fraction ) : Comparable<Time> { /** Compares this [Time] with the given one */ override fun compareTo(time: Time) = when { measure < time.measure -> -1 measure > time.measure -> 1 else -> beat.compareTo(time.beat) } override fun toString() = "[Measure = " + measure + ", Beat = " + beat.numerator + "/" + beat.denominator + "]" fun toStringCompact() = "m" + measure + ",b" + beat.numerator + "/" + beat.denominator } /** Creates a new [Time] at the given measure and beat. */ fun time(measure: Int, beat: Fraction) = Time(measure, beat) /** Musical position with all values set to 0. */ val time0 = Time(0, _0)
core/src/com/xenoage/zong/core/position/Time.kt
2408296674
package solutions import solutions.day01.Day1 import solutions.day02.Day2 import solutions.day03.Day3 import solutions.day04.Day4 import solutions.day05.Day5 import solutions.day06.Day6 import solutions.day07.Day7 import solutions.day08.Day8 import solutions.day09.Day9 import solutions.day10.Day10 import solutions.day11.Day11 import solutions.day12.Day12 import solutions.day13.Day13 import solutions.day14.Day14 import solutions.day15.Day15 import solutions.day16.Day16 import solutions.day18.Day18 import solutions.day20.Day20 import solutions.day21.Day21 import solutions.day22.Day22 import solutions.day23.Day23 import solutions.day24.Day24 import solutions.day25.Day25 import utils.readFile import kotlin.system.measureNanoTime enum class Days { Day01, Day02, Day03, Day04, Day05, Day06, Day07, Day08, Day09, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day18, Day20, Day22, Day21, Day23, Day24, Day25 } fun Long.toSeconds(): Double = this / (10e8) fun Long.toMilliseconds(): Double = this / (10e5) fun main(args: Array<String>) { val time = measureNanoTime { val partTwo = false val day = Days.Day16 val input = getInput(day) val solver = when (day) { Days.Day01 -> Day1() Days.Day02 -> Day2() Days.Day03 -> Day3() Days.Day04 -> Day4() Days.Day05 -> Day5() Days.Day06 -> Day6() Days.Day07 -> Day7() Days.Day08 -> Day8() Days.Day09 -> Day9() Days.Day10 -> Day10() Days.Day11 -> Day11() Days.Day12 -> Day12() Days.Day13 -> Day13() Days.Day14 -> Day14() Days.Day15 -> Day15() Days.Day16 -> Day16() Days.Day18 -> Day18() Days.Day20 -> Day20() Days.Day21 -> Day21() Days.Day22 -> Day22() Days.Day23 -> Day23() Days.Day24 -> Day24() Days.Day25 -> Day25() } printAnswer(day.name, solver.solve(input, partTwo)) } println("Took ${time.toSeconds()} seconds") println("Took ${time.toMilliseconds()} milliseconds") } fun getInput(day: Days): List<String> { val solutions = "src/main/kotlin/solutions" return readFile("$solutions/${day.name.toLowerCase()}/input") } fun printAnswer(msg: String, answer: String) { println("$msg: $answer") }
src/main/kotlin/solutions/Main.kt
4119558508
package com.riaektiv.fdp.common.xwire import com.google.protobuf.ByteString import org.junit.Assert.assertEquals import org.junit.Test /** * Created: 3/11/2018, 11:01 AM Eastern Time * * @author Sergey Chuykov */ class XWireProtoBufTest { @Test fun test() { val header = XWire.Header.newBuilder().setReplyTo("replyTo").build() val body = ByteString.copyFromUtf8("Ok") val wire = XWire.Wire.newBuilder() .setHeader(header) .setBody(body) .build() val bytes = wire.toByteArray() val msg = XWire.Wire.newBuilder().mergeFrom(bytes) assertEquals("replyTo", msg.header.replyTo) val bb = msg.body.asReadOnlyByteBuffer() val text = Charsets.UTF_8.decode(bb).toString(); assertEquals("Ok", text) } }
fdp-common/src/test/java/com/riaektiv/fdp/common/xwire/XWireProtoBufTest.kt
4249927057
package com.teamwizardry.librarianlib.facade.container.builtin import java.util.function.Supplier public fun interface ContainerLock { public fun isLocked(): Boolean public class ManualLock(private var isLocked: Boolean) : ContainerLock { public fun setLocked(value: Boolean) { this.isLocked = value } public fun lock() { this.isLocked = true } public fun unlock() { this.isLocked = false } override fun isLocked(): Boolean { return isLocked } } public class StaticLock(private val isLocked: Boolean) : ContainerLock { override fun isLocked(): Boolean { return isLocked } } /** * A slot intended to prevent certain kinds of item duplication glitches. To do this, it records the value returned * from the [verificationCallback] and before every operation it verifies that the callback returns the same object. * * The specific dupe this prevents is (using a backpack as an example): * * - the player opens a backpack item * - you open a container and add the held backpack's inventory to it * - the player puts items in the backpack inventory * - the player uses a "player interface" of some sort to take the backpack out of their inventory and put it in a * chest, which copies the itemstack and discards the existing instance * - your screen is now accessing an "orphaned" backpack, so the player can pull items out without affecting the * instance in the chest * - congratulations, you've just introduced a new dupe! * * ***!NOTE!*** * It seems the default inventory code in 1.16+ does *not* actually *replace* the ItemStack in the inventory, it * just *modifies* it. This means you can *not* use the actual stack, you'll have to use something like a capability * instead. (e.g. `player.getItemInHand(...).getCapability(...)`) * * The code is designed to be more general though, so you can use any object as the verification. * * * @param verificationCallback A callback that, if its value changes, will lock the slot. * @param isClient Whether this slot is in the client container. ItemStack object identity in particular is not * preserved on the client, so the check has to be disabled there. */ public class ConsistencyLock( private val isClient: Boolean, private val verificationCallback: Supplier<Any> ) : ContainerLock { private val verificationReference: Any = verificationCallback.get() override fun isLocked(): Boolean { if (isClient) return false return verificationCallback.get() !== verificationReference } } public companion object { @JvmField public val LOCKED: ContainerLock = StaticLock(true) @JvmField public val UNLOCKED: ContainerLock = StaticLock(false) } }
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/builtin/ContainerLock.kt
3485362680
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.ext.isIntentionPreviewElement import org.rust.openapiext.checkReadAccessAllowed import org.rust.openapiext.checkWriteAccessAllowed /** * A base class for implementing intentions: actions available via "light bulb" / `Alt+Enter`. * * The cool thing about intentions is their UX: there is a huge number of intentions, * and they all can be invoked with a single `Alt + Enter` shortcut. This is possible * because at the position of the cursor only small number of intentions is applicable. * * So, intentions consists of two functions: [findApplicableContext] functions determines * if the intention can be applied at the given position, it is used to populate "light bulb" list. * [invoke] is called when the user selects the intention from the list and must apply the changes. * * The context collected by [findApplicableContext] is gathered into [Ctx] object and is passed to * [invoke]. In general, [invoke] should be infallible: if you need to check if some element is not * null, do this in [findApplicableContext] and pass the element via the context. * * [findApplicableContext] is executed under a read action, and [invoke] under a write action. */ abstract class RsElementBaseIntentionAction<Ctx> : BaseElementAtCaretIntentionAction() { /** * Return `null` if the intention is not applicable, otherwise collect and return * all the necessary info to actually apply the intention. */ abstract fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Ctx? abstract fun invoke(project: Project, editor: Editor, ctx: Ctx) final override fun invoke(project: Project, editor: Editor, element: PsiElement) { val ctx = findApplicableContext(project, editor, element) ?: return if (startInWriteAction() && !element.isIntentionPreviewElement) { checkWriteAccessAllowed() } invoke(project, editor, ctx) } final override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { checkReadAccessAllowed() return findApplicableContext(project, editor, element) != null } }
src/main/kotlin/org/rust/ide/intentions/RsElementBaseIntentionAction.kt
1208471838
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.currency import com.mvcoding.expensius.data.ParameterDataSource import com.mvcoding.expensius.data.testMemoryParameterDataSource import com.mvcoding.expensius.model.ExchangeRateCurrencies import com.mvcoding.expensius.model.extensions.aCurrency import com.mvcoding.expensius.model.extensions.anAmount import com.mvcoding.expensius.model.extensions.anExchangeRateCurrencies import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.verify import org.junit.Test import rx.Observable import rx.observers.TestSubscriber import java.math.BigDecimal class ExchangeRatesSourceTest { @Test fun `behaves like memory parameter data source`() { testMemoryParameterDataSource( anExchangeRateCurrencies(), anExchangeRateCurrencies(), anAmount(), anAmount()) { dataSource: ParameterDataSource<ExchangeRateCurrencies, BigDecimal> -> ExchangeRatesSource { dataSource.data(it) } } } @Test fun `returns ONE when currencies are same`() { val currency = aCurrency() val getExchangeRate = mock<(ExchangeRateCurrencies) -> Observable<BigDecimal>>() val exchangeRatesSource = ExchangeRatesSource(getExchangeRate) val subscriber = TestSubscriber<BigDecimal>() exchangeRatesSource.data(ExchangeRateCurrencies(currency, currency)).subscribe(subscriber) subscriber.assertValue(BigDecimal.ONE) verify(getExchangeRate, never()).invoke(any()) } }
app-core/src/test/kotlin/com/mvcoding/expensius/feature/currency/ExchangeRatesSourceTest.kt
1883204958
package com.teamwizardry.librarianlib.facade.pastry.layers import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layers.SpriteLayer import com.teamwizardry.librarianlib.facade.pastry.ExperimentalPastryAPI import com.teamwizardry.librarianlib.facade.pastry.PastryTexture import com.teamwizardry.librarianlib.core.util.vec @ExperimentalPastryAPI public class PastryTabPane: GuiLayer { private val background = SpriteLayer(PastryTexture.tabsBody) public val pages: List<PastryTabPage> get() = children.filterIsInstance<PastryTabPage>().filter { it.isVisible } public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(): super() init { this.add(background) } override fun layoutChildren() { pages.forEach { it.frame = this.bounds } children.forEach { it.runLayout() } var x = 1.0 val maxTabHeight = pages.map { it.tab.height }.maxOrNull() ?: 0.0 pages.forEach { it.tab.pos = vec(x, maxTabHeight - it.tab.height) x += it.tab.width + 1 it.contents.frame = it.bounds.offset(0, maxTabHeight, 0, 0) } background.frame = this.bounds.offset(0, maxTabHeight - 1, 0, 0) } }
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryTabPane.kt
533132381
package org.jetbrains.fortran.lang.psi.mixin import com.intellij.ide.projectView.PresentationData import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import org.jetbrains.fortran.FortranIcons import org.jetbrains.fortran.lang.FortranTypes import org.jetbrains.fortran.lang.psi.* import org.jetbrains.fortran.lang.stubs.FortranEntityDeclStub import org.jetbrains.fortran.lang.psi.ext.FortranStubbedNamedElementImpl import javax.swing.Icon abstract class FortranEntityDeclMixin : FortranStubbedNamedElementImpl<FortranEntityDeclStub>, FortranEntityDecl { constructor(node: ASTNode) : super(node) constructor(stub: FortranEntityDeclStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getNameIdentifier(): PsiElement? = stub?.psi ?: findChildByType(FortranTypes.IDENTIFIER) override fun getTextOffset(): Int = node.startOffset override fun getName(): String? = stub?.name ?: nameIdentifier?.text override fun setName(name: String): PsiElement? { return this } override fun getIcon(flags: Int): Icon? { val grandParent = parent.parent if (grandParent is FortranProgramUnit) { return when(grandParent) { is FortranMainProgram -> FortranIcons.mainProgramIcon is FortranFunctionSubprogram -> FortranIcons.functionIcon is FortranSubroutineSubprogram -> FortranIcons.subroutineIcon is FortranModule -> FortranIcons.moduleIcon is FortranSubmodule -> FortranIcons.submoduleIcon is FortranSeparateModuleSubprogram -> FortranIcons.separateModuleSubprogramIcon is FortranBlockData -> FortranIcons.blockDataIcon else -> super.getIcon(flags) } } if (grandParent is FortranDerivedTypeDef) return FortranIcons.typeIcon if (grandParent is FortranDataComponentDefStmt) return FortranIcons.variableIcon if (parent is FortranTypeDeclarationStmt) return FortranIcons.variableIcon return super.getIcon(flags) } }
src/main/java/org/jetbrains/fortran/lang/psi/mixin/FortranEntityDeclMixin.kt
3437095615
package com.github.jk1.ytplugin.timeTracker import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.rest.TimeTrackerRestClient import com.github.jk1.ytplugin.tasks.NoYouTrackRepositoryException import com.github.jk1.ytplugin.tasks.YouTrackServer import com.intellij.concurrency.JobScheduler import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.intellij.serviceContainer.AlreadyDisposedException import java.util.* import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities /** * Manages timed issueWorkItems store updates for active projects * todo: the service is initialized lazily, so it's only behave as expected because of a #subscribe call * todo: convert into a post startup activity */ @Service class IssueWorkItemsStoreUpdaterService(override val project: Project) : Disposable, ComponentAware { // todo: customizable update interval private val timedRefreshTask: ScheduledFuture<*> = JobScheduler.getScheduler().scheduleWithFixedDelay({ SwingUtilities.invokeLater { if (!project.isDisposed) { taskManagerComponent.getAllConfiguredYouTrackRepositories().forEach { issueWorkItemsStoreComponent[it].update(it) } } } }, 5, 5, TimeUnit.MINUTES) private val listeners: MutableSet<() -> Unit> = mutableSetOf() override fun dispose() { try { val repo = taskManagerComponent.getActiveYouTrackRepository() val timer = timeTrackerComponent if (timer.isWhenProjectClosedEnabled) { logger.debug("state PROJECT_CLOSE with posting enabled") postOnProjectClose(timer, repo) } } catch (e: NoYouTrackRepositoryException) { logger.warn("NoYouTrackRepository: ${e.message}") } catch (e: AlreadyDisposedException) { logger.debug("Container is already disposed") logger.debug(e) } timedRefreshTask.cancel(true) } private fun postOnProjectClose(timer: TimeTracker, repo: YouTrackServer) { try { timer.stop() repo.let { it1 -> val connector = TimeTrackerConnector(it1, project) connector.postWorkItemToServer(timer.issueId, timer.recordedTime, timer.type, timer.comment, (Date().time).toString(), mapOf()) // post not only last recorded item, but all saved items as well connector.postSavedWorkItemsToServer(spentTimePerTaskStorage.getAllStoredItems()) } val propertiesStore: PropertiesComponent = PropertiesComponent.getInstance(project) propertiesStore.setValue("spentTimePerTaskStorage.store", timer.spentTimePerTaskStorage.getAllStoredItems().toString()) logger.debug("time tracker stopped on PROJECT_CLOSE with time ${timer.recordedTime}") } catch (e: IllegalStateException) { logger.debug("Could not stop time tracking: timer is not started: ${e.message}") } } fun subscribe(listener: () -> Unit) { listeners.add(listener) } fun onAfterUpdate() { listeners.forEach { it.invoke() } } }
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/IssueWorkItemsStoreUpdaterService.kt
2894381493
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycrypt.asymmetric import com.pvryan.easycrypt.Constants import com.pvryan.easycrypt.extensions.asString import com.pvryan.easycrypt.extensions.fromBase64 import org.jetbrains.anko.AnkoLogger import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.security.InvalidParameterException import java.security.Signature import java.security.SignatureException import java.security.interfaces.RSAPublicKey @Suppress("ClassName") internal object performVerify : AnkoLogger { private val signature = Signature.getInstance(Constants.SIGNATURE_ALGORITHM) @JvmSynthetic internal fun <T> invoke(input: T, publicKey: RSAPublicKey, sigFile: File, evl: ECVerifiedListener) { signature.initVerify(publicKey) when (input) { is InputStream -> { val buffer = ByteArray(8192) var bytesCopied: Long = 0 try { val size = if (input is FileInputStream) input.channel.size() else -1 var read = input.read(buffer) while (read > -1) { signature.update(buffer, 0, read) bytesCopied += read evl.onProgress(read, bytesCopied, size) read = input.read(buffer) } try { evl.onSuccess(signature.verify( sigFile.readBytes().asString().fromBase64())) } catch (e: IllegalArgumentException) { evl.onFailure(Constants.ERR_BAD_BASE64, e) } catch (e: SignatureException) { evl.onFailure(Constants.ERR_VERIFY_EXCEPTION, e) } } catch (e: IOException) { evl.onFailure(Constants.ERR_CANNOT_WRITE, e) } } else -> evl.onFailure(Constants.ERR_INPUT_TYPE_NOT_SUPPORTED, InvalidParameterException()) } } }
easycrypt/src/main/java/com/pvryan/easycrypt/asymmetric/performVerify.kt
1432068986
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.junit4 import androidx.activity.ComponentActivity import androidx.compose.runtime.Composable import androidx.compose.ui.test.AndroidComposeUiTestEnvironment import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.IdlingResource import androidx.compose.ui.test.MainTestClock import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.SemanticsNodeInteractionCollection import androidx.compose.ui.unit.Density import androidx.test.ext.junit.rules.ActivityScenarioRule import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement actual fun createComposeRule(): ComposeContentTestRule = createAndroidComposeRule<ComponentActivity>() /** * Factory method to provide android specific implementation of [createComposeRule], for a given * activity class type [A]. * * This method is useful for tests that require a custom Activity. This is usually the case for * tests where the compose content is set by that Activity, instead of via the test rule's * [setContent][ComposeContentTestRule.setContent]. Make sure that you add the provided activity * into your app's manifest file (usually in main/AndroidManifest.xml). * * This creates a test rule that is using [ActivityScenarioRule] as the activity launcher. If you * would like to use a different one you can create [AndroidComposeTestRule] directly and supply * it with your own launcher. * * If your test doesn't require a specific Activity, use [createComposeRule] instead. */ inline fun <reified A : ComponentActivity> createAndroidComposeRule(): AndroidComposeTestRule<ActivityScenarioRule<A>, A> { // TODO(b/138993381): By launching custom activities we are losing control over what content is // already there. This is issue in case the user already set some compose content and decides // to set it again via our API. In such case we won't be able to dispose the old composition. // Other option would be to provide a smaller interface that does not expose these methods. return createAndroidComposeRule(A::class.java) } /** * Factory method to provide android specific implementation of [createComposeRule], for a given * [activityClass]. * * This method is useful for tests that require a custom Activity. This is usually the case for * tests where the compose content is set by that Activity, instead of via the test rule's * [setContent][ComposeContentTestRule.setContent]. Make sure that you add the provided activity * into your app's manifest file (usually in main/AndroidManifest.xml). * * This creates a test rule that is using [ActivityScenarioRule] as the activity launcher. If you * would like to use a different one you can create [AndroidComposeTestRule] directly and supply * it with your own launcher. * * If your test doesn't require a specific Activity, use [createComposeRule] instead. */ fun <A : ComponentActivity> createAndroidComposeRule( activityClass: Class<A> ): AndroidComposeTestRule<ActivityScenarioRule<A>, A> = AndroidComposeTestRule( activityRule = ActivityScenarioRule(activityClass), activityProvider = ::getActivityFromTestRule ) /** * Factory method to provide an implementation of [ComposeTestRule] that doesn't create a compose * host for you in which you can set content. * * This method is useful for tests that need to create their own compose host during the test. * The returned test rule will not create a host, and consequently does not provide a * `setContent` method. To set content in tests using this rule, use the appropriate `setContent` * methods from your compose host. * * A typical use case on Android is when the test needs to launch an Activity (the compose host) * after one or more dependencies have been injected. */ fun createEmptyComposeRule(): ComposeTestRule = AndroidComposeTestRule<TestRule, ComponentActivity>( activityRule = TestRule { base, _ -> base }, activityProvider = { error( "createEmptyComposeRule() does not provide an Activity to set Compose content in." + " Launch and use the Activity yourself, or use createAndroidComposeRule()." ) } ) @OptIn(ExperimentalTestApi::class) class AndroidComposeTestRule<R : TestRule, A : ComponentActivity> private constructor( val activityRule: R, private val environment: AndroidComposeUiTestEnvironment<A> ) : ComposeContentTestRule { private val composeTest = environment.test /** * Android specific implementation of [ComposeContentTestRule], where compose content is hosted * by an Activity. * * The Activity is normally launched by the given [activityRule] before the test starts, but it * is possible to pass a test rule that chooses to launch an Activity on a later time. The * Activity is retrieved from the [activityRule] by means of the [activityProvider], which can be * thought of as a getter for the Activity on the [activityRule]. If you use an [activityRule] * that launches an Activity on a later time, you should make sure that the Activity is launched * by the time or while the [activityProvider] is called. * * The [AndroidComposeTestRule] wraps around the given [activityRule] to make sure the Activity * is launched _after_ the [AndroidComposeTestRule] has completed all necessary steps to control * and monitor the compose content. * * @param activityRule Test rule to use to launch the Activity. * @param activityProvider Function to retrieve the Activity from the given [activityRule]. */ constructor(activityRule: R, activityProvider: (R) -> A) : this( activityRule, AndroidComposeUiTestEnvironment { activityProvider(activityRule) } ) /** * Provides the current activity. * * Avoid calling often as it can involve synchronization and can be slow. */ val activity: A get() = checkNotNull(composeTest.activity) { "Host activity not found" } override fun apply(base: Statement, description: Description): Statement { val testStatement = activityRule.apply(base, description) return object : Statement() { override fun evaluate() { environment.runTest { testStatement.evaluate() } } } } @Deprecated( message = "Do not instantiate this Statement, use AndroidComposeTestRule instead", level = DeprecationLevel.ERROR ) inner class AndroidComposeStatement(private val base: Statement) : Statement() { override fun evaluate() { base.evaluate() } } /* * WHEN THE NAME AND SHAPE OF THE NEW COMMON INTERFACES HAS BEEN DECIDED, * REPLACE ALL OVERRIDES BELOW WITH DELEGATION: ComposeTest by composeTest */ override val density: Density get() = composeTest.density override val mainClock: MainTestClock get() = composeTest.mainClock override fun <T> runOnUiThread(action: () -> T): T = composeTest.runOnUiThread(action) override fun <T> runOnIdle(action: () -> T): T = composeTest.runOnIdle(action) override fun waitForIdle() = composeTest.waitForIdle() override suspend fun awaitIdle() = composeTest.awaitIdle() override fun waitUntil(timeoutMillis: Long, condition: () -> Boolean) = composeTest.waitUntil(timeoutMillis, condition) override fun registerIdlingResource(idlingResource: IdlingResource) = composeTest.registerIdlingResource(idlingResource) override fun unregisterIdlingResource(idlingResource: IdlingResource) = composeTest.unregisterIdlingResource(idlingResource) override fun onNode( matcher: SemanticsMatcher, useUnmergedTree: Boolean ): SemanticsNodeInteraction = composeTest.onNode(matcher, useUnmergedTree) override fun onAllNodes( matcher: SemanticsMatcher, useUnmergedTree: Boolean ): SemanticsNodeInteractionCollection = composeTest.onAllNodes(matcher, useUnmergedTree) override fun setContent(composable: @Composable () -> Unit) = composeTest.setContent(composable) } private fun <A : ComponentActivity> getActivityFromTestRule(rule: ActivityScenarioRule<A>): A { var activity: A? = null rule.scenario.onActivity { activity = it } if (activity == null) { throw IllegalStateException("Activity was not set in the ActivityScenarioRule!") } return activity!! }
compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule.android.kt
1085046478
/* * 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 * * 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.datastore.core /** * Returns an initializer function created from a list of DataMigrations. */ internal class DataMigrationInitializer<T>() { companion object { /** * Creates an initializer from DataMigrations for use with DataStore. * * @param migrations A list of migrations that will be included in the initializer. * @return The initializer which includes the data migrations returned from the factory * functions. */ fun <T> getInitializer(migrations: List<DataMigration<T>>): suspend (api: InitializerApi<T>) -> Unit = { api -> runMigrations(migrations, api) } private suspend fun <T> runMigrations( migrations: List<DataMigration<T>>, api: InitializerApi<T> ) { val cleanUps = mutableListOf<suspend () -> Unit>() api.updateData { startingData -> migrations.fold(startingData) { data, migration -> if (migration.shouldMigrate(data)) { cleanUps.add { migration.cleanUp() } migration.migrate(data) } else { data } } } var cleanUpFailure: Throwable? = null cleanUps.forEach { cleanUp -> try { cleanUp() } catch (exception: Throwable) { if (cleanUpFailure == null) { cleanUpFailure = exception } else { cleanUpFailure!!.addSuppressed(exception) } } } // If we encountered a failure on cleanup, throw it. cleanUpFailure?.let { throw it } } } }
datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/DataMigrationInitializer.kt
1915367852
package com.raizlabs.android.dbflow.processor.definition import com.raizlabs.android.dbflow.processor.ClassNames import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition import com.raizlabs.android.dbflow.processor.definition.column.DefinitionUtils import com.raizlabs.android.dbflow.processor.utils.ModelUtils import com.raizlabs.android.dbflow.sql.QueryBuilder import com.squareup.javapoet.* import javax.lang.model.element.Modifier /** * Description: Assists in writing methods for adapters */ object InternalAdapterHelper { fun writeGetModelClass(typeBuilder: TypeSpec.Builder, modelClassName: ClassName?) { typeBuilder.addMethod(MethodSpec.methodBuilder("getModelClass") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("return \$T.class", modelClassName) .returns(ParameterizedTypeName.get(ClassName.get(Class::class.java), modelClassName)) .build()) } fun writeGetTableName(typeBuilder: TypeSpec.Builder, tableName: String?) { typeBuilder.addMethod(MethodSpec.methodBuilder("getTableName") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("return \$S", QueryBuilder.quote(tableName)) .returns(ClassName.get(String::class.java)) .build()) } fun writeUpdateAutoIncrement(typeBuilder: TypeSpec.Builder, modelClassName: TypeName?, autoIncrementDefinition: ColumnDefinition) { typeBuilder.addMethod(MethodSpec.methodBuilder("updateAutoIncrement") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) .addParameter(ClassName.get(Number::class.java), "id") .addCode(autoIncrementDefinition.updateAutoIncrementMethod) .build()) } fun writeGetCachingId(typeBuilder: TypeSpec.Builder, modelClassName: TypeName?, primaryColumns: List<ColumnDefinition>) { if (primaryColumns.size > 1) { var methodBuilder: MethodSpec.Builder = MethodSpec.methodBuilder("getCachingColumnValuesFromModel") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ArrayTypeName.of(Any::class.java), "inValues") .addParameter(modelClassName, ModelUtils.variable) for (i in primaryColumns.indices) { val column = primaryColumns[i] methodBuilder.addCode(column.getColumnAccessString(i)) } methodBuilder.addStatement("return \$L", "inValues").returns(ArrayTypeName.of(Any::class.java)) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingColumnValuesFromCursor") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ArrayTypeName.of(Any::class.java), "inValues") .addParameter(ClassNames.CURSOR, "cursor") for (i in primaryColumns.indices) { val column = primaryColumns[i] val method = DefinitionUtils.getLoadFromCursorMethodString(column.elementTypeName, column.wrapperTypeName) methodBuilder.addStatement("inValues[\$L] = \$L.\$L(\$L.getColumnIndex(\$S))", i, LoadFromCursorMethod.PARAM_CURSOR, method, LoadFromCursorMethod.PARAM_CURSOR, column.columnName) } methodBuilder.addStatement("return \$L", "inValues").returns(ArrayTypeName.of(Any::class.java)) typeBuilder.addMethod(methodBuilder.build()) } else { // single primary key var methodBuilder: MethodSpec.Builder = MethodSpec.methodBuilder("getCachingColumnValueFromModel") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) methodBuilder.addCode(primaryColumns[0].getSimpleAccessString()) .returns(Any::class.java) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingColumnValueFromCursor") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ClassNames.CURSOR, "cursor") val column = primaryColumns[0] val method = DefinitionUtils.getLoadFromCursorMethodString(column.elementTypeName, column.wrapperTypeName) methodBuilder.addStatement("return \$L.\$L(\$L.getColumnIndex(\$S))", LoadFromCursorMethod.PARAM_CURSOR, method, LoadFromCursorMethod.PARAM_CURSOR, column.columnName).returns(Any::class.java) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingId") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) .addStatement("return getCachingColumnValueFromModel(\$L)", ModelUtils.variable).returns(TypeName.OBJECT) typeBuilder.addMethod(methodBuilder.build()) } } }
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/InternalAdapterHelper.kt
1994978222
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.gestures import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.gestures.DragEvent.DragCancelled import androidx.compose.foundation.gestures.DragEvent.DragDelta import androidx.compose.foundation.gestures.DragEvent.DragStarted import androidx.compose.foundation.gestures.DragEvent.DragStopped import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.internal.JvmDefaultWithCompatibility import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Velocity import kotlin.coroutines.cancellation.CancellationException import kotlin.math.sign import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.isActive /** * State of [draggable]. Allows for a granular control of how deltas are consumed by the user as * well as to write custom drag methods using [drag] suspend function. */ @JvmDefaultWithCompatibility interface DraggableState { /** * Call this function to take control of drag logic. * * All actions that change the logical drag position must be performed within a [drag] * block (even if they don't call any other methods on this object) in order to guarantee * that mutual exclusion is enforced. * * If [drag] is called from elsewhere with the [dragPriority] higher or equal to ongoing * drag, ongoing drag will be canceled. * * @param dragPriority of the drag operation * @param block to perform drag in */ suspend fun drag( dragPriority: MutatePriority = MutatePriority.Default, block: suspend DragScope.() -> Unit ) /** * Dispatch drag delta in pixels avoiding all drag related priority mechanisms. * * **NOTE:** unlike [drag], dispatching any delta with this method will bypass scrolling of * any priority. This method will also ignore `reverseDirection` and other parameters set in * [draggable]. * * This method is used internally for low level operations, allowing implementers of * [DraggableState] influence the consumption as suits them, e.g. introduce nested scrolling. * Manually dispatching delta via this method will likely result in a bad user experience, * you must prefer [drag] method over this one. * * @param delta amount of scroll dispatched in the nested drag process */ fun dispatchRawDelta(delta: Float) } /** * Scope used for suspending drag blocks */ interface DragScope { /** * Attempts to drag by [pixels] px. */ fun dragBy(pixels: Float) } /** * Default implementation of [DraggableState] interface that allows to pass a simple action that * will be invoked when the drag occurs. * * This is the simplest way to set up a [draggable] modifier. When constructing this * [DraggableState], you must provide a [onDelta] lambda, which will be invoked whenever * drag happens (by gesture input or a custom [DraggableState.drag] call) with the delta in * pixels. * * If you are creating [DraggableState] in composition, consider using [rememberDraggableState]. * * @param onDelta callback invoked when drag occurs. The callback receives the delta in pixels. */ fun DraggableState(onDelta: (Float) -> Unit): DraggableState = DefaultDraggableState(onDelta) /** * Create and remember default implementation of [DraggableState] interface that allows to pass a * simple action that will be invoked when the drag occurs. * * This is the simplest way to set up a [draggable] modifier. When constructing this * [DraggableState], you must provide a [onDelta] lambda, which will be invoked whenever * drag happens (by gesture input or a custom [DraggableState.drag] call) with the delta in * pixels. * * @param onDelta callback invoked when drag occurs. The callback receives the delta in pixels. */ @Composable fun rememberDraggableState(onDelta: (Float) -> Unit): DraggableState { val onDeltaState = rememberUpdatedState(onDelta) return remember { DraggableState { onDeltaState.value.invoke(it) } } } /** * Configure touch dragging for the UI element in a single [Orientation]. The drag distance * reported to [DraggableState], allowing users to react on the drag delta and update their state. * * The common usecase for this component is when you need to be able to drag something * inside the component on the screen and represent this state via one float value * * If you need to control the whole dragging flow, consider using [pointerInput] instead with the * helper functions like [detectDragGestures]. * * If you are implementing scroll/fling behavior, consider using [scrollable]. * * @sample androidx.compose.foundation.samples.DraggableSample * * @param state [DraggableState] state of the draggable. Defines how drag events will be * interpreted by the user land logic. * @param orientation orientation of the drag * @param enabled whether or not drag is enabled * @param interactionSource [MutableInteractionSource] that will be used to emit * [DragInteraction.Start] when this draggable is being dragged. * @param startDragImmediately when set to true, draggable will start dragging immediately and * prevent other gesture detectors from reacting to "down" events (in order to block composed * press-based gestures). This is intended to allow end users to "catch" an animating widget by * pressing on it. It's useful to set it when value you're dragging is settling / animating. * @param onDragStarted callback that will be invoked when drag is about to start at the starting * position, allowing user to suspend and perform preparation for drag, if desired. This suspend * function is invoked with the draggable scope, allowing for async processing, if desired * @param onDragStopped callback that will be invoked when drag is finished, allowing the * user to react on velocity and process it. This suspend function is invoked with the draggable * scope, allowing for async processing, if desired * @param reverseDirection reverse the direction of the scroll, so top to bottom scroll will * behave like bottom to top and left to right will behave like right to left. */ fun Modifier.draggable( state: DraggableState, orientation: Orientation, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, startDragImmediately: Boolean = false, onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit = {}, onDragStopped: suspend CoroutineScope.(velocity: Float) -> Unit = {}, reverseDirection: Boolean = false ): Modifier = draggable( state = state, orientation = orientation, enabled = enabled, interactionSource = interactionSource, startDragImmediately = { startDragImmediately }, onDragStarted = onDragStarted, onDragStopped = { velocity -> onDragStopped(velocity.toFloat(orientation)) }, reverseDirection = reverseDirection, canDrag = { true } ) internal fun Modifier.draggable( state: DraggableState, canDrag: (PointerInputChange) -> Boolean, orientation: Orientation, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, startDragImmediately: () -> Boolean, onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit = {}, onDragStopped: suspend CoroutineScope.(velocity: Velocity) -> Unit = {}, reverseDirection: Boolean = false ): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "draggable" properties["canDrag"] = canDrag properties["orientation"] = orientation properties["enabled"] = enabled properties["reverseDirection"] = reverseDirection properties["interactionSource"] = interactionSource properties["startDragImmediately"] = startDragImmediately properties["onDragStarted"] = onDragStarted properties["onDragStopped"] = onDragStopped properties["state"] = state } ) { val draggedInteraction = remember { mutableStateOf<DragInteraction.Start?>(null) } DisposableEffect(interactionSource) { onDispose { draggedInteraction.value?.let { interaction -> interactionSource?.tryEmit(DragInteraction.Cancel(interaction)) draggedInteraction.value = null } } } val channel = remember { Channel<DragEvent>(capacity = Channel.UNLIMITED) } val startImmediatelyState = rememberUpdatedState(startDragImmediately) val canDragState = rememberUpdatedState(canDrag) val dragLogic by rememberUpdatedState( DragLogic(onDragStarted, onDragStopped, draggedInteraction, interactionSource) ) LaunchedEffect(state) { while (isActive) { var event = channel.receive() if (event !is DragStarted) continue with(dragLogic) { processDragStart(event as DragStarted) } try { state.drag(MutatePriority.UserInput) { while (event !is DragStopped && event !is DragCancelled) { (event as? DragDelta)?.let { dragBy(it.delta.toFloat(orientation)) } event = channel.receive() } } with(dragLogic) { if (event is DragStopped) { processDragStop(event as DragStopped) } else if (event is DragCancelled) { processDragCancel() } } } catch (c: CancellationException) { with(dragLogic) { processDragCancel() } } } } Modifier.pointerInput(orientation, enabled, reverseDirection) { if (!enabled) return@pointerInput coroutineScope { try { awaitPointerEventScope { while (isActive) { val velocityTracker = VelocityTracker() awaitDownAndSlop( canDragState, startImmediatelyState, velocityTracker, orientation )?.let { var isDragSuccessful = false try { isDragSuccessful = awaitDrag( it.first, it.second, velocityTracker, channel, reverseDirection, orientation ) } catch (cancellation: CancellationException) { isDragSuccessful = false if (!isActive) throw cancellation } finally { val event = if (isDragSuccessful) { val velocity = velocityTracker.calculateVelocity() DragStopped(velocity * if (reverseDirection) -1f else 1f) } else { DragCancelled } channel.trySend(event) } } } } } catch (exception: CancellationException) { if (!isActive) { throw exception } } } } } private suspend fun AwaitPointerEventScope.awaitDownAndSlop( canDrag: State<(PointerInputChange) -> Boolean>, startDragImmediately: State<() -> Boolean>, velocityTracker: VelocityTracker, orientation: Orientation ): Pair<PointerInputChange, Offset>? { val initialDown = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) return if (!canDrag.value.invoke(initialDown)) { null } else if (startDragImmediately.value.invoke()) { initialDown.consume() velocityTracker.addPointerInputChange(initialDown) // since we start immediately we don't wait for slop and the initial delta is 0 initialDown to Offset.Zero } else { val down = awaitFirstDown(requireUnconsumed = false) velocityTracker.addPointerInputChange(down) var initialDelta = Offset.Zero val postPointerSlop = { event: PointerInputChange, offset: Offset -> velocityTracker.addPointerInputChange(event) event.consume() initialDelta = offset } val afterSlopResult = awaitPointerSlopOrCancellation( down.id, down.type, pointerDirectionConfig = orientation.toPointerDirectionConfig(), onPointerSlopReached = postPointerSlop ) if (afterSlopResult != null) afterSlopResult to initialDelta else null } } private suspend fun AwaitPointerEventScope.awaitDrag( startEvent: PointerInputChange, initialDelta: Offset, velocityTracker: VelocityTracker, channel: SendChannel<DragEvent>, reverseDirection: Boolean, orientation: Orientation ): Boolean { val overSlopOffset = initialDelta val xSign = sign(startEvent.position.x) val ySign = sign(startEvent.position.y) val adjustedStart = startEvent.position - Offset(overSlopOffset.x * xSign, overSlopOffset.y * ySign) channel.trySend(DragStarted(adjustedStart)) channel.trySend(DragDelta(if (reverseDirection) initialDelta * -1f else initialDelta)) val dragTick: (PointerInputChange) -> Unit = { event -> velocityTracker.addPointerInputChange(event) val delta = event.positionChange() event.consume() channel.trySend(DragDelta(if (reverseDirection) delta * -1f else delta)) } return if (orientation == Orientation.Vertical) { verticalDrag(startEvent.id, dragTick) } else { horizontalDrag(startEvent.id, dragTick) } } private class DragLogic( val onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit, val onDragStopped: suspend CoroutineScope.(velocity: Velocity) -> Unit, val dragStartInteraction: MutableState<DragInteraction.Start?>, val interactionSource: MutableInteractionSource? ) { suspend fun CoroutineScope.processDragStart(event: DragStarted) { dragStartInteraction.value?.let { oldInteraction -> interactionSource?.emit(DragInteraction.Cancel(oldInteraction)) } val interaction = DragInteraction.Start() interactionSource?.emit(interaction) dragStartInteraction.value = interaction onDragStarted.invoke(this, event.startPoint) } suspend fun CoroutineScope.processDragStop(event: DragStopped) { dragStartInteraction.value?.let { interaction -> interactionSource?.emit(DragInteraction.Stop(interaction)) dragStartInteraction.value = null } onDragStopped.invoke(this, event.velocity) } suspend fun CoroutineScope.processDragCancel() { dragStartInteraction.value?.let { interaction -> interactionSource?.emit(DragInteraction.Cancel(interaction)) dragStartInteraction.value = null } onDragStopped.invoke(this, Velocity.Zero) } } private class DefaultDraggableState(val onDelta: (Float) -> Unit) : DraggableState { private val dragScope: DragScope = object : DragScope { override fun dragBy(pixels: Float): Unit = onDelta(pixels) } private val scrollMutex = MutatorMutex() override suspend fun drag( dragPriority: MutatePriority, block: suspend DragScope.() -> Unit ): Unit = coroutineScope { scrollMutex.mutateWith(dragScope, dragPriority, block) } override fun dispatchRawDelta(delta: Float) { return onDelta(delta) } } private sealed class DragEvent { class DragStarted(val startPoint: Offset) : DragEvent() class DragStopped(val velocity: Velocity) : DragEvent() object DragCancelled : DragEvent() class DragDelta(val delta: Offset) : DragEvent() } private fun Offset.toFloat(orientation: Orientation) = if (orientation == Orientation.Vertical) this.y else this.x private fun Velocity.toFloat(orientation: Orientation) = if (orientation == Orientation.Vertical) this.y else this.x
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/Draggable.kt
3029377540
package com.github.willjgriff.ethereumwallet.ethereum.node import org.ethereum.geth.Context import org.ethereum.geth.EthereumClient import org.ethereum.geth.Node /** * Created by Will on 16/03/2017. * * This is a likely candidate for being replaced in the future, eg for Parity or similar. * This should not return objects from the Ethereum library but just domain objects. */ class NodeDetailsAdapter(private val node: Node, private val ethereumClient: EthereumClient, private val context: Context) { fun getNodeInfo(): String = node.getNodeInfoString() fun getNumberOfPeers(): Long = node.peersInfo.size() fun getPeersInfo(): List<String> = node.getPeersInfoStrings() fun getSyncProgressString(): String = ethereumClient.getSyncProgressString(context) }
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ethereum/node/NodeDetailsAdapter.kt
595290978
<selection>fun foo(a : Array<String>, <caret>b : Int) { }</selection>
kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/ValueParameters/2.kt
2635948694
package com.github.willjgriff.ethereumwallet.ethereum.icap import java.util.* enum class IbanParam(paramString: String) { AMOUNT("amount"), LABEL("label"), UKNOWN("unknown"); private object Static { val params: MutableMap<String, IbanParam> = HashMap() } init { Static.params.put(paramString, this) } companion object { fun fromString(paramString: String): IbanParam { return Static.params.get(paramString) ?: UKNOWN } } }
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ethereum/icap/IbanParam.kt
2189884385
package com.intellij.configurationStore import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.StateStorageManager import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import java.io.File import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean class StorageVirtualFileTracker(private val messageBus: MessageBus) { private val filePathToStorage: ConcurrentMap<String, TrackedStorage> = ContainerUtil.newConcurrentMap() private @Volatile var hasDirectoryBasedStorages = false private val vfsListenerAdded = AtomicBoolean() interface TrackedStorage : StateStorage { val storageManager: StateStorageManagerImpl } fun put(path: String, storage: TrackedStorage) { filePathToStorage.put(path, storage) if (storage is DirectoryBasedStorage) { hasDirectoryBasedStorages = true } if (vfsListenerAdded.compareAndSet(false, true)) { addVfsChangesListener() } } fun remove(path: String) { filePathToStorage.remove(path) } fun remove(processor: (TrackedStorage) -> Boolean) { val iterator = filePathToStorage.values.iterator() for (storage in iterator) { if (processor(storage)) { iterator.remove() } } } private fun addVfsChangesListener() { messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener.Adapter() { override fun after(events: MutableList<out VFileEvent>) { eventLoop@ for (event in events) { var storage: StateStorage? if (event is VFilePropertyChangeEvent && VirtualFile.PROP_NAME.equals(event.propertyName)) { val oldPath = event.oldPath storage = filePathToStorage.remove(oldPath) if (storage != null) { filePathToStorage.put(event.path, storage) if (storage is FileBasedStorage) { storage.setFile(null, File(event.path)) } // we don't support DirectoryBasedStorage renaming // StoragePathMacros.MODULE_FILE -> old path, we must update value storage.storageManager.pathRenamed(oldPath, event.path, event) } } else { val path = event.path storage = filePathToStorage[path] // we don't care about parent directory create (because it doesn't affect anything) and move (because it is not supported case), // but we should detect deletion - but again, it is not supported case. So, we don't check if some of registered storages located inside changed directory. // but if we have DirectoryBasedStorage, we check - if file located inside it if (storage == null && hasDirectoryBasedStorages && StringUtilRt.endsWithIgnoreCase(path, FileStorageCoreUtil.DEFAULT_EXT)) { storage = filePathToStorage[VfsUtil.getParentDir(path)] } } if (storage == null) { continue } when (event) { is VFileMoveEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, File(event.path)) } } is VFileCreateEvent -> { if (storage is FileBasedStorage) { storage.setFile(event.file, null) } } is VFileDeleteEvent -> { if (storage is FileBasedStorage) { storage.setFile(null, null) } else { (storage as DirectoryBasedStorage).setVirtualDir(null) } } is VFileCopyEvent -> continue@eventLoop } val componentManager = storage.storageManager.componentManager!! componentManager.messageBus.syncPublisher(StateStorageManager.STORAGE_TOPIC).storageFileChanged(event, storage, componentManager) } } }) } }
platform/configuration-store-impl/src/StorageVirtualFileTracker.kt
1517272692
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* val EXT_occlusion_query_boolean = "EXTOcclusionQueryBoolean".nativeClassGLES("EXT_occlusion_query_boolean", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. This extension defines a mechanism whereby an application can query whether any pixels (or, more precisely, samples) are drawn by a primitive or group of primitives. The primary purpose of such a query (hereafter referred to as an "occlusion query") is to determine the visibility of an object. Typically, the application will render the major occluders in the scene, then perform an occlusion query for each detail object in the scene. On subsequent frames, the previous results of the occlusion queries can be used to decide whether to draw an object or not. """ IntConstant( "Accepted by the {@code target} parameter of BeginQueryEXT, EndQueryEXT, and GetQueryivEXT.", "ANY_SAMPLES_PASSED_EXT"..0x8C2F, "ANY_SAMPLES_PASSED_CONSERVATIVE_EXT"..0x8D6A ) IntConstant( "Accepted by the {@code pname} parameter of GetQueryivEXT.", "CURRENT_QUERY_EXT"..0x8865 ) IntConstant( "Accepted by the {@code pname} parameter of GetQueryObjectivEXT and GetQueryObjectuivEXT.", "QUERY_RESULT_EXT"..0x8866, "QUERY_RESULT_AVAILABLE_EXT"..0x8867 ) void( "GenQueriesEXT", "", AutoSize("ids")..GLsizei.IN("n", ""), ReturnParam..GLuint_p.OUT("ids", "") ) void( "DeleteQueriesEXT", "", AutoSize("ids")..GLsizei.IN("n", ""), SingleValue("id")..const..GLuint_p.IN("ids", "") ) GLboolean( "IsQueryEXT", "", GLuint.IN("id", "") ) void( "BeginQueryEXT", "", GLenum.IN("target", ""), GLuint.IN("id", "") ) void( "EndQueryEXT", "", GLenum.IN("target", "") ) void( "GetQueryivEXT", "", GLenum.IN("target", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLint_p.OUT("params", "") ) void( "GetQueryObjectuivEXT", "", GLuint.IN("id", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLuint_p.OUT("params", "") ) }
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/EXT_occlusion_query_boolean.kt
608655906
package org.jetbrains.kotlin.ui.editors.selection.handlers import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import com.intellij.psi.PsiElement import com.intellij.openapi.util.TextRange public class KotlinDocSectionSelectionHandler: KotlinElementSelectionHandler { override fun canSelect(enclosingElement: PsiElement) = enclosingElement is KDocSection override fun selectEnclosing(enclosingElement: PsiElement, selectedRange: TextRange) = KotlinElementSelectioner.selectEnclosing(enclosingElement.getParent(), selectedRange) override fun selectNext(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange) = selectEnclosing(enclosingElement, selectedRange) override fun selectPrevious(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange) = selectEnclosing(enclosingElement, selectedRange) }
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/selection/handlers/KotlinDocSectionSelectionHandler.kt
2200873867
package me.echeung.moemoekyun.client.stream.player import android.content.Context import android.media.AudioManager import android.net.Uri import com.google.android.exoplayer2.C import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import me.echeung.moemoekyun.client.RadioClient import me.echeung.moemoekyun.util.PreferenceUtil import me.echeung.moemoekyun.util.ext.isCarUiMode import me.echeung.moemoekyun.util.system.AudioManagerUtil import me.echeung.moemoekyun.util.system.NetworkUtil import org.koin.core.KoinComponent import org.koin.core.inject class LocalStreamPlayer(private val context: Context) : StreamPlayer<SimpleExoPlayer>(), KoinComponent { private val preferenceUtil: PreferenceUtil by inject() private var audioManagerUtil: AudioManagerUtil private var audioFocusChangeListener: AudioManager.OnAudioFocusChangeListener private var wasPlayingBeforeLoss: Boolean = false private val focusLock = Any() init { audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange -> when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { unduck() if (wasPlayingBeforeLoss) { play() } } AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { wasPlayingBeforeLoss = isPlaying if (wasPlayingBeforeLoss && (preferenceUtil.shouldPauseAudioOnLoss() || context.isCarUiMode())) { pause() } } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { wasPlayingBeforeLoss = isPlaying if (preferenceUtil.shouldDuckAudio()) { duck() } } } } audioManagerUtil = AudioManagerUtil(context, audioFocusChangeListener) } override fun initPlayer() { if (player == null) { player = SimpleExoPlayer.Builder(context).build() player!!.setWakeMode(C.WAKE_MODE_NETWORK) player!!.addListener(eventListener) player!!.volume = 1f val audioAttributes = AudioAttributes.Builder() .setContentType(C.CONTENT_TYPE_MUSIC) .setUsage(C.USAGE_MEDIA) .build() player!!.audioAttributes = audioAttributes } // Set stream val streamUrl = RadioClient.library.streamUrl if (streamUrl != currentStreamUrl) { val dataSourceFactory = DefaultDataSourceFactory(context, NetworkUtil.userAgent) val streamSource = ProgressiveMediaSource.Factory(dataSourceFactory, DefaultExtractorsFactory()) .createMediaSource(Uri.parse(streamUrl)) player!!.prepare(streamSource) currentStreamUrl = streamUrl } } override fun play() { // Request audio focus for playback val result = audioManagerUtil.requestAudioFocus() synchronized(focusLock) { if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { super.play() } } } override fun stop() { audioManagerUtil.abandonAudioFocus() super.stop() } private fun duck() { player?.audioComponent?.volume = 0.5f } private fun unduck() { player?.audioComponent?.volume = 1f } }
app/src/main/java/me/echeung/moemoekyun/client/stream/player/LocalStreamPlayer.kt
3879598033
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.db.persistence import org.apache.ibatis.annotations.Param import java.io.Serializable /** * @param <K> * @param <T> * @author MyCollab Ltd. * @since 1.0 </T></K> */ interface ICrudGenericDAO<K : Serializable, T> { /** * @param record */ fun insert(record: T) /** * @param record * @return */ fun updateByPrimaryKey(record: T): Int /** * @param record * @return */ fun updateByPrimaryKeySelective(record: T): Int /** * @param record * @param primaryKeys */ fun massUpdateWithSession(@Param("record") record: T, @Param("primaryKeys") primaryKeys: List<K>) /** * @param primaryKey * @return */ fun selectByPrimaryKey(primaryKey: K): T? /** * @param primaryKey * @return */ fun deleteByPrimaryKey(primaryKey: K): Int /** * @param value * @return */ fun insertAndReturnKey(value: T): Int /** * @param keys */ fun removeKeysWithSession(keys: List<*>) }
mycollab-dao/src/main/java/com/mycollab/db/persistence/ICrudGenericDAO.kt
3806928760
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package coffee internal interface Pump { fun pump() }
examples/dagger/src/coffee/Pump.kt
3464627674
package de.pbauerochse.worklogviewer.timereport import java.time.LocalDate /** * Groups an [Issue] with its [WorkItem]s */ class IssueWithWorkItems( val issue: Issue, val workItems: List<WorkItem> ): Comparable<IssueWithWorkItems> { /** * Returns `true` if any of the [WorkItem]s * were created by the current user. */ val hasWorkItemsBelongingToCurrentUser: Boolean get() = workItems.any { it.belongsToCurrentUser } /** * Returns all [WorkItem]s that are for the given LocalDate */ fun getWorkItemsForDate(date: LocalDate): List<WorkItem> { return workItems.filter { it.workDateAtLocalZone.toLocalDate() == date } } /** * Returns the total time in minutes spent on this [Issue], * by summing up the `durationInMinutes` of each [WorkItem] */ val totalTimeInMinutes: Long get() = workItems.sumOf { it.durationInMinutes } override fun compareTo(other: IssueWithWorkItems): Int = issue.compareTo(other.issue) }
common-api/src/main/java/de/pbauerochse/worklogviewer/timereport/IssueWithWorkItems.kt
632610452
package org.jetbrains.haskell.debugger.protocol import java.util.Deque import org.jetbrains.haskell.debugger.parser.ParseResult import org.json.simple.JSONObject import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent /** * @author Habibullin Marat */ public class RemoveBreakpointCommand(val module: String?, val breakpointNumber: Int, callback: CommandCallback<Nothing?>?) : RealTimeCommand<Nothing?>(callback) { override fun getText(): String = ":delete ${module ?: ""} $breakpointNumber\n" override fun parseGHCiOutput(output: Deque<String?>): Nothing? = null override fun parseJSONOutput(output: JSONObject): Nothing? = null public class StandardRemoveBreakpointCallback(val respondent: DebugRespondent) : CommandCallback<Nothing?>() { override fun execAfterParsing(result: Nothing?) { respondent.breakpointRemoved() } } }
plugin/src/org/jetbrains/haskell/debugger/protocol/RemoveBreakpointCommand.kt
1236187821
package com.intfocus.template.model.response.mine_page import com.google.gson.annotations.SerializedName import com.intfocus.template.model.response.BaseResult /** * @author liuruilin * @data 2017/12/6 * @describe */ class FeedbackContent: BaseResult() { /** * code : 200 * message : 获取数据列表成功 * current_page : 0 * page_size : 15 * total_page : 15 * data : [{"id":210,"title":"生意人问题反馈","content":"测试","images":["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"],"replies":[{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}],"user_num":"13564379606","app_version":"0.0.2","platform":"ios","platform_version":"iphoneos","progress_state":0,"progress_content":null,"publicly":false,"created_at":"2017-08-15 10:55:49"}] */ var current_page: Int = 0 var page_size: Int = 0 var total_page: Int = 0 @SerializedName("data") var data: Data? = null class Data { /** * id : 210 * title : 生意人问题反馈 * content : 测试 * images : ["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"] * replies : [{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}] * user_num : 13564379606 * app_version : 0.0.2 * platform : ios * platform_version : iphoneos * progress_state : 0 * progress_content : null * publicly : false * created_at : 2017-08-15 10:55:49 */ var id: Int = 0 var title: String? = null var content: String? = null var user_num: String? = null var app_version: String? = null var platform: String? = null var platform_version: String? = null var progress_state: Int = 0 var progress_content: Any? = null var publicly: Boolean = false var created_at: String? = null var images: List<String>? = null var replies: List<Replies>? = null class Replies { /** * id : 1 * content : 测试 * images : ["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"] * created_at : 2017-11-17 17:30:30 */ var id: Int = 0 var content: String? = null var created_at: String? = null var images: List<String>? = null } } }
app/src/main/java/com/intfocus/template/model/response/mine_page/FeedbackContent.kt
3174572095
package com.intfocus.template.subject.one import android.util.Log import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSONReader import com.intfocus.template.SYPApplication.globalContext import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.entity.Report import com.intfocus.template.model.entity.ReportModule import com.intfocus.template.model.gen.ReportDao import com.intfocus.template.subject.model.ReportModelImpl import com.intfocus.template.subject.one.entity.Filter import com.intfocus.template.util.* import com.intfocus.template.util.ApiHelper.clearResponseHeader import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.io.File import java.io.StringReader /** * **************************************************** * @author jameswong * created on: 17/10/25 下午5:11 * e-mail: [email protected] * name: * desc: 模板一 Model 层 * **************************************************** */ class ModeImpl : ReportModelImpl() { private val sqlDistinctPageTitle = "SELECT DISTINCT " + ReportDao.Properties.Page_title.columnName + " FROM " + ReportDao.TABLENAME private var pageTitleList: MutableList<String> = arrayListOf() private var reportDao: ReportDao = DaoUtil.getReportDao() lateinit private var filterObject: Filter private var urlString: String = "" private var jsonFileName: String = "" private var groupId: String = "" private var templateId: String = "" private var reportId: String = "" private var count = 0 companion object { private val TAG = "ModeImpl" private var INSTANCE: ModeImpl? = null private var observable: Subscription? = null private var uuid: String = "" /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): ModeImpl { return INSTANCE ?: ModeImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { unSubscribe() observable?.let { Log.d(TAG, "取消订阅 ::: " + it.isUnsubscribed) } INSTANCE = null } /** * 取消订阅 */ private fun unSubscribe() { observable?.unsubscribe() ?: return } } fun getData(reportId: String, templateId: String, groupId: String, callback: ModeModel.LoadDataCallback) { this.reportId = reportId this.templateId = templateId this.groupId = groupId uuid = reportId + templateId + groupId jsonFileName = String.format("group_%s_template_%s_report_%s.json", groupId, templateId, reportId) urlString = String.format(K.API_REPORT_JSON_ZIP, TempHost.getHost(), groupId, templateId, reportId) LogUtil.d(this@ModeImpl, "报表 url ::: " + urlString) checkReportData(callback) } private fun checkReportData(callback: ModeModel.LoadDataCallback) { observable = Observable.just(uuid) .subscribeOn(Schedulers.io()) .map { when { check(urlString) -> { LogUtil.d(this@ModeImpl, "网络数据") analysisData() } available(uuid) -> { LogUtil.d(this@ModeImpl, "本地数据") queryFilter(uuid) generatePageList() } else -> { LogUtil.d(this@ModeImpl, "报表数据有缓存,数据库无数据") analysisData() } } } .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : Subscriber<List<String>>() { override fun onCompleted() { } override fun onNext(t: List<String>?) { t?.let { callback.onDataLoaded(it, filterObject) } } override fun onError(e: Throwable?) { delete(uuid) clearResponseHeader(urlString) callback.onDataNotAvailable(e!!) } }) } private fun analysisData(): List<String> { LogUtil.d(TAG, "ModeImpl 报表数据开始转为对象") delete(uuid) val response: String? val jsonFilePath = FileUtil.dirPath(globalContext, K.K_CACHED_DIR_NAME, jsonFileName) val dataState = ApiHelper.reportJsonData(globalContext, groupId, templateId, reportId) if (dataState || File(jsonFilePath).exists()) { response = FileUtil.readFile(jsonFilePath) } else { throw Throwable("获取数据失败") } // response = LoadAssetsJsonUtil.getAssetsJsonData("group_165_template_1_report_31.json") val stringReader = StringReader(response) val reader = JSONReader(stringReader) reader.startObject() var report: Report val reportDataList = mutableListOf<Report>() while (reader.hasNext()) { val configKey = reader.readString() when (configKey) { "filter" -> { filterObject = JSON.parseObject(reader.readObject().toString(), Filter::class.java) report = Report() report.id = null report.uuid = uuid report.name = filterObject.display report.index = 0 report.type = "filter" report.page_title = "filter" report.config = JSON.toJSONString(filterObject) reportDataList.add(report) // reportDao.insert(report) } "parts" -> { reader.startArray() var i = 0 while (reader.hasNext()) { val partsItem = JSON.parseObject(reader.readObject().toString(), ReportModule::class.java) report = Report() report.id = null report.uuid = uuid report.name = partsItem.name ?: "name" report.page_title = partsItem.page_title ?: "page_title" report.index = partsItem.control_index ?: i report.type = partsItem.type ?: "unknown_type" report.config = partsItem.config ?: "null_config" // reportDao.insert(report) reportDataList.add(report) i++ } reader.endArray() } } } reader.endObject() reportDao.insertInTx(reportDataList) LogUtil.d(TAG, "ModeImpl 报表数据解析完成") return generatePageList() } /** * 查询筛选条件 * @uuid 报表唯一标识 * @return 筛选实体类 */ private fun queryFilter(uuid: String) { val reportDao = DaoUtil.getReportDao() val filter = reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Type.eq("filter"))).unique() filterObject = JSON.parseObject(filter.config, Filter::class.java) } /** * 查询单个页面的所有报表组件 * @pageId 页面id * @return pageId 对应页面的所有报表组件 */ fun queryPageData(uuid: String, pageId: Int): List<Report> { val reportDao = DaoUtil.getReportDao() return if (null == filterObject.data) { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]))) .list() } else { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Name.eq(filterObject!!.display))) .list() } } /** * 查询单个组件的 Config * @index 组件 index 标识 * @pageId 组件所在页面的 id * @return 组件 config */ fun queryModuleConfig(index: Int, pageId: Int): String { val reportDao = DaoUtil.getReportDao() return if (null == filterObject.data) { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Index.eq(index))) .unique().config } else { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Name.eq(filterObject.display), ReportDao.Properties.Index.eq(index))) .unique().config } } /** * 更新筛选条件 * @display 当前已选的筛选项 * @callback 数据加载回调 */ fun updateFilter(display: String, callback: ModeModel.LoadDataCallback) { filterObject.display = display val reportDao = DaoUtil.getReportDao() val filter = reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Type.eq("filter"))).unique() filter?.name = display filter?.config = JSON.toJSONString(filterObject) filter?.let { reportDao.update(it) checkReportData(callback) } } /** * 根页签去重 * @reports 当前报表所有数据 * @return 去重后的根页签 */ private fun generatePageList(): List<String> { pageTitleList.clear() var distinctPageTitle = sqlDistinctPageTitle if (null != filterObject.data) { distinctPageTitle = sqlDistinctPageTitle + " WHERE " + ReportDao.Properties.Name.columnName + " = \'" + filterObject.display + "\' AND " + ReportDao.Properties.Uuid.columnName + " = \'" + uuid + "\'" } val cursor = DaoUtil.getDaoSession()!!.database.rawQuery(distinctPageTitle, null) cursor.use { if (it.moveToFirst()) { do { val pageTitle = it.getString(0) if (pageTitle != null && "" != pageTitle && "filter" != pageTitle) { pageTitleList.add(pageTitle) } } while (it.moveToNext()) } } if (pageTitleList.size == 0) { pageTitleList.add("") } return pageTitleList } }
app/src/main/java/com/intfocus/template/subject/one/ModeImpl.kt
453260861
package com.github.sybila.ode.generator.zero import com.github.sybila.checker.Transition import com.github.sybila.checker.decreaseProp import com.github.sybila.checker.increaseProp import com.github.sybila.huctl.DirectionFormula import com.github.sybila.ode.generator.ExplicitEvaluable import com.github.sybila.ode.generator.bool.BoolOdeModel import com.github.sybila.ode.model.OdeModel import com.github.sybila.ode.model.Summand import org.junit.Test import kotlin.test.assertEquals /** * This test suit should provide a really basic way to test how * s.s.g behaves in trivial cases of one dimensional models. * * All test cases rely on a one dimensional model with three states and predefined result. **/ class OneDimNoParamGeneratorTest { private val variable = OdeModel.Variable( name = "v1", range = Pair(0.0, 3.0), varPoints = null, thresholds = listOf(0.0, 1.0, 2.0, 3.0), summands = Summand(evaluables = ExplicitEvaluable( 0, mapOf(0.0 to 0.0, 1.0 to 0.0, 2.0 to 0.0, 3.0 to 0.0) )) ) private fun createFragment(vararg values: Double): BoolOdeModel { return BoolOdeModel(OdeModel(variable.copy(equation = listOf(Summand( evaluables = ExplicitEvaluable(0, listOf(0.0, 1.0, 2.0, 3.0).zip(values.toList()).toMap() ) ))))) } private infix fun Int.s(s: Int) = Transition(s, if (this == s) DirectionFormula.Atom.Loop else if (this > s) "v1".decreaseProp() else "v1".increaseProp() , true) private infix fun Int.p(s: Int) = Transition(s, if (this == s) DirectionFormula.Atom.Loop else if (this < s) "v1".decreaseProp() else "v1".increaseProp() , true) private fun BoolOdeModel.checkSuccessors(from: Int, to: List<Int>) { this.run { val s = from.successors(true).asSequence().toSet() assertEquals(to.map { from s it }.toSet(), s) } } private fun BoolOdeModel.checkPredecessors(from: Int, to: List<Int>) { this.run { val s = from.predecessors(true).asSequence().toSet() assertEquals(to.map { from p it }.toSet(), s) } } //ignore symmetric cases, otherwise try as many combinations as possible //No +/- //0..0..0..0 @Test fun case0() { createFragment(0.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //One + //+..0..0..0 @Test fun case1() { createFragment(1.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..+..0..0 @Test fun case2() { createFragment(0.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //One - //-..0..0..0 @Test fun case3() { createFragment(-1.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..-..0..0 @Test fun case4() { createFragment(0.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //Two + //+..+..0..0 @Test fun case5() { createFragment(1.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //+..0..+..0 @Test fun case6() { createFragment(1.0, 0.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //+..0..0..+ @Test fun case7() { createFragment(1.0, 0.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..+..+..0 @Test fun case8() { createFragment(0.0, 1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //Two - //-..-..0..0 @Test fun case9() { createFragment(-1.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //-..0..-..0 @Test fun case10() { createFragment(-1.0, 0.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf(2)) } } //-..0..0..- @Test fun case11() { createFragment(-1.0, 0.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..-..-..0 @Test fun case12() { createFragment(0.0, -1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf(2)) } } //Three + //0..+..+..+ @Test fun case13() { createFragment(0.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //+..0..+..+ @Test fun case14() { createFragment(1.0, 0.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three - //0..-..-..- @Test fun case15() { createFragment(0.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //-..0..-..- @Test fun case16() { createFragment(-1.0, 0.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf()) } } //Four + //+..+..+..+ @Test fun case17() { createFragment(1.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //Four - //-..-..-..- @Test fun case18() { createFragment(-1.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //One + / One - //+..-..0..0 @Test fun case19() { createFragment(1.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..0..-..0 @Test fun case20() { createFragment(1.0, 0.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf(2)) } } //+..0..0..- @Test fun case21() { createFragment(1.0, 0.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //-..+..0..0 @Test fun case22() { createFragment(-1.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..0..+..0 @Test fun case23() { createFragment(-1.0, 0.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //0..+..-..0 @Test fun case24() { createFragment(0.0, 1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf(2)) } } //0..-..+..0 @Test fun case25() { createFragment(0.0, -1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //One + / Two - //+..0..-..- @Test fun case26() { createFragment(1.0, 0.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf()) } } //+..-..0..- @Test fun case27() { createFragment(1.0, -1.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..-..-..0 @Test fun case28() { createFragment(1.0, -1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf(2)) } } //0..+..-..- @Test fun case29() { createFragment(0.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } //-..+..0..- @Test fun case30() { createFragment(-1.0, 1.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..+..-..0 @Test fun case31() { createFragment(-1.0, 1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf(2)) } } //Two + / One - //-..0..+..+ @Test fun case32() { createFragment(-1.0, 0.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //-..+..0..+ @Test fun case33() { createFragment(-1.0, 1.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..+..+..0 @Test fun case34() { createFragment(-1.0, 1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //0..-..+..+ @Test fun case35() { createFragment(0.0, -1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //+..-..0..+ @Test fun case36() { createFragment(1.0, -1.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..-..+..0 @Test fun case37() { createFragment(1.0, -1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Two + / Two - //+..+..-..- @Test fun case38() { createFragment(1.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } //+..-..+..- @Test fun case39() { createFragment(1.0, -1.0, 1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three + / One - //-..+..+..+ @Test fun case40() { createFragment(-1.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //+..-..+..+ @Test fun case41() { createFragment(1.0, -1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three - / One + //+..-..-..- @Test fun case42() { createFragment(1.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //-..+..-..- @Test fun case43() { createFragment(-1.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } }
src/test/kotlin/com/github/sybila/ode/generator/zero/OneDimNoParamGeneratorTest.kt
4062528148
package pl.shockah.godwit.node import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.SpriteBatch.* import com.badlogic.gdx.graphics.g2d.TextureRegion import pl.shockah.godwit.GDelegates import pl.shockah.godwit.color.GAlphaColor import pl.shockah.godwit.color.RGBColor import pl.shockah.godwit.geom.MutableVec2 import pl.shockah.godwit.geom.ObservableVec2 import pl.shockah.godwit.geom.Rectangle open class SpriteNode( val region: TextureRegion ) : Node() { constructor(texture: Texture) : this(TextureRegion(texture)) companion object { const val VERTEX_SIZE = 2 + 1 + 2 const val SPRITE_SIZE = 4 * VERTEX_SIZE } val texture: Texture get() = region.texture protected val observableSize = ObservableVec2 { setupPoints() } var size: MutableVec2 by observableSize.asMutableProperty() var color: GAlphaColor by GDelegates.observable(RGBColor.white.alpha()) { -> setupColor() } var usesRectangleTouchShape: Boolean by GDelegates.observable(true) { -> setupRectangleTouchShape() } private val vertices = FloatArray(SPRITE_SIZE) init { size.x = region.regionWidth.toFloat() size.y = region.regionHeight.toFloat() origin.x = size.x * 0.5f origin.y = size.y * 0.5f setupPoints() setupUV() setupColor() } private fun setupUV() { vertices[U1] = region.u vertices[V1] = region.v2 vertices[U2] = region.u vertices[V2] = region.v vertices[U3] = region.u2 vertices[V3] = region.v vertices[U4] = region.u2 vertices[V4] = region.v2 } private fun setupRectangleTouchShape() { if (usesRectangleTouchShape) touchShape = Rectangle(position - origin, size) } private fun setupPoints() { vertices[X1] = 0f vertices[Y1] = 0f vertices[X2] = 0f vertices[Y2] = size.y vertices[X3] = size.x vertices[Y3] = size.y vertices[X4] = size.x vertices[Y4] = 0f setupRectangleTouchShape() } private fun setupColor() { val colorBits = color.gdx.toFloatBits() vertices[C1] = colorBits vertices[C2] = colorBits vertices[C3] = colorBits vertices[C4] = colorBits } override fun drawSelf(renderers: NodeRenderers) { renderers.sprites { draw(texture, vertices, 0, SPRITE_SIZE) } } }
core/src/pl/shockah/godwit/node/SpriteNode.kt
1543267078
package com.themovielist.ui import android.content.Context import android.support.v7.widget.LinearLayoutManager class NonScrollableLLM(context: Context, orientation: Int, reverseLayout: Boolean) : LinearLayoutManager(context, orientation, reverseLayout) { // it will always pass false to RecyclerView when calling "canScrollVertically()" method. override fun canScrollVertically(): Boolean { return false } }
app/src/main/java/com/themovielist/ui/NonScrollableLLM.kt
2251332789
/* * Copyright (C) 2020-2022 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.saxon.lang import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginContextItemFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginLambdaFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginParamRef import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginTypeAlias import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.* import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathBundle import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxErrorReporter import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresAny import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresProductVersion import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryItemTypeDecl import xqt.platform.intellij.saxon.SaxonXPathTokenProvider import xqt.platform.intellij.xpath.XPathTokenProvider object SaxonSyntaxValidator : XpmSyntaxValidator { override fun validate( element: XpmSyntaxValidationElement, reporter: XpmSyntaxErrorReporter ): Unit = when (element) { is PluginContextItemFunctionExpr -> when (element.conformanceElement.elementType) { XPathTokenProvider.ContextItem, SaxonXPathTokenProvider.ContextFunctionOpen -> reporter.requires(element, SAXON_PE_10) else -> reporter.requires(element, SAXON_PE_9_9_ONLY) } is PluginLambdaFunctionExpr -> reporter.requires(element, SAXON_PE_10) is XPathOtherwiseExpr -> reporter.requires(element, SAXON_PE_10) is PluginParamRef -> reporter.requires(element, SAXON_PE_10) is XPathAnyMapTest -> reporter.requires(element, SAXON_PE_9_4) is XPathSimpleForClause -> when (element.conformanceElement.elementType) { XPathTokenProvider.KMember -> reporter.requires(element, SAXON_PE_10) else -> { } } is XPathFieldDeclaration -> { val recordTest = (element as PsiElement).parent as XpmSyntaxValidationElement when (recordTest.conformanceElement.elementType) { XPathTokenProvider.KRecord -> { } else -> when (element.conformanceElement.elementType) { XPathTokenProvider.QuestionMark, XPathTokenType.ELVIS -> reporter.requires(element, SAXON_PE_9_9) XPathTokenProvider.KAs -> reporter.requires(element, SAXON_PE_10) else -> { } } } } is XPathRecordTest -> when (element.conformanceElement.elementType) { XPathTokenProvider.KRecord -> { } else -> when (element.isExtensible) { true -> reporter.requires(element, SAXON_PE_9_9) else -> reporter.requires(element, SAXON_PE_9_8) } } is PluginTypeAlias -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.TypeAlias -> reporter.requires(element, SAXON_PE_9_8_TO_9_9) // ~T else -> reporter.requires(element, SAXON_PE_10) // type(T) } is XQueryItemTypeDecl -> when (element.conformanceElement.elementType) { XPathTokenProvider.KType -> reporter.requires(element, SAXON_PE_9_8) else -> { } } is XPathLocalUnionType -> reporter.requires(element, SAXON_PE_9_8) is XPathAndExpr -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.KAndAlso -> reporter.requires(element, SAXON_PE_9_9) else -> { } } is XPathAttributeTest -> when (element.conformanceElement) { is XPathWildcard -> { val name = XPathBundle.message("construct.wildcard-attribute-test") reporter.requires(element, SAXON_PE_10, name) } else -> { } } is XPathElementTest -> when (element.conformanceElement) { is XPathWildcard -> { val name = XPathBundle.message("construct.wildcard-element-test") reporter.requires(element, SAXON_PE_10, name) } else -> { } } is XPathOrExpr -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.KOrElse -> reporter.requires(element, SAXON_PE_9_9) else -> { } } else -> { } } private val SAXON_PE_9_4 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_4), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_4) ) private val SAXON_PE_9_8 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_8), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_8) ) private val SAXON_PE_9_8_TO_9_9 = XpmRequiresAny( XpmRequiresProductVersion.between(SaxonPE.VERSION_9_8, SaxonPE.VERSION_9_9), XpmRequiresProductVersion.between(SaxonEE.VERSION_9_8, SaxonEE.VERSION_9_9) ) private val SAXON_PE_9_9 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_9), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_9) ) private val SAXON_PE_9_9_ONLY = XpmRequiresAny( XpmRequiresProductVersion.between(SaxonPE.VERSION_9_9, SaxonPE.VERSION_9_9), XpmRequiresProductVersion.between(SaxonEE.VERSION_9_9, SaxonEE.VERSION_9_9) ) private val SAXON_PE_10 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_10_0), XpmRequiresProductVersion.since(SaxonEE.VERSION_10_0) ) }
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/lang/SaxonSyntaxValidator.kt
729827335
/* * Copyright (C) 2016, 2018-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xqdoc.resources import com.intellij.AbstractBundle import org.jetbrains.annotations.PropertyKey object XQDocBundle : AbstractBundle("messages.XQDocBundle") { fun message(@PropertyKey(resourceBundle = "messages.XQDocBundle") key: String, vararg params: Any): String { return getMessage(key, *params) } }
src/lang-xqdoc/main/uk/co/reecedunn/intellij/plugin/xqdoc/resources/XQDocBundle.kt
2462124041
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 examples.kotlin.mybatis3.canonical import org.mybatis.dynamic.sql.util.mybatis3.CommonInsertMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonSelectMapper interface AddressMapper: CommonInsertMapper<AddressRecord>, CommonSelectMapper
src/test/kotlin/examples/kotlin/mybatis3/canonical/AddressMapper.kt
1347509171
/* * Copyright (C) 2016-2018 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.ast.plugin import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathKindTest /** * A MarkLogic 8.0 `NumberNodeTest` node in the XQuery AST. * * Because the child nodes of an `NumberNodeTest` are only referenced * from the `NumberNodeTest` node in the grammar, the * `NumberNodeTest` nodes are stored as instances of the child nodes * instead of as distinct nodes themselves. */ interface PluginNumberNodeTest : XPathKindTest
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/plugin/PluginNumberNodeTest.kt
1907033477
package lt.markmerkk.app.network.events.models /** * Event when sending registered players on the server */ class PlayerRegister( var connectionId: Int = -1, var name: String = "" )
core/src/main/java/lt/markmerkk/app/network/events/models/PlayerRegister.kt
3142395644
/* * Copyright 2010-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 kotlin // (0..22).joinToString("\n") { i -> "interface SuspendFunction$i<${(1..i).joinToString("") { j -> "in P$j, " }}out R> : SuspendFunction<R> {\n operator suspend fun invoke(${(1..i).joinToString { j -> "p$j: P$j" }}): R\n}\n" } interface SuspendFunction0<out R> : SuspendFunction<R> { operator suspend fun invoke(): R } interface SuspendFunction1<in P1, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1): R } interface SuspendFunction2<in P1, in P2, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2): R } interface SuspendFunction3<in P1, in P2, in P3, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3): R } interface SuspendFunction4<in P1, in P2, in P3, in P4, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4): R } interface SuspendFunction5<in P1, in P2, in P3, in P4, in P5, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R } interface SuspendFunction6<in P1, in P2, in P3, in P4, in P5, in P6, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R } interface SuspendFunction7<in P1, in P2, in P3, in P4, in P5, in P6, in P7, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R } interface SuspendFunction8<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R } interface SuspendFunction9<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R } interface SuspendFunction10<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R } interface SuspendFunction11<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11): R } interface SuspendFunction12<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12): R } interface SuspendFunction13<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13): R } interface SuspendFunction14<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14): R } interface SuspendFunction15<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15): R } interface SuspendFunction16<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16): R } interface SuspendFunction17<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17): R } interface SuspendFunction18<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18): R } interface SuspendFunction19<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19): R } interface SuspendFunction20<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, in P20, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19, p20: P20): R } interface SuspendFunction21<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, in P20, in P21, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19, p20: P20, p21: P21): R } interface SuspendFunction22<in P1, in P2, in P3, in P4, in P5, in P6, in P7, in P8, in P9, in P10, in P11, in P12, in P13, in P14, in P15, in P16, in P17, in P18, in P19, in P20, in P21, in P22, out R> : SuspendFunction<R> { operator suspend fun invoke(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10, p11: P11, p12: P12, p13: P13, p14: P14, p15: P15, p16: P16, p17: P17, p18: P18, p19: P19, p20: P20, p21: P21, p22: P22): R }
runtime/src/main/kotlin/kotlin/SuspendFunctions.kt
3936820944
package isotop.se.isotop15.contests import android.content.Context import android.support.v4.app.Fragment import android.util.Log import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import isotop.se.isotop15.App import isotop.se.isotop15.models.Contestant import isotop.se.isotop15.models.Game import isotop.se.isotop15.models.HighScore import isotop.se.isotop15.models.Participation import java.util.* /** * @author Ann-Sofi Åhn * * Created on 17/02/13. */ abstract class ContestFragment(val app: App) : Fragment() { protected lateinit var callback: ContestCallbacks protected val contestants = ArrayList<Contestant>() override fun onAttach(context: Context?) { super.onAttach(context) if (context is ContestCallbacks) { callback = context } else { throw IllegalStateException("Attaching activity must implement ContestCallbacks") } } fun setContestants(contestants: ArrayList<Contestant>) { this.contestants.clear() this.contestants.addAll(contestants) Log.d("ContestFragment", "Number of contestants: ${this.contestants.size}") contestantsUpdated() } fun postScoreForContestant(contestant: Contestant, points: Int, lapTime: String? = null) { val score = HighScore(points = points, activityId = getActivityId(), contestantId = contestant.id, lapTime = lapTime) val tagId = contestant.slug!! app.gameBackend.postContestantScore(tagId, score) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ Log.d(TAG, "Uploaded score, got this back: $it") callback.onContestFinished() }, { // TODO: Skicka upp en snackbar? Log.w(TAG, "Couldn't post score", it) }) } fun postParticipationForContestant(contestant: Contestant) { val participation = Participation(activityId = getActivityId(), contestantId = contestant.id) app.gameBackend.postContestantParticipation(contestant.slug!!, participation) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ Log.d(TAG, "Uploaded participation, got this back: $it") }, { Log.w(TAG, "Couldn't post participation", it) }) } abstract protected fun contestantsUpdated() abstract protected fun getActivityId(): Int companion object { val TAG = "ContestFragment" fun newInstance(app: App, game: Game): ContestFragment { val fragment = when (game) { Game.DRONE_RACE -> DroneRaceFragment(app) Game.SLOT_CARS -> SlotCarsFragment(app) Game.ROBOT_WARS -> RobotWarsFragment(app) Game.VR -> VrFragment(app) Game.OTHER -> OtherContestsFragment(app) Game.NONE -> TODO() } return fragment } } }
contest/app/src/main/kotlin/isotop/se/isotop15/contests/ContestFragment.kt
799001225
package com.vmenon.mpo.core.work import android.content.Context import com.vmenon.mpo.core.usecases.Interactors import javax.inject.Inject class UpdateAllShowsWorker( context: Context, workerParams: androidx.work.WorkerParameters ) : BaseWorker(context, workerParams) { @Inject lateinit var interactors: Interactors override suspend fun doMyWork(): Result { appComponent.inject(this) interactors.updateAllShows() return Result.success() } }
app/src/main/java/com/vmenon/mpo/core/work/UpdateAllShowsWorker.kt
764336945
package eu.kanade.tachiyomi.ui.reader.loader import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.EpubFile import rx.Observable import java.io.File /** * Loader used to load a chapter from a .epub file. */ class EpubPageLoader(file: File) : PageLoader() { /** * The epub file. */ private val epub = EpubFile(file) /** * Recycles this loader and the open zip. */ override fun recycle() { super.recycle() epub.close() } /** * Returns an observable containing the pages found on this zip archive ordered with a natural * comparator. */ override fun getPages(): Observable<List<ReaderPage>> { return epub.getImagesFromPages() .mapIndexed { i, path -> val streamFn = { epub.getInputStream(epub.getEntry(path)!!) } ReaderPage(i).apply { stream = streamFn status = Page.READY } } .let { Observable.just(it) } } /** * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable<Int> { return Observable.just(if (isRecycled) { Page.ERROR } else { Page.READY }) } }
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/EpubPageLoader.kt
973645321
/* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nomic.core import org.assertj.core.api.Assertions.assertThat import org.junit.Test /** * @author [email protected] */ class TopologySortTest { @Test fun `test of simple topology sort`() { val graph = listOf<Node<String>>( Node("A"), Node("B", mutableListOf("A")), Node("C", mutableListOf("A")), Node("E", mutableListOf("D")), Node("D", mutableListOf("B", "C")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[A, B, C, D, E]") } /** * test of graph: https://en.wikipedia.org/wiki/File:Directed_acyclic_graph_2.svg */ @Test fun `test of topology sort over advanced graph`() { val graph = listOf<Node<String>>( Node("5"), Node("7"), Node("3"), Node("11", mutableListOf("5", "7")), Node("8", mutableListOf("7", "3")), Node("2", mutableListOf("11")), Node("9", mutableListOf("11", "8")), Node("10", mutableListOf("11", "3")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[5, 7, 3, 11, 8, 2, 10, 9]") } /** * test of more complicated graph with multiple starts (https://www.youtube.com/watch?v=tFpvX8T0-Pw) */ @Test fun `test of topology sort over advanced graph with two starts`() { val graph = listOf<Node<String>>( Node("A", mutableListOf("B")), Node("B", mutableListOf("E")), Node("C", mutableListOf("B")), Node("D", mutableListOf("A", "F")), Node("E", mutableListOf()), Node("F", mutableListOf("E")), Node("G", mutableListOf("C", "D", "J")), Node("H", mutableListOf("F", "I", "K")), Node("I", mutableListOf()), Node("J", mutableListOf("H")), Node("K", mutableListOf("I")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[E, I, B, F, K, A, C, H, D, J, G]") } }
nomic-core/src/test/kotlin/nomic/core/TopologySortTest.kt
1943131166
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.filament.litcube import android.animation.ValueAnimator import android.app.Activity import android.opengl.Matrix import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import android.view.animation.LinearInterpolator import com.google.android.filament.* import com.google.android.filament.RenderableManager.* import com.google.android.filament.VertexBuffer.* import com.google.android.filament.android.DisplayHelper import com.google.android.filament.android.UiHelper import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels class MainActivity : Activity() { // Make sure to initialize Filament first // This loads the JNI library needed by most API calls companion object { init { Filament.init() } } // The View we want to render into private lateinit var surfaceView: SurfaceView // UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture private lateinit var uiHelper: UiHelper // DisplayHelper is provided by Filament to manage the display private lateinit var displayHelper: DisplayHelper // Choreographer is used to schedule new frames private lateinit var choreographer: Choreographer // Engine creates and destroys Filament resources // Each engine must be accessed from a single thread of your choosing // Resources cannot be shared across engines private lateinit var engine: Engine // A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.) private lateinit var renderer: Renderer // A scene holds all the renderable, lights, etc. to be drawn private lateinit var scene: Scene // A view defines a viewport, a scene and a camera for rendering private lateinit var view: View // Should be pretty obvious :) private lateinit var camera: Camera private lateinit var material: Material private lateinit var materialInstance: MaterialInstance private lateinit var vertexBuffer: VertexBuffer private lateinit var indexBuffer: IndexBuffer // Filament entity representing a renderable object @Entity private var renderable = 0 @Entity private var light = 0 // A swap chain is Filament's representation of a surface private var swapChain: SwapChain? = null // Performs the rendering and schedules new frames private val frameScheduler = FrameCallback() private val animator = ValueAnimator.ofFloat(0.0f, 360.0f) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) setContentView(surfaceView) choreographer = Choreographer.getInstance() displayHelper = DisplayHelper(this) setupSurfaceView() setupFilament() setupView() setupScene() } private fun setupSurfaceView() { uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) uiHelper.renderCallback = SurfaceCallback() // NOTE: To choose a specific rendering resolution, add the following line: // uiHelper.setDesiredSize(1280, 720) uiHelper.attachTo(surfaceView) } private fun setupFilament() { engine = Engine.create() renderer = engine.createRenderer() scene = engine.createScene() view = engine.createView() camera = engine.createCamera(engine.entityManager.create()) } private fun setupView() { scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine) // NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference // view.isPostProcessingEnabled = false // Tell the view which camera we want to use view.camera = camera // Tell the view which scene we want to render view.scene = scene } private fun setupScene() { loadMaterial() setupMaterial() createMesh() // To create a renderable we first create a generic entity renderable = EntityManager.get().create() // We then create a renderable component on that entity // A renderable is made of several primitives; in this case we declare only 1 // If we wanted each face of the cube to have a different material, we could // declare 6 primitives (1 per face) and give each of them a different material // instance, setup with different parameters RenderableManager.Builder(1) // Overall bounding box of the renderable .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f)) // Sets the mesh data of the first primitive, 6 faces of 6 indices each .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6) // Sets the material of the first primitive .material(0, materialInstance) .build(engine, renderable) // Add the entity to the scene to render it scene.addEntity(renderable) // We now need a light, let's create a directional light light = EntityManager.get().create() // Create a color from a temperature (5,500K) val (r, g, b) = Colors.cct(5_500.0f) LightManager.Builder(LightManager.Type.DIRECTIONAL) .color(r, g, b) // Intensity of the sun in lux on a clear day .intensity(110_000.0f) // The direction is normalized on our behalf .direction(0.0f, -0.5f, -1.0f) .castShadows(true) .build(engine, light) // Add the entity to the scene to light it scene.addEntity(light) // Set the exposure on the camera, this exposure follows the sunny f/16 rule // Since we've defined a light that has the same intensity as the sun, it // guarantees a proper exposure camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f) // Move the camera back to see the object camera.lookAt(0.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) startAnimation() } private fun loadMaterial() { readUncompressedAsset("materials/lit.filamat").let { material = Material.Builder().payload(it, it.remaining()).build(engine) } } private fun setupMaterial() { // Create an instance of the material to set different parameters on it materialInstance = material.createInstance() // Specify that our color is in sRGB so the conversion to linear // is done automatically for us. If you already have a linear color // you can pass it directly, or use Colors.RgbType.LINEAR materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f) // The default value is always 0, but it doesn't hurt to be clear about our intentions // Here we are defining a dielectric material materialInstance.setParameter("metallic", 0.0f) // We increase the roughness to spread the specular highlights materialInstance.setParameter("roughness", 0.3f) } private fun createMesh() { val floatSize = 4 val shortSize = 2 // A vertex is a position + a tangent frame: // 3 floats for XYZ position, 4 floats for normal+tangents (quaternion) val vertexSize = 3 * floatSize + 4 * floatSize // Define a vertex and a function to put a vertex in a ByteBuffer @Suppress("ArrayInDataClass") data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray) fun ByteBuffer.put(v: Vertex): ByteBuffer { putFloat(v.x) putFloat(v.y) putFloat(v.z) v.tangents.forEach { putFloat(it) } return this } // 6 faces, 4 vertices per face val vertexCount = 6 * 4 // Create tangent frames, one per face val tfPX = FloatArray(4) val tfNX = FloatArray(4) val tfPY = FloatArray(4) val tfNY = FloatArray(4) val tfPZ = FloatArray(4) val tfNZ = FloatArray(4) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ) MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ) val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) // It is important to respect the native byte order .order(ByteOrder.nativeOrder()) // Face -Z .put(Vertex(-1.0f, -1.0f, -1.0f, tfNZ)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNZ)) // Face +X .put(Vertex( 1.0f, -1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPX)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPX)) // Face +Z .put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ)) // Face -X .put(Vertex(-1.0f, -1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNX)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNX)) // Face -Y .put(Vertex(-1.0f, -1.0f, 1.0f, tfNY)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfNY)) // Face +Y .put(Vertex(-1.0f, 1.0f, -1.0f, tfPY)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPY)) // Make sure the cursor is pointing in the right place in the byte buffer .flip() // Declare the layout of our mesh vertexBuffer = VertexBuffer.Builder() .bufferCount(1) .vertexCount(vertexCount) // Because we interleave position and color data we must specify offset and stride // We could use de-interleaved data by declaring two buffers and giving each // attribute a different buffer index .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) .attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize) .build(engine) // Feed the vertex data to the mesh // We only set 1 buffer because the data is interleaved vertexBuffer.setBufferAt(engine, 0, vertexData) // Create the indices val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize) .order(ByteOrder.nativeOrder()) repeat(6) { val i = (it * 4).toShort() indexData .putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort()) .putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort()) } indexData.flip() // 6 faces, 2 triangles per face, indexBuffer = IndexBuffer.Builder() .indexCount(vertexCount * 2) .bufferType(IndexBuffer.Builder.IndexType.USHORT) .build(engine) indexBuffer.setBuffer(engine, indexData) } private fun startAnimation() { // Animate the triangle animator.interpolator = LinearInterpolator() animator.duration = 6000 animator.repeatMode = ValueAnimator.RESTART animator.repeatCount = ValueAnimator.INFINITE animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { val transformMatrix = FloatArray(16) override fun onAnimationUpdate(a: ValueAnimator) { Matrix.setRotateM(transformMatrix, 0, a.animatedValue as Float, 0.0f, 1.0f, 0.0f) val tcm = engine.transformManager tcm.setTransform(tcm.getInstance(renderable), transformMatrix) } }) animator.start() } override fun onResume() { super.onResume() choreographer.postFrameCallback(frameScheduler) animator.start() } override fun onPause() { super.onPause() choreographer.removeFrameCallback(frameScheduler) animator.cancel() } override fun onDestroy() { super.onDestroy() // Stop the animation and any pending frame choreographer.removeFrameCallback(frameScheduler) animator.cancel(); // Always detach the surface before destroying the engine uiHelper.detach() // Cleanup all resources engine.destroyEntity(light) engine.destroyEntity(renderable) engine.destroyRenderer(renderer) engine.destroyVertexBuffer(vertexBuffer) engine.destroyIndexBuffer(indexBuffer) engine.destroyMaterialInstance(materialInstance) engine.destroyMaterial(material) engine.destroyView(view) engine.destroyScene(scene) engine.destroyCameraComponent(camera.entity) // Engine.destroyEntity() destroys Filament related resources only // (components), not the entity itself val entityManager = EntityManager.get() entityManager.destroy(light) entityManager.destroy(renderable) entityManager.destroy(camera.entity) // Destroying the engine will free up any resource you may have forgotten // to destroy, but it's recommended to do the cleanup properly engine.destroy() } inner class FrameCallback : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { // Schedule the next frame choreographer.postFrameCallback(this) // This check guarantees that we have a swap chain if (uiHelper.isReadyToRender) { // If beginFrame() returns false you should skip the frame // This means you are sending frames too quickly to the GPU if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { renderer.render(view) renderer.endFrame() } } } } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface) displayHelper.attach(renderer, surfaceView.display) } override fun onDetachedFromSurface() { displayHelper.detach() swapChain?.let { engine.destroySwapChain(it) // Required to ensure we don't return before Filament is done executing the // destroySwapChain command, otherwise Android might destroy the Surface // too early engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { val aspect = width.toDouble() / height.toDouble() camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL) view.viewport = Viewport(0, 0, width, height) } } private fun readUncompressedAsset(assetName: String): ByteBuffer { assets.openFd(assetName).use { fd -> val input = fd.createInputStream() val dst = ByteBuffer.allocate(fd.length.toInt()) val src = Channels.newChannel(input) src.read(dst) src.close() return dst.apply { rewind() } } } }
android/samples/sample-lit-cube/src/main/java/com/google/android/filament/litcube/MainActivity.kt
2189210463
package com.letit0or1.akimaleo.eyedoctor import com.letit0or1.akimaleo.eyedoctor.colorblind.entity.DataCollection /** * Created by akimaleo on 15.01.17. */ class Application : android.app.Application() { override fun onCreate() { super.onCreate() //set application context to dataCollection class for allowing resources access DataCollection.instance.context = applicationContext } }
app/src/main/java/com/letit0or1/akimaleo/eyedoctor/Application.kt
791305065
package expo.modules.devmenu.react import android.util.Log import com.facebook.react.ReactInstanceManager import com.facebook.react.devsupport.DevServerHelper import com.facebook.react.devsupport.DevSupportManagerBase import com.facebook.react.devsupport.interfaces.DevSupportManager import com.facebook.react.packagerconnection.JSPackagerClient import com.facebook.react.packagerconnection.RequestHandler import expo.modules.devmenu.DevMenuManager import expo.modules.devmenu.helpers.getPrivateDeclaredFieldValue import expo.modules.devmenu.helpers.setPrivateDeclaredFieldValue import kotlinx.coroutines.delay import kotlinx.coroutines.launch class DevMenuPackagerCommandHandlersSwapper { fun swapPackagerCommandHandlers( reactInstanceManager: ReactInstanceManager, handlers: Map<String, RequestHandler> ) { try { val devSupportManager: DevSupportManager = ReactInstanceManager::class.java.getPrivateDeclaredFieldValue( "mDevSupportManager", reactInstanceManager ) // We don't want to add handlers into `DisabledDevSupportManager` or other custom classes if (devSupportManager !is DevSupportManagerBase) { return } val currentCommandHandlers: Map<String, RequestHandler>? = DevSupportManagerBase::class.java.getPrivateDeclaredFieldValue( "mCustomPackagerCommandHandlers", devSupportManager ) val newCommandHandlers = currentCommandHandlers?.toMutableMap() ?: mutableMapOf() newCommandHandlers.putAll(handlers) DevSupportManagerBase::class.java.setPrivateDeclaredFieldValue( "mCustomPackagerCommandHandlers", devSupportManager, newCommandHandlers ) swapCurrentCommandHandlers(reactInstanceManager, handlers) } catch (e: Exception) { Log.w("DevMenu", "Couldn't add packager command handlers to current client: ${e.message}", e) } } /** * No matter where we swap the command handlers there always will be an instance of [JSPackagerClient] * that was created before swapping. The only place where you can add custom handlers, * is in the [com.facebook.react.ReactInstanceManagerBuilder.setCustomPackagerCommandHandlers]. * Unfortunately, we don't have access to this function. What's worst, we can't even add a new installation step. * The builder is hidden from the user. * * So we need to swap command handlers in the current [JSPackagerClient] instance. * However, we can't just use the reflection API to access handlers variable inside that object, * cause we don't know if it is available. [JSPackagerClient] is created on background thread (see [DevServerHelper.openPackagerConnection]). * The final solution is to spin a background task that monitors if the client is present. */ private fun swapCurrentCommandHandlers( reactInstanceManager: ReactInstanceManager, handlers: Map<String, RequestHandler> ) { DevMenuManager.coroutineScope.launch { try { while (true) { val devSupportManager: DevSupportManagerBase = ReactInstanceManager::class.java.getPrivateDeclaredFieldValue( "mDevSupportManager", reactInstanceManager ) val devServerHelper: DevServerHelper = DevSupportManagerBase::class.java.getPrivateDeclaredFieldValue( "mDevServerHelper", devSupportManager ) val jsPackagerClient: JSPackagerClient? = DevServerHelper::class.java.getPrivateDeclaredFieldValue( "mPackagerClient", devServerHelper ) if (jsPackagerClient != null) { val currentCommandHandlers: Map<String, RequestHandler>? = JSPackagerClient::class.java.getPrivateDeclaredFieldValue( "mRequestHandlers", jsPackagerClient ) val newCommandHandlers = currentCommandHandlers?.toMutableMap() ?: mutableMapOf() newCommandHandlers.putAll(handlers) JSPackagerClient::class.java.setPrivateDeclaredFieldValue( "mRequestHandlers", jsPackagerClient, newCommandHandlers ) return@launch } delay(50) } } catch (e: Exception) { Log.w("DevMenu", "Couldn't add packager command handlers to current client: ${e.message}", e) } } } }
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/react/DevMenuPackagerCommandHandlersSwapper.kt
330630326
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable import java.io.Serializable import java.nio.ByteBuffer open class BasalInsulinProgramElement( val startSlotIndex: Byte, val numberOfSlots: Byte, val totalTenthPulses: Short ) : Encodable, Serializable { override val encoded: ByteArray get() = ByteBuffer.allocate(6) .putShort(totalTenthPulses) .putInt(if (totalTenthPulses.toInt() == 0) Int.MIN_VALUE or delayBetweenTenthPulsesInUsec else delayBetweenTenthPulsesInUsec) .array() val durationInSeconds: Short get() = (numberOfSlots * 1800).toShort() val delayBetweenTenthPulsesInUsec: Int get() = if (totalTenthPulses.toInt() == 0) { ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT } else (ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT.toLong() * numberOfSlots / totalTenthPulses.toDouble()).toInt() override fun toString(): String { return "LongInsulinProgramElement{" + "startSlotIndex=" + startSlotIndex + ", numberOfSlots=" + numberOfSlots + ", totalTenthPulses=" + totalTenthPulses + ", delayBetweenTenthPulsesInUsec=" + delayBetweenTenthPulsesInUsec + '}' } }
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt
2799247707
package tr.xip.scd.tensuu.student import android.annotation.SuppressLint import android.app.Application import android.content.Context import android.support.v7.app.AppCompatDelegate import io.realm.Realm class App : Application() { /* Fix for vector drawables in pre-23 * * See: http://stackoverflow.com/questions/36867298/using-android-vector-drawables-on-pre-lollipop-crash */ init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } override fun onCreate() { context = this super.onCreate() /* Realm */ Realm.init(this) } companion object { /** * A static [Context] accessible from everywhere. */ @SuppressLint("StaticFieldLeak") lateinit var context: Context } }
app-student/src/main/java/tr/xip/scd/tensuu/student/App.kt
2954618089
package com.sivalabs.geeksclub.techfeed import com.sivalabs.geeksclub.entities.Link import org.springframework.data.domain.Sort import org.springframework.data.jpa.repository.JpaRepository interface LinkRepository : JpaRepository<Link, Long> { fun findByTitleContainingIgnoreCase(q: String, sort: Sort): List<Link> fun findByCreatedById(userId: Long): List<Link> fun findByCategoryIdAndTitleContainingIgnoreCase(catId: Long, query: String): List<Link> }
spring-boot-k8s-demo/src/main/kotlin/com/sivalabs/geeksclub/techfeed/LinkRepository.kt
4182248846
/* * Copyright (c) 2021. Adventech <[email protected]> * * 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 app.ss.lessons.data.repository.lessons import app.ss.lessons.data.model.QuarterlyLessonInfo import app.ss.lessons.data.repository.quarterly.QuarterliesDataSource import app.ss.lessons.data.repository.quarterly.QuarterlyInfoDataSource import app.ss.models.PdfAnnotations import app.ss.models.PreferredBibleVersion import app.ss.models.SSDay import app.ss.models.SSLessonInfo import app.ss.models.SSQuarterlyInfo import app.ss.models.SSRead import app.ss.models.SSReadComments import app.ss.models.SSReadHighlights import app.ss.models.TodayData import app.ss.models.WeekData import app.ss.models.WeekDay import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs import com.cryart.sabbathschool.core.misc.DateHelper.formatDate import com.cryart.sabbathschool.core.misc.DateHelper.parseDate import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.response.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import org.joda.time.DateTime import javax.inject.Inject import javax.inject.Singleton @Singleton internal class LessonsRepositoryImpl @Inject constructor( private val ssPrefs: SSPrefs, private val quarterliesDataSource: QuarterliesDataSource, private val quarterlyInfoDataSource: QuarterlyInfoDataSource, private val lessonInfoDataSource: LessonInfoDataSource, private val readsDataSource: ReadsDataSource, private val pdfAnnotationsDataSource: PdfAnnotationsDataSource, private val readCommentsDataSource: ReadCommentsDataSource, private val readHighlightsDataSource: ReadHighlightsDataSource, private val bibleVersionDataSource: BibleVersionDataSource, private val dispatcherProvider: DispatcherProvider, private val readerArtifactHelper: ReaderArtifactHelper ) : LessonsRepository { override suspend fun getLessonInfo(lessonIndex: String, cached: Boolean): Resource<SSLessonInfo> { return if (cached) { withContext(dispatcherProvider.io) { lessonInfoDataSource.cache.getItem(LessonInfoDataSource.Request(lessonIndex)) } } else { lessonInfoDataSource.getItem(LessonInfoDataSource.Request(lessonIndex)) } } override suspend fun getTodayRead(cached: Boolean): Resource<TodayData> { val dataResponse = getQuarterlyAndLessonInfo(cached) val lessonInfo = dataResponse.data?.lessonInfo ?: return Resource.error(dataResponse.error ?: Throwable("Invalid QuarterlyInfo")) val today = DateTime.now().withTimeAtStartOfDay() val todayModel = lessonInfo.days.find { day -> today.isEqual(parseDate(day.date)) }?.let { day -> TodayData( day.index, lessonInfo.lesson.index, day.title, formatDate(day.date), lessonInfo.lesson.cover ) } ?: return Resource.error(Throwable("Error Finding Today Read")) return Resource.success(todayModel) } private suspend fun getQuarterlyAndLessonInfo(cached: Boolean): Resource<QuarterlyLessonInfo> { val quarterlyResponse = getQuarterlyInfo() val quarterlyInfo = quarterlyResponse.data ?: return Resource.error(quarterlyResponse.error ?: Throwable("Invalid QuarterlyInfo")) val lessonInfo = getWeekLessonInfo(quarterlyInfo, cached) ?: return Resource.error(Throwable("Invalid LessonInfo")) return Resource.success(QuarterlyLessonInfo(quarterlyInfo, lessonInfo)) } private suspend fun getQuarterlyInfo(): Resource<SSQuarterlyInfo> { val index = getLastQuarterlyInfoIfCurrent()?.let { return Resource.success(it) } ?: getDefaultQuarterlyIndex() ?: return Resource.error(Throwable("Invalid Quarterly Index")) return withContext(dispatcherProvider.io) { quarterlyInfoDataSource.cache.getItem(QuarterlyInfoDataSource.Request(index)) } } private suspend fun getLastQuarterlyInfoIfCurrent(): SSQuarterlyInfo? { val index = ssPrefs.getLastQuarterlyIndex() ?: return null val info = withContext(dispatcherProvider.io) { quarterlyInfoDataSource.cache.getItem(QuarterlyInfoDataSource.Request(index)).data } ?: return null val today = DateTime.now().withTimeAtStartOfDay() return if (today.isBefore(parseDate(info.quarterly.end_date))) { info } else { null } } private suspend fun getDefaultQuarterlyIndex(): String? { val resource = withContext(dispatcherProvider.io) { quarterliesDataSource.cache.get(QuarterliesDataSource.Request(ssPrefs.getLanguageCode())) } val quarterly = resource.data?.firstOrNull() return quarterly?.index } private suspend fun getWeekLessonInfo(quarterlyInfo: SSQuarterlyInfo, cached: Boolean): SSLessonInfo? { val lesson = quarterlyInfo.lessons.find { lesson -> val startDate = parseDate(lesson.start_date) val endDate = parseDate(lesson.end_date) val today = DateTime.now().withTimeAtStartOfDay() startDate?.isBeforeNow == true && (endDate?.isAfterNow == true || today.isEqual(endDate)) } return lesson?.let { getLessonInfo(it.index, cached).data } } override suspend fun getDayRead(dayIndex: String): Resource<SSRead> = withContext(dispatcherProvider.io) { readsDataSource.cache.getItem( ReadsDataSource.Request(dayIndex = dayIndex, fullPath = "") ) } override suspend fun getDayRead(day: SSDay): Resource<SSRead> = readsDataSource.getItem( ReadsDataSource.Request( dayIndex = day.index, fullPath = day.full_read_path ) ) override suspend fun getWeekData(cached: Boolean): Resource<WeekData> { val dataResponse = getQuarterlyAndLessonInfo(cached) val (quarterlyInfo, lessonInfo) = dataResponse.data ?: return Resource.error(dataResponse.error ?: Throwable("Invalid QuarterlyInfo")) val today = DateTime.now().withTimeAtStartOfDay() val days = lessonInfo.days.map { ssDay -> WeekDay( ssDay.index, ssDay.title, formatDate(ssDay.date, SSConstants.SS_DATE_FORMAT_OUTPUT_DAY_SHORT), today.isEqual(parseDate(ssDay.date)) ) }.take(7) return Resource.success( WeekData( quarterlyInfo.quarterly.index, quarterlyInfo.quarterly.title, lessonInfo.lesson.index, lessonInfo.lesson.title, quarterlyInfo.quarterly.cover, days ) ) } override suspend fun saveAnnotations(lessonIndex: String, pdfId: String, annotations: List<PdfAnnotations>) { pdfAnnotationsDataSource.sync( PdfAnnotationsDataSource.Request(lessonIndex, pdfId), annotations ) } override fun getAnnotations( lessonIndex: String, pdfId: String ): Flow<Resource<List<PdfAnnotations>>> = pdfAnnotationsDataSource.getAsFlow( PdfAnnotationsDataSource.Request(lessonIndex, pdfId) ) override suspend fun getComments( readIndex: String ): Resource<SSReadComments> = readCommentsDataSource.getItem(ReadCommentsDataSource.Request(readIndex)) override suspend fun saveComments(comments: SSReadComments) { readCommentsDataSource.sync( ReadCommentsDataSource.Request(comments.readIndex), listOf(comments) ) } override suspend fun getReadHighlights( readIndex: String ): Resource<SSReadHighlights> = readHighlightsDataSource.getItem(ReadHighlightsDataSource.Request(readIndex)) override suspend fun saveHighlights(highlights: SSReadHighlights) { readHighlightsDataSource.sync( ReadHighlightsDataSource.Request(highlights.readIndex), listOf(highlights) ) } override fun checkReaderArtifact() { readerArtifactHelper.sync() } override suspend fun getPreferredBibleVersion(): String? = withContext(dispatcherProvider.io) { bibleVersionDataSource .cache .getItem(BibleVersionDataSource.Request(ssPrefs.getLanguageCode())) .data?.version } override suspend fun savePreferredBibleVersion(version: String) = withContext(dispatcherProvider.io) { bibleVersionDataSource .cache .updateItem(PreferredBibleVersion(version, ssPrefs.getLanguageCode())) } }
common/lessons-data/src/main/java/app/ss/lessons/data/repository/lessons/LessonsRepositoryImpl.kt
3409190345
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.profile.codeInspection import com.intellij.codeInsight.daemon.impl.SeverityRegistrar import com.intellij.codeInspection.InspectionProfile import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.project.Project import com.intellij.profile.Profile import com.intellij.profile.ProfileChangeAdapter import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus @JvmField internal val LOG = Logger.getInstance(BaseInspectionProfileManager::class.java) abstract class BaseInspectionProfileManager(messageBus: MessageBus) : InspectionProjectProfileManager() { protected abstract val schemeManager: SchemeManager<InspectionProfileImpl> protected val profileListeners: MutableList<ProfileChangeAdapter> = ContainerUtil.createLockFreeCopyOnWriteList<ProfileChangeAdapter>() private val severityRegistrar = SeverityRegistrar(messageBus) override final fun getSeverityRegistrar() = severityRegistrar override final fun getOwnSeverityRegistrar() = severityRegistrar override final fun addProfileChangeListener(listener: ProfileChangeAdapter, parentDisposable: Disposable) { ContainerUtil.add(listener, profileListeners, parentDisposable) } @Suppress("OverridingDeprecatedMember") override final fun addProfileChangeListener(listener: ProfileChangeAdapter) { profileListeners.add(listener) } @Suppress("OverridingDeprecatedMember") override final fun removeProfileChangeListener(listener: ProfileChangeAdapter) { profileListeners.remove(listener) } internal fun cleanupSchemes(project: Project) { for (profile in schemeManager.allSchemes) { profile.cleanup(project) } } override final fun fireProfileChanged(profile: Profile?) { if (profile is InspectionProfileImpl) { profile.profileChanged() } for (adapter in profileListeners) { adapter.profileChanged(profile) } } override final fun fireProfileChanged(oldProfile: Profile?, profile: Profile) { for (adapter in profileListeners) { adapter.profileActivated(oldProfile, profile) } } fun addProfile(profile: InspectionProfileImpl) { schemeManager.addScheme(profile) } override final fun deleteProfile(name: String) { schemeManager.removeScheme(name)?.let { schemeRemoved(it) } } fun deleteProfile(profile: InspectionProfileImpl) { schemeManager.removeScheme(profile) schemeRemoved(profile) } open protected fun schemeRemoved(scheme: InspectionProfile) { } override fun updateProfile(profile: Profile) { schemeManager.addScheme(profile as InspectionProfileImpl) fireProfileChanged(profile) } } abstract class InspectionProfileProcessor : LazySchemeProcessor<InspectionProfileImpl, InspectionProfileImpl>() { override fun getState(scheme: InspectionProfileImpl): SchemeState { return if (scheme.wasInitialized()) SchemeState.POSSIBLY_CHANGED else SchemeState.UNCHANGED } }
platform/analysis-impl/src/com/intellij/profile/codeInspection/BaseInspectionProfileManager.kt
2200805909
// 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.scratch.compile import org.jetbrains.kotlin.diagnostics.rendering.Renderers import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore class KtScratchSourceFileProcessor { companion object { const val GENERATED_OUTPUT_PREFIX = "##scratch##generated##" const val LINES_INFO_MARKER = "end##" const val END_OUTPUT_MARKER = "end##!@#%^&*" const val OBJECT_NAME = "ScratchFileRunnerGenerated" const val INSTANCE_NAME = "instanceScratchFileRunner" const val PACKAGE_NAME = "org.jetbrains.kotlin.idea.scratch.generated" const val GET_RES_FUN_NAME_PREFIX = "generated_get_instance_res" } fun process(expressions: List<ScratchExpression>): Result { val sourceProcessor = KtSourceProcessor() expressions.forEach { sourceProcessor.process(it) } val codeResult = """ package $PACKAGE_NAME ${sourceProcessor.imports.joinToString("\n") { it.text }} object $OBJECT_NAME { class $OBJECT_NAME { ${sourceProcessor.classBuilder} } @JvmStatic fun main(args: Array<String>) { val $INSTANCE_NAME = $OBJECT_NAME() ${sourceProcessor.objectBuilder} println("$END_OUTPUT_MARKER") } } """ return Result.OK("$PACKAGE_NAME.$OBJECT_NAME", codeResult) } class KtSourceProcessor { val classBuilder = StringBuilder() val objectBuilder = StringBuilder() val imports = arrayListOf<KtImportDirective>() private var resCount = 0 fun process(expression: ScratchExpression) { when (val psiElement = expression.element) { is KtDestructuringDeclaration -> processDestructuringDeclaration(expression, psiElement) is KtVariableDeclaration -> processDeclaration(expression, psiElement) is KtFunction -> processDeclaration(expression, psiElement) is KtClassOrObject -> processDeclaration(expression, psiElement) is KtImportDirective -> imports.add(psiElement) is KtExpression -> processExpression(expression, psiElement) } } private fun processDeclaration(e: ScratchExpression, c: KtDeclaration) { classBuilder.append(c.text).newLine() val descriptor = c.resolveToDescriptorIfAny() ?: return val context = RenderingContext.of(descriptor) objectBuilder.println(Renderers.COMPACT.render(descriptor, context)) objectBuilder.appendLineInfo(e) } private fun processDestructuringDeclaration(e: ScratchExpression, c: KtDestructuringDeclaration) { val entries = c.entries.mapNotNull { if (it.isSingleUnderscore) null else it.resolveToDescriptorIfAny() } entries.forEach { val context = RenderingContext.of(it) val rendered = Renderers.COMPACT.render(it, context) classBuilder.append(rendered).newLine() objectBuilder.println(rendered) } objectBuilder.appendLineInfo(e) classBuilder.append("init {").newLine() classBuilder.append(c.text).newLine() entries.forEach { classBuilder.append("this.${it.name} = ${it.name}").newLine() } classBuilder.append("}").newLine() } private fun processExpression(e: ScratchExpression, expr: KtExpression) { val resName = "$GET_RES_FUN_NAME_PREFIX$resCount" classBuilder.append("fun $resName() = run { ${expr.text} }").newLine() objectBuilder.printlnObj("$INSTANCE_NAME.$resName()") objectBuilder.appendLineInfo(e) resCount += 1 } private fun StringBuilder.appendLineInfo(e: ScratchExpression) { println("$LINES_INFO_MARKER${e.lineStart}|${e.lineEnd}") } private fun StringBuilder.println(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX$str\")").newLine() private fun StringBuilder.printlnObj(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX\${$str}\")").newLine() private fun StringBuilder.newLine() = append("\n") } sealed class Result { class Error(val message: String) : Result() class OK(val mainClassName: String, val code: String) : Result() } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchSourceFileProcessor.kt
3013614520
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.sdk.wasm class SingletonApiTest : AbstractSingletonApiTest() { var x = 0 init { handles.inHandle.onUpdate { x = 1 } } override fun fireEvent(slotName: String, eventName: String, eventData: Map<String, String>) { when (eventName) { "case1" -> { if (handles.ioHandle.fetch() == null) { handles.errors.store( SingletonApiTest_Errors(msg = "case1: populated handle should not be null") ) } if (x == 1) { handles.errors.store( SingletonApiTest_Errors( msg = "case1: handle.onUpdate should not have been called yet." ) ) } handles.outHandle.clear() handles.ioHandle.clear() if (handles.ioHandle.fetch() != null) { handles.errors.store( SingletonApiTest_Errors(msg = "case1: cleared handle should be null") ) } } "case2" -> { if (x == 0) { handles.errors.store( SingletonApiTest_Errors( msg = "case1: handle.onUpdate should have been called." ) ) } val input = handles.inHandle.fetch() val d = SingletonApiTest_OutHandle( num = input?.num ?: 0.0, txt = input?.txt ?: "" ) handles.outHandle.store(d.copy(num = d.num.times(2))) } "case3" -> { val input = handles.inHandle.fetch() val d = SingletonApiTest_IoHandle( num = input?.num ?: 0.0, txt = input?.txt ?: "" ) handles.ioHandle.store(d.copy(d.num.times(3))) } "case4" -> { if (handles.ioHandle.fetch() != null) { handles.errors.store( SingletonApiTest_Errors(msg = "case4: cleared handle should be null") ) } handles.outHandle.store(SingletonApiTest_OutHandle(txt = "out", num = 0.0)) handles.ioHandle.store(SingletonApiTest_IoHandle(txt = "io", num = 0.0)) if (handles.ioHandle.fetch() == null) { handles.errors.store( SingletonApiTest_Errors(msg = "case4: populated handle should not be null") ) } } } } }
javatests/arcs/sdk/wasm/SingletonApiTest.kt
1525045627