content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2015 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.android.robowrapper
import android.app.Activity
import android.view.Gravity
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.test.*
import android.text.TextUtils.TruncateAt
import android.widget.ImageView.ScaleType
import android.widget.TextView
import android.view.View
import android.widget.LinearLayout
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import android.widget.Button
import java.io.ByteArrayInputStream
import kotlin.dom.parseXml
import org.w3c.dom.Element
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner::class)
class XmlBuilderTest {
@Test
fun testXml() {
val a = Robolectric.setupActivity<Activity>(Activity::class.java)
val frameLayout = FrameLayout(a)
val linearLayout = LinearLayout(a)
linearLayout.orientation = LinearLayout.VERTICAL
val textView = TextView(a)
textView.setPadding(10, 20, 30, 40)
val textViewLP = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
textViewLP.gravity = Gravity.CENTER
val button = Button(a)
button.text = "Button text"
linearLayout.addView(textView, textViewLP)
linearLayout.addView(button)
frameLayout.addView(linearLayout)
val xml = toXml(parseView(frameLayout))
val inputStream = ByteArrayInputStream(xml.toByteArray("UTF-8"))
val document = parseXml(inputStream)
val rootElement = document.documentElement!!
assertEquals("FrameLayout", rootElement.tagName)
val linearLayoutElement = rootElement.getElementsByTagName("LinearLayout")?.item(0) as Element
assertEquals("LinearLayout", linearLayoutElement.tagName)
assertEquals("vertical", linearLayoutElement.getAttribute("android:orientation"))
val textViewElement = linearLayoutElement.getElementsByTagName("TextView")?.item(0) as Element
assertEquals("TextView", textViewElement.tagName)
assertEquals("10dp", textViewElement.getAttribute("android:paddingLeft"))
assertEquals("20dp", textViewElement.getAttribute("android:paddingTop"))
assertEquals("30dp", textViewElement.getAttribute("android:paddingRight"))
assertEquals("40dp", textViewElement.getAttribute("android:paddingBottom"))
assertEquals("match_parent", textViewElement.getAttribute("android:layout_width"))
assertEquals("wrap_content", textViewElement.getAttribute("android:layout_height"))
assertEquals("center_vertical|center_horizontal", textViewElement.getAttribute("android:layout_gravity"))
val buttonElement = linearLayoutElement.getElementsByTagName("Button")?.item(0) as Element
assertEquals("Button", buttonElement.tagName)
assertEquals("Button text", buttonElement.getAttribute("android:text"))
}
@Test
fun testGravity() {
Robolectric.setupActivity<Activity>(Activity::class.java)
assertEquals("center_vertical|center_horizontal", resolveGravity(Gravity.CENTER))
assertEquals("left|right", resolveGravity(Gravity.FILL_HORIZONTAL))
assertEquals("top|bottom", resolveGravity(Gravity.FILL_VERTICAL))
assertEquals("top", resolveGravity(Gravity.TOP))
assertEquals("right", resolveGravity(Gravity.RIGHT))
assertEquals("start", resolveGravity(Gravity.START))
assertEquals("end", resolveGravity(Gravity.END))
assertEquals("center_horizontal", resolveGravity(Gravity.CENTER_HORIZONTAL))
assertEquals("right|bottom", resolveGravity(Gravity.RIGHT or Gravity.BOTTOM))
assertEquals("left|top|right|bottom", resolveGravity(Gravity.FILL))
}
@Test
fun testBasicRenderAttr() {
Robolectric.setupActivity<Activity>(Activity::class.java)
val key = "someKey" //used only for debug print
assertEquals("1", basicRenderAttr(key, 1))
assertEquals("-5", basicRenderAttr(key, -5))
assertEquals("0", basicRenderAttr(key, 0))
assertEquals("0", basicRenderAttr(key, 0.0))
assertEquals("2", basicRenderAttr(key, 1.9999999999999999999999999999.toFloat()))
assertEquals("2.5", basicRenderAttr(key, 2.5))
assertEquals("2.5", basicRenderAttr(key, 2.5.toFloat()))
assertEquals("SomeText", basicRenderAttr(key, "SomeText"))
assertEquals("true", basicRenderAttr(key, true))
assertEquals("false", basicRenderAttr(key, false))
}
@Test
fun testResolveEllipsize() {
Robolectric.setupActivity<Activity>(Activity::class.java)
assertEquals("end", convertEllipsize(TruncateAt.END))
assertEquals("marquee", convertEllipsize(TruncateAt.MARQUEE))
assertEquals("middle", convertEllipsize(TruncateAt.MIDDLE))
assertEquals("start", convertEllipsize(TruncateAt.START))
}
@Test
fun testResolveScaleType() {
assertEquals("center", convertScaleType(ScaleType.CENTER))
assertEquals("centerCrop", convertScaleType(ScaleType.CENTER_CROP))
assertEquals("fitInside", convertScaleType(ScaleType.CENTER_INSIDE))
assertEquals("fitCenter", convertScaleType(ScaleType.FIT_CENTER))
assertEquals("fitEnd", convertScaleType(ScaleType.FIT_END))
assertEquals("fitStart", convertScaleType(ScaleType.FIT_START))
assertEquals("fitXY", convertScaleType(ScaleType.FIT_XY))
assertEquals("matrix", convertScaleType(ScaleType.MATRIX))
}
@Test
fun testResolveDimension() {
val a = Robolectric.setupActivity<Activity>(Activity::class.java)
val v = View(a)
assertEquals("17sp", resolveDimension(TextView(a), "textSize", "17"))
assertEquals("4dp", resolveDimension(v, "paddingRight", "4")) //density=1
}
@Test
fun testParseEnumFlagValue() {
assertEquals(-1L, "-1".parseEnumFlagValue())
assertEquals(0L, "0".parseEnumFlagValue())
assertEquals(1L, "1".parseEnumFlagValue())
assertEquals(1L, "0x1".parseEnumFlagValue())
assertEquals(0L, "0x0".parseEnumFlagValue())
assertEquals(255L, "0xfF".parseEnumFlagValue())
}
}
| preview/robowrapper/test/org/jetbrains/kotlin/android/robowrapper/XmlBuilderTest.kt | 4293262042 |
package xyz.rankki.psnine.ui.topics
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.find
import org.jetbrains.anko.support.v4.onRefresh
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import xyz.rankki.psnine.base.BaseFragment
import xyz.rankki.psnine.base.BaseTopicsModel
import xyz.rankki.psnine.common.config.RefreshColors
import xyz.rankki.psnine.common.listener.RecyclerViewScrollListener
import xyz.rankki.psnine.data.http.HttpManager
import xyz.rankki.psnine.ui.topic.TopicActivity
class TopicsFragment<K> : BaseFragment(), RecyclerViewScrollListener.LoadingListener {
private lateinit var mAdapter: TopicsAdapter<K>
private lateinit var clz: Class<*>
private var page: Int = 1
companion object {
const val ID_SwipeRefreshLayout: Int = 1
const val ID_RecyclerView: Int = 2
fun <T, K> newInstance(clz: Class<T>, clazz: Class<K>): TopicsFragment<K> {
val topicsModel: BaseTopicsModel<*> = clz.newInstance() as BaseTopicsModel<*>
val args = Bundle()
val fragment: TopicsFragment<K> = TopicsFragment()
args.putString("clz", clz.name)
args.putString("path", topicsModel.getPath())
args.putString("name", topicsModel.getName())
fragment.arguments = args
return fragment
}
}
override fun initView(): View {
mAdapter = TopicsAdapter(mContext)
mAdapter.clickListener = View.OnClickListener {
val position: Int = find<RecyclerView>(ID_RecyclerView).getChildAdapterPosition(it)
if (position != RecyclerView.NO_POSITION) {
val extras = Bundle()
extras.putString("url", mAdapter.getData(position).getTopicUrl())
ActivityUtils.startActivity(extras, TopicActivity::class.java)
}
}
clz = Class.forName(arguments?.getString("clz")) as Class<*>
return UI {
swipeRefreshLayout {
id = ID_SwipeRefreshLayout
setColorSchemeColors(RefreshColors.ColorA, RefreshColors.ColorB, RefreshColors.ColorC)
onRefresh {
initData()
}
recyclerView {
id = ID_RecyclerView
layoutManager = LinearLayoutManager(mContext)
adapter = mAdapter
addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL))
val scrollListener = RecyclerViewScrollListener(mContext, this@TopicsFragment)
addOnScrollListener(scrollListener)
}
}
}.view
}
override fun initData() {
setRefreshing(true)
HttpManager.get()
.getTopics("${arguments!!.getString("path")}?page=$page", clz)
.subscribe {
mAdapter.updateData(it)
setRefreshing(false)
}
}
private fun setRefreshing(isRefreshing: Boolean) {
find<SwipeRefreshLayout>(ID_SwipeRefreshLayout).isRefreshing = isRefreshing
}
override fun loadMore() {
page += 1
initData()
}
override fun isLoading(): Boolean = find<SwipeRefreshLayout>(ID_SwipeRefreshLayout).isRefreshing
} | app/src/main/java/xyz/rankki/psnine/ui/topics/TopicsFragment.kt | 4127484960 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.sample.tutorial.ui
import com.facebook.flipper.sample.tutorial.MarineMammal
import com.facebook.litho.annotations.FromEvent
import com.facebook.litho.annotations.OnEvent
import com.facebook.litho.annotations.Prop
import com.facebook.litho.sections.Children
import com.facebook.litho.sections.SectionContext
import com.facebook.litho.sections.annotations.GroupSectionSpec
import com.facebook.litho.sections.annotations.OnCreateChildren
import com.facebook.litho.sections.common.DataDiffSection
import com.facebook.litho.sections.common.RenderEvent
import com.facebook.litho.widget.ComponentRenderInfo
import com.facebook.litho.widget.RenderInfo
@GroupSectionSpec
object FeedSectionSpec {
@OnCreateChildren
fun onCreateChildren(c: SectionContext, @Prop data: List<MarineMammal>): Children =
Children.create()
.child(
DataDiffSection.create<MarineMammal>(c)
.data(data)
.renderEventHandler(FeedSection.render(c)))
.build()
@OnEvent(RenderEvent::class)
fun render(c: SectionContext, @FromEvent model: MarineMammal): RenderInfo =
ComponentRenderInfo.create().component(FeedItemCard.create(c).mammal(model).build()).build()
}
| android/tutorial/src/main/java/com/facebook/flipper/sample/tutorial/ui/FeedSectionSpec.kt | 435629457 |
package org.wow.logger
import com.epam.starwors.bot.Logic
import com.epam.starwors.galaxy.Planet
import com.epam.starwors.galaxy.Move
import com.epam.starwors.galaxy.PlanetType
import com.fasterxml.jackson.databind.ObjectMapper
import org.wow.http.GameClient
data class SerializedGameTurn(val planets: List<SerializedPlanet> = arrayListOf(),
var moves: List<PlayerMove> = arrayListOf())
data class SerializedPlanet(val id: String = "",
val owner: String = "",
val units: Int = 0,
val `type`: PlanetType = PlanetType.TYPE_A,
val neighbours: List<String> = listOf())
data class PlayerActionsResponse(val actions: List<PlayerMove> = listOf())
data class GameTurnResponse(val turnNumber: Int = 0, val playersActions: PlayerActionsResponse = PlayerActionsResponse())
public class GameLogger(val serializer: ObjectMapper,
val gameId: String,
val client: GameClient): Logic {
var states: List<GameTurn> = arrayListOf()
/**
* Game turn contains world + moves.
* But moves could be requested only after this game turn
*/
var lastWorld: Collection<Planet>? = null
override fun step(world: Collection<Planet>?): MutableCollection<Move>? {
if(world!!.empty) { // end of the game
return arrayListOf()
}
if(lastWorld != null) {
states = states.plus(GameTurn(lastWorld!!, client.getMovesForPreviousTurn(gameId)))
}
lastWorld = world
return arrayListOf()
}
private fun serializePlanet(planet: Planet): SerializedPlanet = SerializedPlanet(planet.getId()!!,
planet.getOwner()!!,
planet.getUnits(), planet.getType()!!,
planet.getNeighbours()!!.map { it.getId()!! })
fun dump(): ByteArray = serializer.writeValueAsBytes(states.
map { SerializedGameTurn(it.planets.map { serializePlanet(it) }, it.moves) })!!
}
| src/main/kotlin/org/wow/logger/GameLogger.kt | 2137670961 |
package com.gm.soundzones.activity
import android.app.Activity
import android.os.Bundle
import com.gm.soundzones.fragment.SettingsFragment
/**
* Created by titan on 30-Sep-17.
*/
class SettingsActivity : Activity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null){
fragmentManager.beginTransaction()
.replace(android.R.id.content, SettingsFragment())
.commit()
}
}
}
| app/src/main/java/com/gm/soundzones/activity/SettingsActivity.kt | 2083691817 |
package org.tasks.files
import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import androidx.fragment.app.Fragment
import com.google.common.collect.Iterables
import com.google.common.io.ByteStreams
import com.google.common.io.Files
import com.todoroo.astrid.utility.Constants
import org.tasks.Strings.isNullOrEmpty
import org.tasks.extensions.Context.safeStartActivity
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
object FileHelper {
fun newFilePickerIntent(activity: Activity?, initial: Uri?, vararg mimeTypes: String?): Intent =
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
putExtra("android.content.extra.SHOW_ADVANCED", true)
putExtra("android.content.extra.FANCY", true)
putExtra("android.content.extra.SHOW_FILESIZE", true)
addCategory(Intent.CATEGORY_OPENABLE)
setInitialUri(activity, this, initial)
if (mimeTypes.size == 1) {
type = mimeTypes[0]
} else {
type = "*/*"
if (mimeTypes.size > 1) {
putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
}
}
}
fun newDirectoryPicker(fragment: Fragment, rc: Int, initial: Uri?) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
addFlags(
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
or Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)
putExtra("android.content.extra.SHOW_ADVANCED", true)
putExtra("android.content.extra.FANCY", true)
putExtra("android.content.extra.SHOW_FILESIZE", true)
setInitialUri(fragment.context, this, initial)
}
fragment.startActivityForResult(intent, rc)
}
@TargetApi(Build.VERSION_CODES.O)
private fun setInitialUri(context: Context?, intent: Intent, uri: Uri?) {
if (uri == null || uri.scheme != ContentResolver.SCHEME_CONTENT) {
return
}
try {
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, DocumentFile.fromTreeUri(context!!, uri)!!.uri)
} catch (e: Exception) {
Timber.e(e)
}
}
fun delete(context: Context?, uri: Uri?) {
if (uri == null) {
return
}
when (uri.scheme) {
"content" -> {
val documentFile = DocumentFile.fromSingleUri(context!!, uri)
documentFile!!.delete()
}
"file" -> delete(File(uri.path))
}
}
private fun delete(vararg files: File) {
for (file in files) {
if (file.isDirectory) {
file.listFiles()?.let { delete(*it) }
} else {
file.delete()
}
}
}
fun getFilename(context: Context, uri: Uri): String? {
when (uri.scheme) {
ContentResolver.SCHEME_FILE -> return uri.lastPathSegment
ContentResolver.SCHEME_CONTENT -> {
val cursor = context.contentResolver.query(uri, null, null, null, null)
if (cursor != null && cursor.moveToFirst()) {
return try {
cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
} finally {
cursor.close()
}
}
}
}
return null
}
fun getExtension(context: Context, uri: Uri): String? {
if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
val mimeType = context.contentResolver.getType(uri)
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
if (!isNullOrEmpty(extension)) {
return extension
}
}
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.path)
return if (!isNullOrEmpty(extension))
extension
else
Files.getFileExtension(getFilename(context, uri)!!)
}
fun getMimeType(context: Context, uri: Uri): String? {
val mimeType = context.contentResolver.getType(uri)
if (!isNullOrEmpty(mimeType)) {
return mimeType
}
val extension = getExtension(context, uri)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
}
fun startActionView(context: Activity, uri: Uri?) {
var uri = uri ?: return
val mimeType = getMimeType(context, uri)
val intent = Intent(Intent.ACTION_VIEW)
if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
uri = copyToUri(context, Uri.fromFile(context.externalCacheDir), uri)
}
val share = FileProvider.getUriForFile(context, Constants.FILE_PROVIDER_AUTHORITY, File(uri.path))
intent.setDataAndType(share, mimeType)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.safeStartActivity(intent)
}
@JvmStatic
@Throws(IOException::class)
fun newFile(
context: Context, destination: Uri, mimeType: String?, baseName: String, extension: String?): Uri {
val filename = getNonCollidingFileName(context, destination, baseName, extension)
return when (destination.scheme) {
"content" -> {
val tree = DocumentFile.fromTreeUri(context, destination)
val f1 = tree!!.createFile(mimeType!!, filename)
?: throw FileNotFoundException("Failed to create $filename")
f1.uri
}
"file" -> {
val dir = File(destination.path)
if (!dir.exists() && !dir.mkdirs()) {
throw IOException("Failed to create %s" + dir.absolutePath)
}
val f2 = File(dir.absolutePath + File.separator + filename)
if (f2.createNewFile()) {
return Uri.fromFile(f2)
}
throw FileNotFoundException("Failed to create $filename")
}
else -> throw IllegalArgumentException("Unknown URI scheme: " + destination.scheme)
}
}
fun copyToUri(context: Context, destination: Uri, input: Uri): Uri {
val filename = getFilename(context, input)
val basename = Files.getNameWithoutExtension(filename!!)
try {
val output = newFile(
context,
destination,
getMimeType(context, input),
basename,
getExtension(context, input)
)
copyStream(context, input, output)
return output
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
fun copyStream(context: Context, input: Uri?, output: Uri?) {
val contentResolver = context.contentResolver
try {
val inputStream = contentResolver.openInputStream(input!!)
val outputStream = contentResolver.openOutputStream(output!!)
ByteStreams.copy(inputStream!!, outputStream!!)
inputStream.close()
outputStream.close()
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
private fun getNonCollidingFileName(
context: Context, uri: Uri, baseName: String, extension: String?): String {
var extension = extension
var tries = 1
if (!extension!!.startsWith(".")) {
extension = ".$extension"
}
var tempName = baseName
when (uri.scheme) {
ContentResolver.SCHEME_CONTENT -> {
val dir = DocumentFile.fromTreeUri(context, uri)
val documentFiles = Arrays.asList(*dir!!.listFiles())
while (true) {
val result = tempName + extension
if (Iterables.any(documentFiles) { f: DocumentFile? -> f!!.name == result }) {
tempName = "$baseName-$tries"
tries++
} else {
break
}
}
}
ContentResolver.SCHEME_FILE -> {
var f = File(uri.path, baseName + extension)
while (f.exists()) {
tempName = "$baseName-$tries" // $NON-NLS-1$
f = File(uri.path, tempName + extension)
tries++
}
}
}
return tempName + extension
}
fun uri2String(uri: Uri?): String {
if (uri == null) {
return ""
}
return if (uri.scheme == ContentResolver.SCHEME_FILE)
File(uri.path).absolutePath
else
uri.toString()
}
} | app/src/main/java/org/tasks/files/FileHelper.kt | 1360493108 |
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.api.util
import io.kotest.assertions.timing.eventually
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.features.websocket.WebSockets
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import io.ktor.server.engine.embeddedServer
import io.ktor.server.jetty.Jetty
import org.jitsi.utils.logging2.LoggerImpl
import kotlin.random.Random
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
@ExperimentalTime
class WebSocketClientTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val wsPort = Random.nextInt(49152, 65535).also {
println("Server running on port $it")
}
private val client = HttpClient(CIO) {
install(WebSockets)
}
private val wsServer = TestWsServer()
private val server = embeddedServer(Jetty, port = wsPort) {
wsServer.app(this)
}
private val receivedMessages = mutableListOf<Frame>()
private fun incomingMessageHandler(frame: Frame) {
receivedMessages.add(frame)
}
private val testLogger = LoggerImpl("test")
init {
server.start()
context("sendString") {
context("when no reply is expected") {
val ws = WebSocketClient(
client,
"localhost",
wsPort,
"/ws/blackhole",
testLogger,
::incomingMessageHandler
)
ws.run()
ws.sendString("hello")
should("send a message") {
eventually(5.seconds) {
wsServer.receivedMessages shouldHaveSize 1
}
wsServer.receivedMessages.first().shouldBeInstanceOf<Frame.Text>()
(wsServer.receivedMessages.first() as Frame.Text).readText() shouldBe "hello"
}
}
context("when a reply is expected") {
val ws = WebSocketClient(client, "localhost", wsPort, "/ws/echo", testLogger, ::incomingMessageHandler)
ws.run()
ws.sendString("hello")
should("invoke the incoming message handler") {
eventually(5.seconds) {
receivedMessages shouldHaveSize 1
}
receivedMessages.first().shouldBeInstanceOf<Frame.Text>()
(receivedMessages.first() as Frame.Text).readText() shouldBe "hello"
}
}
context("stop") {
val ws = WebSocketClient(client, "localhost", wsPort, "/ws/echo", testLogger, ::incomingMessageHandler)
ws.run()
ws.sendString("hello")
should("clean things up correctly") {
ws.stop()
}
}
}
}
}
| jvb-api/jvb-api-client/src/test/kotlin/org/jitsi/videobridge/api/util/WebSocketClientTest.kt | 1377398472 |
package com.flexpoker
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
} | src/main/kotlin/com/flexpoker/Application.kt | 1765100917 |
package com.flexpoker.table.query.handlers
import com.flexpoker.chat.service.ChatService
import com.flexpoker.framework.event.EventHandler
import com.flexpoker.framework.pushnotifier.PushNotificationPublisher
import com.flexpoker.login.repository.LoginRepository
import com.flexpoker.pushnotifications.TableUpdatedPushNotification
import com.flexpoker.table.command.events.PlayerRaisedEvent
import com.flexpoker.table.query.repository.TableRepository
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class PlayerRaisedEventHandler @Inject constructor(
private val loginRepository: LoginRepository,
private val tableRepository: TableRepository,
private val pushNotificationPublisher: PushNotificationPublisher,
private val chatService: ChatService
) : EventHandler<PlayerRaisedEvent> {
override fun handle(event: PlayerRaisedEvent) {
handleUpdatingTable(event)
handlePushNotifications(event)
handleChat(event)
}
private fun handleUpdatingTable(event: PlayerRaisedEvent) {
val tableDTO = tableRepository.fetchById(event.aggregateId)
val username = loginRepository.fetchUsernameByAggregateId(event.playerId)
val raiseToAmount = event.raiseToAmount
val updatedSeats = tableDTO.seats!!
.map {
val amountOverChipsInFront = raiseToAmount - it.chipsInFront
if (it.name == username) {
val updatedChipsInBack = it.chipsInBack - amountOverChipsInFront
it.copy(chipsInBack = updatedChipsInBack, chipsInFront = raiseToAmount,
raiseTo = 0, callAmount = 0, isActionOn = false)
} else {
it.copy(raiseTo = minOf(raiseToAmount * 2, it.chipsInFront + it.chipsInBack),
callAmount = amountOverChipsInFront)
}
}
val previousChipsInFront = tableDTO.seats.first { it.name == username }.chipsInFront
val totalPotIncrease = raiseToAmount - previousChipsInFront
val updatedTable = tableDTO.copy(version = event.version, seats = updatedSeats,
totalPot = tableDTO.totalPot + totalPotIncrease)
tableRepository.save(updatedTable)
}
private fun handlePushNotifications(event: PlayerRaisedEvent) {
val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId)
pushNotificationPublisher.publish(pushNotification)
}
private fun handleChat(event: PlayerRaisedEvent) {
val username = loginRepository.fetchUsernameByAggregateId(event.playerId)
val message = username + " raises to " + event.raiseToAmount
chatService.saveAndPushSystemTableChatMessage(event.gameId, event.aggregateId, message)
}
} | src/main/kotlin/com/flexpoker/table/query/handlers/PlayerRaisedEventHandler.kt | 3588080793 |
package net.mastrgamr.rettiwt.viewmodels
import android.databinding.ObservableField
/**
* Project: rettiwt
* Written by: mastrgamr
* Date: 6/3/17
*/
class TimelineItemViewModel {
private val TAG = javaClass.simpleName
var tweet = ObservableField<String>()
var user = ObservableField<String>()
}
| app/src/main/java/net/mastrgamr/rettiwt/viewmodels/TimelineItemViewModel.kt | 1482333051 |
package me.ccampo.nbody.model
/**
* Represents a circular moving body in 2D space.
*
* @param m The body's mass.
* @param r The body's radius.
* @param x The body's position.
* @param v The body's velocity.
* @param positions A list of the body's previous positions
*/
data class Body(val m: Double, val r: Double, val x: Vector, val v: Vector, val positions: List<Vector> = emptyList()) {
/**
* Returns true if this body has collided (occupies the same space) with another body, otherwise returns false.
*
* @param other The other body to detect collisions with.
*/
fun isCollision(other: Body) = (this.x - other.x).len < other.r && this.m <= other.m
companion object {
val empty = Body(0.0, 0.0, Vector.zero, Vector.zero)
}
}
| src/main/kotlin/me/ccampo/nbody/model/Body.kt | 533733587 |
package com.jraska.module.extract
import com.jraska.module.ArtifactDependencyType
import com.jraska.module.FileType
import com.jraska.module.FileTypeStatistics
import com.jraska.module.ModuleArtifactDependency
import com.jraska.module.ModuleMetadata
import com.jraska.module.ModuleStatistics
import com.jraska.module.ModuleType
import com.jraska.module.ProjectStatistics
import org.gradle.api.Project
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.artifacts.ResolvedDependency
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.util.LinkedList
import java.util.Queue
class StatisticsGradleExtractor {
private val typesToLookFor = arrayOf(FileType.JAVA, FileType.KOTLIN, FileType.XML)
fun extract(project: Project): ProjectStatistics {
val moduleStats = project.rootProject
.subprojects
.filter { it.childProjects.isEmpty() }
.map { extractFromModule(it) }
val externalDependencies = project.rootProject
.subprojects
.filter { it.childProjects.isEmpty() }
.flatMap { extractDependencies(it) }
return ProjectStatistics(
modulesCount = moduleStats.size,
apiModules = moduleStats.count { it.metadata.type == ModuleType.Api },
appModules = moduleStats.count { it.metadata.type == ModuleType.App },
implementationModules = moduleStats.count { it.metadata.type == ModuleType.Implementation },
moduleStatistics = moduleStats,
externalDependencies = externalDependencies,
prodKotlinTotalLines = moduleStats
.map { module -> module.containedProdFiles.single { it.type == FileType.KOTLIN }.lineCount }
.sum(),
prodJavaTotalLines = moduleStats
.map { module -> module.containedProdFiles.single { it.type == FileType.JAVA }.lineCount }
.sum(),
prodXmlTotalLines = moduleStats
.map { module -> module.containedProdFiles.single { it.type == FileType.XML }.lineCount }
.sum()
)
}
private fun extractDependencies(module: Project): List<ModuleArtifactDependency> {
val metadata = module.moduleMetadata()
return module.configurations
.filter { CONFIGURATION_TO_LOOK.containsKey(it.name) }
.flatMap { configuration ->
val projectDependencies = configuration.allDependencies.filterIsInstance(ProjectDependency::class.java)
configuration.resolvedConfiguration.firstLevelModuleDependencies
.filter { isExternalDependency(it, projectDependencies) }
.flatMap { traverseAndAddChildren(it) }
.map {
ModuleArtifactDependency(
metadata = metadata,
group = it.moduleGroup,
dependencyType = CONFIGURATION_TO_LOOK.getValue(configuration.name),
artifact = it.moduleName,
version = it.moduleVersion,
fullName = it.name
)
}
}.distinct()
}
private fun traverseAndAddChildren(firstLevelDependency: ResolvedDependency): Set<ResolvedDependency> {
val queue: Queue<ResolvedDependency> = LinkedList()
val dependencies = mutableSetOf(firstLevelDependency)
queue.offer(firstLevelDependency)
while (queue.isNotEmpty()) {
val element = queue.poll()
element.children.forEach { child ->
dependencies.add(child)
queue.offer(child)
}
}
return dependencies
}
private fun isExternalDependency(dependency: ResolvedDependency, projectDependencies: List<ProjectDependency>): Boolean {
return projectDependencies.none {
it.group == dependency.moduleGroup && it.name == dependency.moduleName
}
}
private fun extractFromModule(module: Project): ModuleStatistics {
val prodFileStats = typesToLookFor.map { getFileTypeStatistics(it, File(module.projectDir, "src/main")) }
val unitTestFileStats = typesToLookFor.map { getFileTypeStatistics(it, File(module.projectDir, "src/test")) }
val androidTestFileStats = typesToLookFor.map { getFileTypeStatistics(it, File(module.projectDir, "src/androidTest")) }
return ModuleStatistics(module.moduleMetadata(), prodFileStats, unitTestFileStats, androidTestFileStats)
}
private fun getFileTypeStatistics(type: FileType, src: File): FileTypeStatistics {
var fileCount = 0
val lineCount = src.walkBottomUp()
.filter { it.name.endsWith(type.suffix) }
.onEach { fileCount++ }
.map { countLines(it) }
.sum()
return FileTypeStatistics(lineCount, fileCount, type)
}
private fun countLines(file: File): Int {
var lines = 0
val reader = BufferedReader(FileReader(file))
reader.use {
while (it.readLine() != null) lines++
}
return lines
}
companion object {
val CONFIGURATION_TO_LOOK = mapOf(
"debugAndroidTestCompileClasspath" to ArtifactDependencyType.AndroidTest,
"debugCompileClasspath" to ArtifactDependencyType.Compile,
"releaseCompileClasspath" to ArtifactDependencyType.Compile,
"debugUnitTestCompileClasspath" to ArtifactDependencyType.Test,
"compileClasspath" to ArtifactDependencyType.Compile,
"testCompileClasspath" to ArtifactDependencyType.Test,
"kapt" to ArtifactDependencyType.Kapt
)
fun Project.moduleMetadata(): ModuleMetadata {
return ModuleMetadata(name, moduleType(this))
}
private fun moduleType(module: Project): ModuleType {
return when {
module.name.endsWith("-api") -> ModuleType.Api
module.name.startsWith("app") -> ModuleType.App
else -> ModuleType.Implementation
}
}
}
}
| plugins/src/main/java/com/jraska/module/extract/StatisticsGradleExtractor.kt | 3598972244 |
package net.nemerosa.ontrack.graphql.schema.settings
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.model.security.Roles
import net.nemerosa.ontrack.model.settings.HomePageSettings
import org.junit.Test
import kotlin.test.assertEquals
class HomePageSettingsQueryProviderGraphQLIT : AbstractQLKTITJUnit4Support() {
@Test
fun `Settings are accessible in admin mode`() {
doTestSettings { code ->
asAdmin {
code()
}
}
}
@Test
fun `Settings are accessible in read-only mode`() {
doTestSettings { code ->
withNoGrantViewToAll {
asAccountWithGlobalRole(Roles.GLOBAL_READ_ONLY) {
code()
}
}
}
}
private fun doTestSettings(
wrapper: (() -> Unit) -> Unit
) {
asAdmin {
withSettings<HomePageSettings> {
settingsManagerService.saveSettings(
HomePageSettings(
maxBranches = 20,
maxProjects = 100
)
)
wrapper {
run("""{
settings {
homePage {
maxBranches
maxProjects
}
}
}""").let { data ->
val homePage = data.path("settings").path("homePage")
assertEquals(20, homePage.path("maxBranches").asInt())
assertEquals(100, homePage.path("maxProjects").asInt())
}
}
}
}
}
} | ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/schema/settings/HomePageSettingsQueryProviderGraphQLIT.kt | 1278099935 |
package com.mycollab.module.project.service
import com.mycollab.db.arguments.BasicSearchRequest
import com.mycollab.db.arguments.NumberSearchField
import com.mycollab.db.arguments.StringSearchField
import com.mycollab.module.project.domain.criteria.ProjectRoleSearchCriteria
import com.mycollab.test.DataSet
import com.mycollab.test.rule.DbUnitInitializerRule
import com.mycollab.test.spring.IntegrationServiceTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import java.util.*
@ExtendWith(DbUnitInitializerRule::class)
class ProjectRoleServiceTest(@Autowired val projectRoleService: ProjectRoleService) : IntegrationServiceTest() {
@Test
@DataSet
fun testFindByCriteria() {
val criteria = ProjectRoleSearchCriteria()
criteria.projectId = NumberSearchField.equal(1)
criteria.saccountid = NumberSearchField.equal(1)
criteria.roleName = StringSearchField.and("role1")
val roles = projectRoleService.findPageableListByCriteria(BasicSearchRequest(criteria))
assertThat(roles.size).isEqualTo(1)
assertThat(projectRoleService.getTotalCount(criteria)).isEqualTo(1)
}
@Test
@DataSet
fun testFindRole() {
val role = projectRoleService.findById(1, 1)
assertThat(role).extracting("rolename").contains("role1")
}
@Test
@DataSet
fun testFindProjectPermissions() {
val permissions = projectRoleService.findProjectsPermissions("[email protected]", Arrays.asList(1), 1)
assertThat(permissions.size).isEqualTo(1)
assertThat(permissions[0].item1).isEqualTo(1)
}
} | mycollab-services-community/src/test/java/com/mycollab/module/project/service/ProjectRoleServiceTest.kt | 1887965642 |
package net.nemerosa.ontrack.service.support
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.common.asOptional
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.json.parseInto
import net.nemerosa.ontrack.model.support.StorageService
import net.nemerosa.ontrack.repository.StorageRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
import kotlin.reflect.KClass
@Service
@Transactional
class StorageServiceImpl(
private val repository: StorageRepository,
) : StorageService {
override fun storeJson(store: String, key: String, node: JsonNode?) {
if (node != null) {
repository.storeJson(store, key, node)
} else {
repository.delete(store, key)
}
}
override fun retrieveJson(store: String, key: String): Optional<JsonNode> =
findJson(store, key).asOptional()
override fun findJson(store: String, key: String): JsonNode? = repository.retrieveJson(store, key)
override fun getKeys(store: String): List<String> = repository.getKeys(store)
override fun getData(store: String): Map<String, JsonNode> = repository.getData(store)
override fun delete(store: String, key: String) {
repository.delete(store, key)
}
override fun clear(store: String) {
repository.clear(store)
}
override fun exists(store: String, key: String): Boolean = repository.exists(store, key)
override fun <T> findByJson(store: String, query: String, variables: Map<String, *>, type: Class<T>): List<T> {
return repository.filter(
store = store,
offset = 0,
size = Int.MAX_VALUE,
query = query,
queryVariables = variables,
).map {
JsonUtils.parse(it, type)
}
}
override fun count(store: String, context: String, query: String?, queryVariables: Map<String, *>?): Int =
repository.count(store, context, query, queryVariables)
override fun <T : Any> filter(
store: String,
type: KClass<T>,
offset: Int,
size: Int,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
): List<T> =
repository.filter(
store = store,
offset = offset,
size = size,
context = context,
query = query,
queryVariables = queryVariables,
orderQuery = orderQuery
).map {
it.parseInto(type)
}
override fun <T : Any> filterRecords(
store: String,
type: KClass<T>,
offset: Int,
size: Int,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
): Map<String, T> =
repository.filterRecords(store, offset, size, context, query, queryVariables, orderQuery)
.mapValues { (_, data) ->
data.parseInto(type)
}
override fun <T : Any> forEach(
store: String,
type: KClass<T>,
context: String,
query: String?,
queryVariables: Map<String, *>?,
orderQuery: String?,
code: (key: String, item: T) -> Unit,
) {
repository.forEach(store, context, query, queryVariables, orderQuery) { key, node ->
val item = node.parseInto(type)
code(key, item)
}
}
override fun deleteWithFilter(store: String, query: String?, queryVariables: Map<String, *>?): Int =
repository.deleteWithFilter(store, query, queryVariables)
}
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/support/StorageServiceImpl.kt | 712577945 |
/*
* Copyright (C) 2019 Johan Dykstrom
*
* 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 se.dykstrom.jcc.basic.compiler
import org.junit.Test
import se.dykstrom.jcc.basic.ast.PrintStatement
import se.dykstrom.jcc.basic.ast.SwapStatement
import se.dykstrom.jcc.common.assembly.base.Line
import se.dykstrom.jcc.common.assembly.instruction.*
import se.dykstrom.jcc.common.assembly.instruction.floating.ConvertIntRegToFloatReg
import se.dykstrom.jcc.common.assembly.instruction.floating.MoveFloatRegToMem
import se.dykstrom.jcc.common.assembly.instruction.floating.MoveMemToFloatReg
import se.dykstrom.jcc.common.assembly.instruction.floating.RoundFloatRegToIntReg
import se.dykstrom.jcc.common.assembly.other.DataDefinition
import se.dykstrom.jcc.common.ast.*
import se.dykstrom.jcc.common.types.Arr
import se.dykstrom.jcc.common.types.F64
import se.dykstrom.jcc.common.types.I64
import se.dykstrom.jcc.common.types.Str
import kotlin.test.assertEquals
/**
* Tests features related to arrays in code generation.
*
* @author Johan Dykstrom
*/
class BasicCodeGeneratorArrayTests : AbstractBasicCodeGeneratorTest() {
@Test
fun shouldDefineSimpleIntegerArray() {
// dim a%(3) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_3)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "3 dup " + I64.INSTANCE.defaultValue }
.count())
}
@Test
fun shouldDefineMultiDimensionalIntegerArray() {
// dim a%(2, 4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_2, listOf(IL_2, IL_4)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable a% should be defined and be a two-dimensional array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "8 dup " + I64.INSTANCE.defaultValue }
.count())
// There should be two dimensions
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_num_dims"))
// Of size two
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_0"))
// And four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_1"))
}
@Test
fun shouldDefineSimpleFloatArray() {
// dim d(2) as double
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_2)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable d should be defined and be an array of floats
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == F64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_F64_D.mappedName + "_arr" }
.filter { it.value() == "2 dup " + F64.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_F64_D.mappedName + "_num_dims"))
// Of size two
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_F64_D.mappedName + "_dim_0"))
}
@Test
fun shouldDefineSimpleStringArray() {
// dim s$(1) as string
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_1)))
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == Str.INSTANCE }
.filter { it.identifier().mappedName == IDENT_STR_S.mappedName + "_arr" }
.filter { it.value() == "1 dup " + Str.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_num_dims"))
// Of size one
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_dim_0"))
}
@Test
fun shouldDefineTwoArrays() {
// dim s$(1) as string
// dim a%(4, 4) as integer
val declarations = listOf(
ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_1)),
ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_2, listOf(IL_4, IL_4))
)
val statement = VariableDeclarationStatement(0, 0, declarations)
val result = assembleProgram(listOf(statement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == Str.INSTANCE }
.filter { it.identifier().mappedName == IDENT_STR_S.mappedName + "_arr" }
.filter { it.value() == "1 dup " + Str.INSTANCE.defaultValue }
.count())
// There should be one dimension
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_num_dims"))
// Of size one
assertEquals(1, getValueOfDataDefinitionAsInt(lines, IDENT_STR_S.mappedName + "_dim_0"))
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.filter { it.identifier().type() == I64.INSTANCE }
.filter { it.identifier().mappedName == IDENT_ARR_I64_A.mappedName + "_arr" }
.filter { it.value() == "16 dup " + I64.INSTANCE.defaultValue }
.count())
// There should be two dimensions
assertEquals(2, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_num_dims"))
// Of size four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_0"))
// And four
assertEquals(4, getValueOfDataDefinitionAsInt(lines, IDENT_ARR_I64_A.mappedName + "_dim_1"))
}
@Test
fun shouldAccessElementInOneDimensionalArray() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_A.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInTwoDimensionalArray() {
// dim a%(3, 2) as integer
val declarations = listOf(ArrayDeclaration(0, 0,
IDENT_ARR_I64_B.name(), Arr.from(2, I64.INSTANCE), listOf(IL_3, IL_2)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2, 0)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_B, listOf(IL_2, IL_0))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move array dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_B.mappedName + "_dim_1") })
// Multiply accumulator with dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(IMulRegWithReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_B.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInThreeDimensionalArray() {
// dim a%(4, 2, 3) as integer
val declarations = listOf(ArrayDeclaration(0, 0,
IDENT_ARR_I64_C.name(), Arr.from(3, I64.INSTANCE), listOf(IL_4, IL_2, IL_3)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2, 0, 2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_C, listOf(IL_2, IL_0, IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move array dimension 1
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_dim_1") })
// Move array dimension 2
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_dim_2") })
// Multiply accumulator with dimension 1 and 2
assertEquals(2, lines.asSequence()
.filterIsInstance(IMulRegWithReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToReg::class.java)
.count { it.source.contains(IDENT_ARR_I64_C.mappedName + "_arr") })
}
@Test
fun shouldAccessElementInFloatArray() {
// dim a%(4) as float
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(IL_2))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToFloatReg::class.java)
.count { it.source.contains(IDENT_ARR_F64_D.mappedName + "_arr") })
}
@Test
fun shouldAccessElementWithSubscriptExpression() {
// dim a%(4) as float
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// print a%(1 + 2)
val addExpression = AddExpression(0, 0, IL_1, IL_2)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(addExpression))
val printStatement = PrintStatement(0, 0, listOf(arrayAccessExpression))
val result = assembleProgram(listOf(declarationStatement, printStatement))
val lines = result.lines()
// Add registers containing 1 and 2
assertEquals(1, lines.asSequence()
.filterIsInstance(AddRegToReg::class.java)
.count())
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveMemToFloatReg::class.java)
.count { it.source.contains(IDENT_ARR_F64_D.mappedName + "_arr") })
}
@Test
fun shouldSetElementInOneDimensionalArray() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
// a%(2) = 4
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val assignStatement = AssignStatement(0, 0, arrayAccessExpression, IL_4)
val result = assembleProgram(listOf(declarationStatement, assignStatement))
val lines = result.lines()
// Move literal value subscript
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "2" })
// Move literal value to assign
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveImmToReg::class.java)
.count { it.source == "4" })
// Move array element
assertEquals(1, lines.asSequence()
.filterIsInstance(MoveRegToMem::class.java)
.count { it.destination.contains(IDENT_ARR_I64_A.mappedName + "_arr") })
}
@Test
fun shouldSwapIntegerAndArrayElement() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val swapStatement = SwapStatement(0, 0, arrayAccessExpression, NAME_H)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_ARR_I64_A.mappedName + "_arr" })
// Variable h% should be defined and be an integer
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_I64_H.mappedName })
// Moving the variable contents to registers
assertEquals(2, countInstances(MoveMemToReg::class.java, lines))
// Moving the register contents to variables
assertEquals(2, countInstances(MoveRegToMem::class.java, lines))
}
@Test
fun shouldSwapStringAndArrayElement() {
// dim a%(4) as integer
val declarations = listOf(ArrayDeclaration(0, 0, IDENT_ARR_STR_S.name(), TYPE_ARR_STR_1, listOf(IL_4)))
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val arrayAccessExpression = ArrayAccessExpression(0, 0, IDENT_ARR_STR_S, listOf(IL_2))
val swapStatement = SwapStatement(0, 0, arrayAccessExpression, NAME_B)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable s$ should be defined and be an array of strings
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == Str.INSTANCE && it.mappedName == IDENT_ARR_STR_S.mappedName + "_arr" })
// Variable b$ should be defined and be a string
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == Str.INSTANCE && it.mappedName == IDENT_STR_B.mappedName })
// Moving the variable contents (and variable type pointers) to registers
assertEquals(4, countInstances(MoveMemToReg::class.java, lines))
// Moving the register contents to variables (and variable type pointers)
assertEquals(4, countInstances(MoveRegToMem::class.java, lines))
}
@Test
fun shouldSwapIntegerArrayElementAndFloatArrayElement() {
// dim a%(4) as integer
// dim d#(2) as double
val declarations = listOf(
ArrayDeclaration(0, 0, IDENT_ARR_I64_A.name(), TYPE_ARR_I64_1, listOf(IL_4)),
ArrayDeclaration(0, 0, IDENT_ARR_F64_D.name(), TYPE_ARR_F64_1, listOf(IL_2))
)
val declarationStatement = VariableDeclarationStatement(0, 0, declarations)
val integerArrayAccess = ArrayAccessExpression(0, 0, IDENT_ARR_I64_A, listOf(IL_2))
val floatArrayAccess = ArrayAccessExpression(0, 0, IDENT_ARR_F64_D, listOf(IL_0))
val swapStatement = SwapStatement(0, 0, integerArrayAccess, floatArrayAccess)
val result = assembleProgram(listOf(declarationStatement, swapStatement))
val lines = result.lines()
// Variable a% should be defined and be an array of integers
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == I64.INSTANCE && it.mappedName == IDENT_ARR_I64_A.mappedName + "_arr" })
// Variable d# should be defined and be an array of floats
assertEquals(1, lines.asSequence()
.filterIsInstance<DataDefinition>()
.map { it.identifier() }
.count { it.type() == F64.INSTANCE && it.mappedName == IDENT_ARR_F64_D.mappedName + "_arr" })
// Move contents of integer array element to register
assertEquals(1, countInstances(MoveMemToReg::class.java, lines))
// Move register contents to integer array element
assertEquals(1, countInstances(MoveRegToMem::class.java, lines))
// Move contents of float array element to register
assertEquals(1, countInstances(MoveMemToFloatReg::class.java, lines))
// Move register contents to float array element
assertEquals(1, countInstances(MoveFloatRegToMem::class.java, lines))
// Convert integer to float
assertEquals(1, countInstances(ConvertIntRegToFloatReg::class.java, lines))
// Convert float to integer
assertEquals(1, countInstances(RoundFloatRegToIntReg::class.java, lines))
}
/**
* Extracts the value of the data definition with the given mapped name as an Int.
* This method expects to find exactly one such data definition, and that the value
* is actually an integer.
*/
private fun getValueOfDataDefinitionAsInt(lines: List<Line>, mappedName: String): Int {
val values = lines
.filterIsInstance<DataDefinition>()
.filter { it.identifier().mappedName == mappedName }
.map { it.value().toInt() }
assertEquals(1, values.size)
return values.first()
}
}
| src/test/kotlin/se/dykstrom/jcc/basic/compiler/BasicCodeGeneratorArrayTests.kt | 3544037204 |
package net.nemerosa.ontrack.extension.jenkins.client
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.nemerosa.ontrack.common.untilTimeout
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.RestTemplate
import java.net.URI
import java.time.Duration
class DefaultJenkinsClient(
private val url: String,
private val client: RestTemplate,
) : JenkinsClient {
private val logger: Logger = LoggerFactory.getLogger(DefaultJenkinsClient::class.java)
private val crumbs: JenkinsCrumbs by lazy {
runBlocking {
untilTimeout("Getting Jenkins authentication crumbs") {
client.getForObject("/crumbIssuer/api/json", JenkinsCrumbs::class.java)
}
}
}
override fun getJob(job: String): JenkinsJob {
val jobPath = getJobPath(job)
val jobUrl = "$url$jobPath"
val jobName = jobPath.substringAfterLast("/")
return JenkinsJob(
jobName,
jobUrl
)
}
override val info: JenkinsInfo
get() =
client.getForObject("/api/json", JenkinsInfo::class.java) ?: error("Cannot get Jenkins info")
override fun runJob(
job: String,
parameters: Map<String, String>,
retries: Int,
retriesDelaySeconds: Int,
): JenkinsBuild {
val retriesDelay = Duration.ofSeconds(retriesDelaySeconds.toLong())
val path = getJobPath(job)
logger.debug("run,job=$job,path=$path,parameters=$parameters")
return runBlocking {
// Query
val map = LinkedMultiValueMap<String, Any>()
parameters.forEach { (key, value) ->
map.add(key, value)
}
// Headers (form)
val headers = createCSRFHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA
// Request to send
val requestEntity = HttpEntity(map, headers)
// Launches the job with parameters and get the queue item
val queueItemURI: URI? = withContext(Dispatchers.IO) {
client.postForLocation(
"$path/buildWithParameters",
requestEntity
)
}
if (queueItemURI == null) {
error("Cannot fire job $path")
} else {
// We must now monitor the state of the queue item
// Until `cancelled` is true, or `executable` contains a valid link
val executable: JenkinsBuildId =
untilTimeout("Waiting for $queueItemURI to be scheduled", retries, retriesDelay) {
logger.debug("queued=$queueItemURI,job=$job,path=$path,parameters=$parameters")
getQueueStatus(queueItemURI)
}
// Waits for its completion
untilTimeout("Waiting for build completion at ${executable.url(path)}", retries, retriesDelay) {
logger.debug("build=${executable.number},job=$job,path=$path,parameters=$parameters")
getBuildStatus(path, executable)
}
}
}
}
private fun getJobPath(job: String): String {
val path = job.replace("/job/".toRegex(), "/").replace("/".toRegex(), "/job/")
return "/job/$path"
}
private fun createCSRFHeaders(): HttpHeaders {
val headers = HttpHeaders()
headers.add(crumbs.crumbRequestField, crumbs.crumb)
return headers
}
private fun getQueueStatus(queueItemURI: URI): JenkinsBuildId? {
val queueItem: JenkinsQueueItem? = client.getForObject("$queueItemURI/api/json", JenkinsQueueItem::class.java)
return if (queueItem != null) {
when {
queueItem.cancelled != null && queueItem.cancelled -> throw JenkinsJobCancelledException(queueItemURI.toString())
queueItem.executable != null -> queueItem.executable
else -> null
}
} else {
null
}
}
private fun getBuildStatus(job: String, buildId: JenkinsBuildId): JenkinsBuild? {
val buildInfoUrl = "${buildId.url(job)}/api/json"
val build: JenkinsBuild? = client.getForObject(buildInfoUrl, JenkinsBuild::class.java)
return build?.takeIf { !build.building }
}
} | ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/client/DefaultJenkinsClient.kt | 1013869325 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.reference
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.AT
import com.demonwav.mcdev.util.insideAnnotationAttribute
import com.intellij.patterns.PsiJavaPatterns
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.PsiReferenceContributor
import com.intellij.psi.PsiReferenceRegistrar
class MixinReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
// Method references
registrar.registerReferenceProvider(
MethodReference.ELEMENT_PATTERN,
MethodReference
)
// Desc references
registrar.registerReferenceProvider(
DescReference.ELEMENT_PATTERN,
DescReference
)
// Injection point types
registrar.registerReferenceProvider(
PsiJavaPatterns.psiLiteral(StandardPatterns.string())
.insideAnnotationAttribute(AT),
InjectionPointReference
)
// Target references
registrar.registerReferenceProvider(
TargetReference.ELEMENT_PATTERN,
TargetReference
)
}
}
| src/main/kotlin/platform/mixin/reference/MixinReferenceContributor.kt | 2085874393 |
package com.groupdocs.ui.modules.upload
import com.groupdocs.ui.config.ApplicationConfig
import com.groupdocs.ui.model.ConfigResponse
import com.groupdocs.ui.util.InternalServerException
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.Produces
import io.micronaut.http.multipart.CompletedFileUpload
import jakarta.inject.Inject
import jakarta.inject.Singleton
import kotlinx.coroutines.runBlocking
import java.io.BufferedInputStream
@Singleton
@Controller("/comparison")
class UploadController(
@Inject private val uploadBean: UploadBean,
@Inject private val appConfig: ApplicationConfig
) {
@Post("/uploadDocument", consumes = [MediaType.MULTIPART_FORM_DATA])
@Produces(MediaType.APPLICATION_JSON)
fun comparer(rewrite: Boolean, file: CompletedFileUpload?, url: String?): HttpResponse<*> {
val isUploadEnabled = appConfig.common.upload
if (!isUploadEnabled) {
throw InternalServerException("Files uploading is disabled!")
}
val response = runBlocking {
if (url == null) {
file?.let { uploadedFile ->
BufferedInputStream(uploadedFile.inputStream).use { inputStream ->
return@let uploadBean.uploadDisk(uploadedFile.filename, inputStream)
}
} ?: throw InternalServerException("Incorrect request!")
} else {
uploadBean.uploadUrl(url)
}
}
return HttpResponse.ok<ConfigResponse>().body(response)
}
} | Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/modules/upload/UploadController.kt | 173816671 |
package com.hewking.custom
import android.content.Context
import androidx.core.view.GestureDetectorCompat
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.OverScroller
/**
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/6/25
* 修改人员:hewking
* 修改时间:2018/6/25
* 修改备注:
* Version: 1.0.0
*/
class LagouHomePanelLayout(ctx: Context, attrs: AttributeSet) : ViewGroup(ctx, attrs) {
private val TAG = "LagouHomePanelLayout"
private var mTopView: View? = null
private var mContentView: View? = null
private var mTopHeight = 0
private var parallRate = 0.6f
private var mCurOffset = 0f
private val mScroller : OverScroller by lazy {
OverScroller(ctx)
}
private fun ensureTargetView() {
if (childCount > 1) {
if (mTopView == null) {
mTopView = getChildAt(0)
}
if (mContentView == null) {
mContentView = getChildAt(1)
}
} else {
throw IllegalArgumentException("must have two child view!!")
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
ensureTargetView()
measureChildren(widthMeasureSpec, heightMeasureSpec)
mTopHeight = mTopView?.measuredHeight?:0
val height = (mTopView?.measuredHeight ?: 0) + (mContentView?.measuredHeight!! ?: 0)
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY))
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
ensureTargetView()
mTopView?.layout(l,t,r,t + mTopHeight)
mContentView?.layout(l,t + mTopHeight,r,mTopHeight + mContentView?.measuredHeight!!)
}
private val mGestenerDetector : GestureDetectorCompat = GestureDetectorCompat(context,object : GestureDetector.SimpleOnGestureListener() {
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
Log.i(TAG,"e1 y : ${e1?.y} e2 y : ${e2?.y} distanceY : ${distanceY}")
refreshLayout(distanceY)
postInvalidate()
return true
}
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
mScroller.fling(0,mCurOffset.toInt(),0,velocityY.toInt() / 2,0,0,-mTopHeight,0)
postInvalidate()
return true
}
})
private fun refreshLayout(distanceY: Float) {
val offset = mCurOffset - distanceY
if (offset != mCurOffset) {
mCurOffset = offset
val l = mTopView?.left?:0
val t = mTopView?.top?:0
val r = mTopView?.right?:0
// mCurOffset 上限 -mTopHeight 下限 0
val offsetLimit = Math.min(0,Math.max(mCurOffset?.toInt(),-mTopHeight))
val topLimit = mTopHeight + offsetLimit?.toInt()?:0
val topT = (parallRate * offsetLimit).toInt()
mTopView?.layout(l,topT,r,topT + mTopHeight)
mContentView?.layout(l,topLimit,r,topLimit + mTopHeight + mContentView?.measuredHeight!!)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
// 需要拦截的时候返回 true
ev?:return false
if (mCurOffset <= - mTopHeight && ev.actionMasked != MotionEvent.ACTION_DOWN) {
// val downEv = MotionEvent.obtain(ev)
// downEv.action = MotionEvent.ACTION_DOWN
// mContentView?.onTouchEvent(downEv)
return false
}
return mGestenerDetector.onTouchEvent(ev)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
mGestenerDetector.onTouchEvent(event)
return true
}
/**
* 动态展开
*/
fun expand(){
mScroller.startScroll(0,0,0,mTopHeight)
invalidate()
}
/**
* 折叠起来
*/
fun collapsing(){
mScroller.startScroll(0,mCurOffset?.toInt(),0,-mTopHeight)
invalidate()
}
private var lastScrollY = -1f
override fun computeScroll() {
if (mScroller.computeScrollOffset()) {
var dy = mScroller.currY?.toFloat() - lastScrollY
if (lastScrollY == -1f) {
dy = 0f
}
lastScrollY = mScroller.currY?.toFloat()
Log.i(TAG,"computeScroll currY : ${mScroller.currY?.toFloat()} dy : $dy")
refreshLayout(-dy)
postInvalidate()
}
}
} | app/src/main/java/com/hewking/custom/LagouHomePanelLayout.kt | 2973613124 |
/*
* Copyright 2013 Maurício Linhares
*
* 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.util
data class Version(val major: Int, val minor: Int, val maintenance: Int) : Comparable<Version> {
companion object {
private fun tryParse(index: Int, pieces: Array<String>): Int =
try {
pieces[index].toInt()
} catch(e: Throwable) {
0
}
}
constructor(pieces: Array<String>) :
this(tryParse(0, pieces), tryParse(1, pieces), tryParse(2, pieces))
constructor(version: String) : this(version.split('.').toTypedArray())
override fun compareTo(other: Version): Int {
if (this.major != other.major) {
return this.major - other.major
}
if (this.minor != other.minor) {
return this.minor - other.minor
}
return this.maintenance - other.maintenance
}
}
| db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/Version.kt | 516084008 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.liteloader.framework
import com.demonwav.mcdev.util.libraryKind
import com.intellij.openapi.roots.libraries.LibraryKind
val LITELOADER_LIBRARY_KIND: LibraryKind = libraryKind("liteloader-library")
| src/main/kotlin/platform/liteloader/framework/LiteLoaderLibraryKind.kt | 4026178283 |
package yuku.alkitab.datatransfer.process
import java.util.Date
import kotlinx.serialization.decodeFromString
import yuku.alkitab.base.util.History
import yuku.alkitab.base.util.Sqlitil
import yuku.alkitab.datatransfer.model.Gid
import yuku.alkitab.datatransfer.model.HistoryEntity
import yuku.alkitab.datatransfer.model.LabelEntity
import yuku.alkitab.datatransfer.model.MabelEntity
import yuku.alkitab.datatransfer.model.MarkerEntity
import yuku.alkitab.datatransfer.model.MarkerLabelEntity
import yuku.alkitab.datatransfer.model.Pin
import yuku.alkitab.datatransfer.model.PinsEntity
import yuku.alkitab.datatransfer.model.Root
import yuku.alkitab.datatransfer.model.Rpp
import yuku.alkitab.datatransfer.model.RppEntity
import yuku.alkitab.datatransfer.model.Snapshot
import yuku.alkitab.model.Label
import yuku.alkitab.model.Marker
import yuku.alkitab.model.Marker_Label
import yuku.alkitab.model.ProgressMark
class ImportProcess(
private val storage: ReadWriteStorageInterface,
private val log: LogInterface,
) {
data class Options(
val importHistory: Boolean,
val importMabel: Boolean,
val importPins: Boolean,
val importRpp: Boolean,
val actualRun: Boolean,
)
fun import(json: String, options: Options) {
log.log("Decoding from JSON")
val root = Serializer.importJson.decodeFromString<Root>(json)
log.log("JSON was read successfully")
if (options.actualRun) {
log.log("Proceeding with actual import unless error happens")
} else {
log.log("Simulating import")
}
storage.transact { handle ->
if (options.importHistory) {
history(root.snapshots.history)
}
if (options.importMabel) {
mabel(root.snapshots.mabel)
}
if (options.importPins) {
pins(root.snapshots.pins)
}
if (options.importRpp) {
rpp(root.snapshots.rp)
}
if (options.actualRun) {
log.log("Everything works without error, committing the change")
handle.commit()
}
}
log.log("All succeeded")
}
/**
* For history, there is no merging done locally, local will be replaced completely.
*/
private fun history(history: Snapshot<HistoryEntity>) {
val logger = log.logger("History")
val old = storage.history()
val new = history.entities.map { entity ->
History.Entry(entity.gid, entity.content.ari, entity.content.timestamp, entity.creator_id)
}
logger("${old.size} entries will be replaced by incoming ${new.size} entries")
storage.replaceHistory(new)
logger("replace succeeded")
}
/**
* For mabel, if the gid matches, they will be replaced. Otherwise, inserted.
*/
private fun mabel(mabel: Snapshot<MabelEntity>) {
val logger = log.logger("Markers and labels")
val oldMarkers = storage.markers()
val oldLabels = storage.labels()
val oldMarkerLabels = storage.markerLabels()
logger("there are currently ${oldMarkers.size} markers")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.bookmark }} bookmarks")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.note }} notes")
logger("- ${oldMarkers.count { it.kind == Marker.Kind.highlight }} highlights")
logger("there are currently ${oldLabels.size} labels")
val markerGids = oldMarkers.associateBy { it.gid }
val labelGids = oldLabels.associateBy { it.gid }
val markerLabelGids = oldMarkerLabels.associateBy { it.gid }
// do the counting first
logger("incoming markers will replace ${
mabel.entities.count { it is MarkerEntity && markerGids.containsKey(it.gid) }
} existing ones")
logger("incoming labels will replace ${
mabel.entities.count { it is LabelEntity && labelGids.containsKey(it.gid) }
} existing ones")
var markerNewCount = 0
var markerEditCount = 0
var labelNewCount = 0
var labelEditCount = 0
var markerLabelNewCount = 0
var markerLabelEditCount = 0
for (entity in mabel.entities) {
when (entity) {
is MarkerEntity -> {
val oldMarker = markerGids[entity.gid]
if (oldMarker == null) markerNewCount++ else markerEditCount++
val newMarker = (oldMarker ?: Marker.createEmptyMarker()).apply {
// _id will be nonzero if oldMarker is non-null
gid = entity.gid
ari = entity.content.ari
kind = Marker.Kind.fromCode(entity.content.kind)
caption = entity.content.caption
verseCount = entity.content.verseCount
createTime = Sqlitil.toDate(entity.content.createTime)
modifyTime = Sqlitil.toDate(entity.content.modifyTime)
}
storage.replaceMarker(newMarker)
}
is LabelEntity -> {
val oldLabel = labelGids[entity.gid]
if (oldLabel == null) labelNewCount++ else labelEditCount++
val newLabel = (oldLabel ?: Label.createEmptyLabel()).apply {
// _id will be nonzero if oldLabel is non-null
gid = entity.gid
title = entity.content.title
ordering = entity.content.ordering
backgroundColor = entity.content.backgroundColor
}
storage.replaceLabel(newLabel)
}
is MarkerLabelEntity -> {
// check validity of marker gid and label gid
val oldMarkerLabel = markerLabelGids[entity.gid]
if (oldMarkerLabel == null) markerLabelNewCount++ else markerLabelEditCount++
val newMarkerLabel = (oldMarkerLabel ?: Marker_Label.createEmptyMarker_Label()).apply {
// _id will be nonzero if oldMarkerLabel is non-null
gid = entity.gid
marker_gid = entity.content.marker_gid
label_gid = entity.content.label_gid
}
storage.replaceMarkerLabel(newMarkerLabel)
}
}
}
logger("added $markerNewCount markers, edited existing $markerEditCount markers")
logger("added $labelNewCount labels, edited existing $labelEditCount labels")
logger("added $markerLabelNewCount label-assignments, edited existing $markerLabelEditCount label-assignments")
}
private fun pins(pins: Snapshot<PinsEntity>) {
val logger = log.logger("Pins")
val old = storage.pins()
val new = pins.entities.firstOrNull()?.content?.pins.orEmpty()
logger("there are currently ${old.size} pins, incoming ${new.size} pins")
fun ProgressMark.display(): String {
val caption = caption
return if (caption == null) "Pin ${preset_id + 1}" else "Pin ${preset_id + 1} ($caption)"
}
fun Pin.display(): String {
val caption = caption
return if (caption == null) "Pin ${preset_id + 1}" else "Pin ${preset_id + 1} ($caption)"
}
for (newPin in new) {
val oldPin = old.find { it.preset_id == newPin.preset_id }
if (oldPin != null) {
logger("current ${oldPin.display()} will be replaced by an incoming ${newPin.display()}")
}
storage.replacePin(newPin)
logger("replace pin ${newPin.preset_id + 1} succeeded")
}
}
private fun rpp(rpp: Snapshot<RppEntity>) {
val logger = log.logger("Reading plan progress")
val old = storage.rpps()
val new = rpp.entities.map { entity ->
Rpp(Gid(entity.gid), entity.content.startTime, entity.content.done.toList())
}
logger("there are currently ${old.size} progresses, incoming ${new.size} progresses")
for (newRpp in new) {
val oldRpp = old.find { it.gid == newRpp.gid }
if (oldRpp != null) {
logger("current progress ${oldRpp.gid} will be replaced by an incoming progress")
}
storage.replaceRpp(newRpp)
logger("replace progress ${newRpp.gid} succeeded")
}
}
}
| Alkitab/src/main/java/yuku/alkitab/datatransfer/process/ImportProcess.kt | 1336763042 |
package com.dewarder.akommons.binding.string
import android.content.Context
import android.view.View
import com.dewarder.akommons.binding.string
import com.dewarder.akommons.binding.stringOptional
import com.dewarder.akommons.binding.strings
import com.dewarder.akommons.binding.stringsOptional
import com.dewarder.akommons.binding.common.NO_STRING1
import com.dewarder.akommons.binding.common.NO_STRING2
import com.dewarder.akommons.binding.common.string.TestableString
import com.dewarder.akommons.binding.common.R
class TestStringView(context: Context) : View(context), TestableString {
override val stringRequiredExist by string(R.string.test_string1)
override val stringRequiredAbsent by string(NO_STRING1)
override val stringOptionalExist by stringOptional(R.string.test_string1)
override val stringOptionalAbsent by stringOptional(NO_STRING1)
override val stringsRequiredExist by strings(R.string.test_string1, R.string.test_string2)
override val stringsRequiredAbsent by strings(NO_STRING1, NO_STRING2)
override val stringsOptionalExist by stringsOptional(R.string.test_string1, R.string.test_string2)
override val stringsOptionalAbsent by stringsOptional(NO_STRING1, NO_STRING2)
override val stringsRequiredFirstExistSecondAbsent by strings(R.string.test_string1, NO_STRING1)
override val stringsOptionalFirstExistSecondAbsent by stringsOptional(R.string.test_string1, NO_STRING1)
} | akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/string/TestStringView.kt | 4268043187 |
package com.dewarder.akommons.binding.common.integer
interface TestableInteger {
val integerRequiredExist: Int
val integerRequiredAbsent: Int
val integerOptionalExist: Int?
val integerOptionalAbsent: Int?
val integersRequiredExist: List<Int>
val integersRequiredAbsent: List<Int>
val integersOptionalExist: List<Int?>
val integersOptionalAbsent: List<Int?>
val integersRequiredFirstExistSecondAbsent: List<Int>
val integersOptionalFirstExistSecondAbsent: List<Int?>
} | akommons-bindings-common-test/src/main/java/com/dewarder/akommons/binding/common/integer/TestableInteger.kt | 2184711179 |
package com.emogoth.android.phone.mimi.db.models
import androidx.room.*
import com.emogoth.android.phone.mimi.db.MimiDatabase
import com.mimireader.chanlib.interfaces.PostConverter
import com.mimireader.chanlib.models.ChanPost
@Entity(tableName = MimiDatabase.POSTS_TABLE,
indices = [Index(Post.ID, unique = true), Index(Post.POST_ID), Index(Post.THREAD_ID), Index(Post.BOARD_NAME)])
class Post() : PostConverter {
constructor(boardName: String, threadId: Long, other: ChanPost): this() {
this.boardName = boardName
this.threadId = threadId
postId = other.no
closed = if (other.isClosed) 1 else 0
sticky = if (other.isSticky) 1 else 0
readableTime = other.now
author = other.name
comment = other.com
subject = other.sub
oldFilename = other.filename
newFilename = other.tim
fileExt = other.ext
fileWidth = other.width
fileHeight = other.height
thumbnailWidth = other.thumbnailWidth
thumbnailHeight = other.thumbnailHeight
epoch = other.time
md5 = other.md5
fileSize = other.fsize
resto = other.resto
bumplimit = other.bumplimit
imagelimit = other.imagelimit
semanticUrl = other.semanticUrl
replyCount = other.replies
imageCount = other.images
omittedPosts = other.omittedPosts
omittedImages = other.omittedImages
email = other.email
tripcode = other.trip
authorId = other.id
capcode = other.capcode
country = other.country
countryName = other.countryName
trollCountry = other.trollCountry
spoiler = other.spoiler
customSpoiler = other.customSpoiler
}
companion object {
const val ID = "id"
const val THREAD_ID = "thread_id"
const val BOARD_NAME = "board_name"
const val POST_ID = "post_id"
const val CLOSED = "closed"
const val STICKY = "sticky"
const val READABLE_TIME = "readable_time"
const val AUTHOR = "author"
const val COMMENT = "comment"
const val SUBJECT = "subject"
const val OLD_FILENAME = "old_filename"
const val NEW_FILENAME = "new_filename"
const val FILE_SIZE = "file_size"
const val FILE_EXT = "file_ext"
const val FILE_WIDTH = "file_width"
const val FILE_HEIGHT = "file_height"
const val THUMB_WIDTH = "thumb_width"
const val THUMB_HEIGHT = "thumb_height"
const val EPOCH = "epoch"
const val MD5 = "md5"
const val RESTO = "resto"
const val BUMP_LIMIT = "bump_limit"
const val IMAGE_LIMIT = "image_limit"
const val SEMANTIC_URL = "semantic_url"
const val REPLY_COUNT = "reply_count"
const val IMAGE_COUNT = "image_count"
const val OMITTED_POSTS = "omitted_posts"
const val OMITTED_IMAGE = "omitted_image"
const val EMAIL = "email"
const val TRIPCODE = "tripcode"
const val AUTHOR_ID = "author_id"
const val CAPCODE = "capcode"
const val COUNTRY = "country"
const val COUNTRY_NAME = "country_name"
const val TROLL_COUNTRY = "troll_country"
const val SPOILER = "spoiler"
const val CUSTOM_SPOILER = "custom_spoiler"
}
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ID)
var id: Int? = null
@ColumnInfo(name = THREAD_ID)
var threadId: Long = 0L
@ColumnInfo(name = BOARD_NAME)
var boardName: String = ""
@ColumnInfo(name = POST_ID)
var postId: Long = 0
@ColumnInfo(name = CLOSED)
var closed: Int = 0
@ColumnInfo(name = STICKY)
var sticky: Int = 0
@ColumnInfo(name = READABLE_TIME)
var readableTime: String? = null
@ColumnInfo(name = AUTHOR)
var author: String? = null
@ColumnInfo(name = COMMENT)
var comment: String? = null
@ColumnInfo(name = SUBJECT)
var subject: String? = null
@ColumnInfo(name = OLD_FILENAME)
var oldFilename: String? = null
@ColumnInfo(name = NEW_FILENAME)
var newFilename: String? = null
@ColumnInfo(name = FILE_EXT)
var fileExt: String? = null
@ColumnInfo(name = FILE_WIDTH)
var fileWidth: Int = 0
@ColumnInfo(name = FILE_HEIGHT)
var fileHeight: Int = 0
@ColumnInfo(name = THUMB_WIDTH)
var thumbnailWidth: Int = 0
@ColumnInfo(name = THUMB_HEIGHT)
var thumbnailHeight: Int = 0
@ColumnInfo(name = EPOCH)
var epoch: Long = 0
@ColumnInfo(name = MD5)
var md5: String? = null
@ColumnInfo(name = FILE_SIZE)
var fileSize: Int = 0
@ColumnInfo(name = RESTO)
var resto: Int = 0
@ColumnInfo(name = BUMP_LIMIT)
var bumplimit: Int = 0
@ColumnInfo(name = IMAGE_LIMIT)
var imagelimit: Int = 0
@ColumnInfo(name = SEMANTIC_URL)
var semanticUrl: String? = null
@ColumnInfo(name = REPLY_COUNT)
var replyCount: Int = 0
@ColumnInfo(name = IMAGE_COUNT)
var imageCount: Int = 0
@ColumnInfo(name = OMITTED_POSTS)
var omittedPosts: Int = 0
@ColumnInfo(name = OMITTED_IMAGE)
var omittedImages: Int = 0
@ColumnInfo(name = EMAIL)
var email: String? = null
@ColumnInfo(name = TRIPCODE)
var tripcode: String? = null
@ColumnInfo(name = AUTHOR_ID)
var authorId: String? = null
@ColumnInfo(name = CAPCODE)
var capcode: String? = null
@ColumnInfo(name = COUNTRY)
var country: String? = null
@ColumnInfo(name = COUNTRY_NAME)
var countryName: String? = null
@ColumnInfo(name = TROLL_COUNTRY)
var trollCountry: String? = null
@ColumnInfo(name = SPOILER)
var spoiler: Int = 0
@ColumnInfo(name = CUSTOM_SPOILER)
var customSpoiler: Int = 0
override fun toPost(): ChanPost {
val post = ChanPost()
post.no = postId
post.isClosed = closed == 1
post.isSticky = sticky == 1
post.bumplimit = bumplimit
post.com = comment
post.sub = subject
post.name = author
post.ext = fileExt
post.filename = oldFilename
post.fsize = fileSize
post.height = fileHeight
post.width = fileWidth
post.thumbnailHeight = thumbnailHeight
post.thumbnailWidth = thumbnailWidth
post.imagelimit = imagelimit
post.images = imageCount
post.replies = replyCount
post.resto = resto
post.omittedImages = omittedImages
post.omittedPosts = omittedPosts
post.semanticUrl = semanticUrl
post.md5 = md5
post.tim = newFilename
post.time = epoch
post.email = email
post.trip = tripcode
post.id = authorId
post.capcode = capcode
post.country = country
post.countryName = countryName
post.trollCountry = trollCountry
post.spoiler = spoiler
post.customSpoiler = customSpoiler
return post
}
} | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/models/Post.kt | 1076657714 |
/*
* Copyright (c) 2017 Michał Bączkowski
*
* 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.github.mibac138.argparser.parser
import com.github.mibac138.argparser.syntax.SyntaxElement
interface SyntaxLinkedMap<K, out V> : Map<K, V> {
val syntaxToValueMap: Map<SyntaxElement, V>
}
// Used to remove ambiguity when using generics
// (this is considered better than explicit casting)
val <K, V> SyntaxLinkedMap<K, V>.keyToValueMap: Map<K, V>
get() = this
@Suppress("FunctionName")
fun <K, V> SyntaxLinkedMap(keyToValueMap: Map<K, V>, syntaxToValueMap: Map<SyntaxElement, V>): SyntaxLinkedMap<K, V>
= SyntaxLinkedMapImpl(keyToValueMap, syntaxToValueMap)
private data class SyntaxLinkedMapImpl<K, out V>(
private val keyToValueMap: Map<K, V>,
override val syntaxToValueMap: Map<SyntaxElement, V>
) : SyntaxLinkedMap<K, V>, Map<K, V> by keyToValueMap
| core/src/main/kotlin/com/github/mibac138/argparser/parser/SyntaxLinkedMap.kt | 1981093734 |
package com.ztiany.acc.live
import com.trello.rxlifecycle2.components.support.RxFragment
/**
*
*@author Ztiany
* Email: [email protected]
* Date : 2018-04-28 16:27
*/
class LiveDataFragment : RxFragment() {
} | Android/AAC-Sample/Paging-Sample/src/main/java/com/ztiany/acc/live/LiveDataFragment.kt | 2218025452 |
/*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2015-Present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.xmpp.jingle
import org.jitsi.jicofo.metrics.JicofoMetricsContainer
import org.jitsi.metrics.CounterMetric
import org.jitsi.xmpp.extensions.jingle.JingleAction
import org.json.simple.JSONObject
import java.util.concurrent.ConcurrentHashMap
class JingleStats {
companion object {
private val stanzasReceivedByAction: MutableMap<JingleAction, CounterMetric> = ConcurrentHashMap()
private val stanzasSentByAction: MutableMap<JingleAction, CounterMetric> = ConcurrentHashMap()
@JvmStatic
fun stanzaReceived(action: JingleAction) {
stanzasReceivedByAction.computeIfAbsent(action) {
JicofoMetricsContainer.instance.registerCounter(
"jingle_${action.name.lowercase()}_received",
"Number of ${action.name} stanzas received"
)
}.inc()
}
@JvmStatic
fun stanzaSent(action: JingleAction) {
stanzasSentByAction.computeIfAbsent(action) {
JicofoMetricsContainer.instance.registerCounter(
"jingle_${action.name.lowercase()}_sent",
"Number of ${action.name} stanzas sent."
)
}.inc()
}
@JvmStatic
fun toJson() = JSONObject().apply {
this["sent"] = stanzasSentByAction.map { it.key to it.value.get() }.toMap()
this["received"] = stanzasReceivedByAction.map { it.key to it.value.get() }.toMap()
}
}
}
| jicofo-common/src/main/kotlin/org/jitsi/jicofo/xmpp/jingle/JingleStats.kt | 3230774953 |
package org.abendigo.plugin.csgo
import org.abendigo.DEBUG
import org.abendigo.csgo.Engine.clientState
import org.abendigo.csgo.Me
import org.abendigo.csgo.Vector
import org.abendigo.csgo.normalizeAngle
import org.abendigo.util.randomFloat
import org.jire.arrowhead.keyReleased
object RCSPlugin : InGamePlugin("RCS", duration = 32) {
// 0F = no correction, 2F = 100% correction
private const val RANDOM_MIN = 1.86F
private const val RANDOM_MAX = 1.97F
private var prevFired = 0
private val lastPunch = FloatArray(2)
override fun cycle() {
val shotsFired = +Me().shotsFired
val weapon = +Me().weapon
try {
if (!weapon.type!!.automatic) {
reset()
return
}
} catch (t: Throwable) {
if (DEBUG) t.printStackTrace()
}
val bulletsLeft = +weapon.bullets
if (shotsFired <= 2 || shotsFired < prevFired || bulletsLeft <= 0 || +Me().dead) {
if (keyReleased(1)) { // prevent aim flick down cheaphax
reset()
return
}
}
val punch = +Me().punch
punch.x *= randomFloat(RANDOM_MIN, RANDOM_MAX)
punch.y *= randomFloat(RANDOM_MIN, RANDOM_MAX)
punch.z = 0F
normalizeAngle(punch)
var view = clientState(1024).angle()
if (view.x == 0F || view.y == 0F || view.z == 0F) view = clientState(1024).angle()
val newView = Vector(punch.x, punch.y, punch.z)
newView.x -= lastPunch[0]
newView.y -= lastPunch[1]
newView.z = 0F
normalizeAngle(newView)
view.x -= newView.x
view.y -= newView.y
view.z = 0F
normalizeAngle(view)
clientState(1024).angle(view)
lastPunch[0] = punch.x
lastPunch[1] = punch.y
prevFired = shotsFired
}
private fun reset() {
prevFired = 0
lastPunch[0] = 0F
lastPunch[1] = 0F
}
override fun disable() {
reset()
}
} | src/main/kotlin/org/abendigo/plugin/csgo/RCSPlugin.kt | 2139845296 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package /*jvm*/x.katydid.events.types
import o.katydid.events.types.KatydidFocusEvent
import x.katydid.events.domevents.FocusEvent
//---------------------------------------------------------------------------------------------------------------------
class KatydidFocusEventImpl(
private val event: FocusEvent
) : KatydidUiEventImpl(event), KatydidFocusEvent {
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-Events-JVM/src/main/kotlin/x/katydid/events/types/KatydidFocusEventImpl.kt | 1513030634 |
package com.github.ivan_osipov.clabo.api.model
import com.github.ivan_osipov.clabo.utils.ChatId
interface HasReplyMarkup<out T : ReplyMarkup> {
val chatId: ChatId?
val replyMarkup: T?
} | src/main/kotlin/com/github/ivan_osipov/clabo/api/model/HasReplyMarkup.kt | 2144747321 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 bbqapp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.bbqaap.android.extension
import android.location.Address
import android.location.Location
import org.bbqapp.android.extension.getLatLng
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.bbqapp.android.api.model.Location as ApiLocation
class LocationUtilsTest {
@Test fun testLocationToLatLng() {
val location = mock(Location::class.java)
`when`(location.latitude).thenReturn(12.65)
`when`(location.longitude).thenReturn(98.12)
val latLng = location.getLatLng()
assertEquals(latLng.latitude, 12.65, 0.001)
assertEquals(latLng.longitude, 98.12, 0.001)
}
@Test fun testApiLocationToLatLng() {
var location = ApiLocation(listOf(95.23, 12.54), "Point")
var latLng = location.getLatLng()
assertEquals(latLng.latitude, 12.54, 0.001)
assertEquals(latLng.longitude, 95.23, 0.001)
}
@Test fun testAddressToLatLng() {
var address = mock(Address::class.java)
`when`(address.latitude).thenReturn(14.98)
`when`(address.longitude).thenReturn(89.21)
var latLng = address.getLatLng()
assertEquals(latLng.latitude, 14.98, 0.001)
assertEquals(latLng.longitude, 89.21, 0.001)
}
} | app/src/test/kotlin/org/bbqaap/android/extension/LocationUtilsTest.kt | 3564118076 |
package com.tamsiree.rxdemo
import android.app.Application
import android.content.Context
import androidx.multidex.MultiDex
import com.tamsiree.rxdemo.activity.ActivitySVG
import com.tamsiree.rxkit.RxTool
import com.tamsiree.rxkit.activity.ActivityCrash
import com.tamsiree.rxkit.crash.TCrashProfile
import com.tamsiree.rxkit.crash.TCrashTool
import com.tamsiree.rxkit.view.RxToast
/**
* @author Tamsiree
* @date 2016/12/23
*/
class ApplicationRxDemo : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this)
}
override fun onCreate() {
super.onCreate()
RxTool.init(this)
.debugLog(true)
.debugLogFile(false)
.crashLogFile(true)
.crashProfile()//以下为崩溃配置
.backgroundMode(TCrashProfile.BACKGROUND_MODE_SILENT) //default: TCrashProfile.BACKGROUND_MODE_SHOW_CUSTOM
.enabled(true) //default: true
.showErrorDetails(true) //default: true
.showRestartButton(true) //default: true
.logErrorOnRestart(true) //default: true
.trackActivities(true) //default: false
.minTimeBetweenCrashesMs(2000) //default: 3000
.errorDrawable(R.drawable.crash_logo) //default: bug image
.restartActivity(ActivitySVG::class.java) //default: null (your app's launch activity)
.errorActivity(ActivityCrash::class.java) //default: null (default error activity)
.eventListener(object : TCrashTool.EventListener {
override fun onRestartAppFromErrorActivity() {
RxToast.normal("onRestartAppFromErrorActivity")
}
override fun onCloseAppFromErrorActivity() {
RxToast.normal("onCloseAppFromErrorActivity")
}
override fun onLaunchErrorActivity() {
RxToast.normal("onLaunchErrorActivity")
}
}) //default: null
.apply()
}
} | RxDemo/src/main/java/com/tamsiree/rxdemo/ApplicationRxDemo.kt | 3392266895 |
package com.calebprior.boilerplate.ui.contracts
import com.calebprior.boilerplate.adapters.FlexibleAdapter
import com.calebprior.boilerplate.adapters.TestHolder
import com.calebprior.boilerplate.data.TestModel
import com.calebprior.boilerplate.flowcontrol.FlowController
import com.calebprior.boilerplate.ui.base.BasePresenter
import com.calebprior.boilerplate.ui.base.BaseView
import java.util.function.Consumer
class RecyclerExampleContract {
class Presenter(
flowController: FlowController
) : BasePresenter<View>(flowController) {
fun loadData() {
for (i in 1..5) {
view?.addItem(TestHolder(TestModel("item $i")).apply { setSubscription(clickListener()) })
}
}
private fun clickListener() = Consumer<TestHolder> {
view?.removeItem(it)
}
fun onButtonPressed() {
view?.addItem(TestHolder(TestModel("added item")).apply { setSubscription(clickListener()) })
}
}
interface View : BaseView {
fun addItem(item: FlexibleAdapter.FlexibleHolder<*>)
fun removeItem(item: FlexibleAdapter.FlexibleHolder<*>)
}
} | app/src/main/kotlin/com/calebprior/boilerplate/ui/contracts/RecyclerExampleContract.kt | 2169704501 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.extension.text
import android.text.Editable
fun Editable.appendCompat(text: CharSequence, what: Any, flags: Int) {
val start = length
append(text)
val end = length
setSpan(what, start, end, flags)
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/extension/text/EditableExtensions.kt | 2513129770 |
package com.matejdro.wearmusiccenter.actions.playback
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.PersistableBundle
import androidx.appcompat.content.res.AppCompatResources
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.ActionHandler
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.actions.SelectableAction
import com.matejdro.wearmusiccenter.music.MusicService
import com.matejdro.wearmusiccenter.view.actionconfigs.ActionConfigFragment
import com.matejdro.wearmusiccenter.view.actionconfigs.ReverseSecondsConfigFragment
import javax.inject.Inject
/**
* Class name needs to be kept at "thirty seconds" for backwards compatibility
*/
class ReverseThirtySecondsAction : SelectableAction {
constructor(context: Context) : super(context)
constructor(context: Context, bundle: PersistableBundle) : super(context, bundle) {
secondsToReverse = bundle.getInt(KEY_SECONDS_TO_REVERSE, DEFAULT_SECONDS_TO_REVERSE)
}
var secondsToReverse: Int = DEFAULT_SECONDS_TO_REVERSE
override fun retrieveTitle(): String = context.getString(R.string.action_reverse_seconds, secondsToReverse)
override val defaultIcon: Drawable
get() = AppCompatResources.getDrawable(context, R.drawable.action_reverse_30_seconds)!!
override val configFragment: Class<out ActionConfigFragment<out PhoneAction>>
get() = ReverseSecondsConfigFragment::class.java
override fun writeToBundle(bundle: PersistableBundle) {
super.writeToBundle(bundle)
bundle.putInt(KEY_SECONDS_TO_REVERSE, secondsToReverse)
}
class Handler @Inject constructor(private val service: MusicService) : ActionHandler<ReverseThirtySecondsAction> {
override suspend fun handleAction(action: ReverseThirtySecondsAction) {
val currentPos = service.currentMediaController?.playbackState?.position ?: return
service.currentMediaController?.transportControls?.seekTo(
(currentPos - action.secondsToReverse * 1_000).coerceAtLeast(0)
)
}
}
}
private const val KEY_SECONDS_TO_REVERSE = "SECONDS_TO_REVERSE"
private const val DEFAULT_SECONDS_TO_REVERSE = 30
| mobile/src/main/java/com/matejdro/wearmusiccenter/actions/playback/ReverseThirtySecondsAction.kt | 102008717 |
package com.stripe.android.view
import android.content.Context
import androidx.appcompat.app.AlertDialog
import com.stripe.android.CustomerSession
import com.stripe.android.R
import com.stripe.android.core.StripeError
import com.stripe.android.model.PaymentMethod
internal class DeletePaymentMethodDialogFactory internal constructor(
private val context: Context,
private val adapter: PaymentMethodsAdapter,
private val cardDisplayTextFactory: CardDisplayTextFactory,
private val customerSession: Result<CustomerSession>,
private val productUsage: Set<String>,
private val onDeletedPaymentMethodCallback: (PaymentMethod) -> Unit
) {
@JvmSynthetic
fun create(paymentMethod: PaymentMethod): AlertDialog {
val message = paymentMethod.card?.let {
cardDisplayTextFactory.createUnstyled(it)
}
return AlertDialog.Builder(context, R.style.AlertDialogStyle)
.setTitle(R.string.delete_payment_method_prompt_title)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ ->
onDeletedPaymentMethod(paymentMethod)
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
adapter.resetPaymentMethod(paymentMethod)
}
.setOnCancelListener {
adapter.resetPaymentMethod(paymentMethod)
}
.create()
}
@JvmSynthetic
internal fun onDeletedPaymentMethod(paymentMethod: PaymentMethod) {
adapter.deletePaymentMethod(paymentMethod)
paymentMethod.id?.let { paymentMethodId ->
customerSession.getOrNull()?.detachPaymentMethod(
paymentMethodId = paymentMethodId,
productUsage = productUsage,
listener = PaymentMethodDeleteListener()
)
}
onDeletedPaymentMethodCallback(paymentMethod)
}
private class PaymentMethodDeleteListener : CustomerSession.PaymentMethodRetrievalListener {
override fun onPaymentMethodRetrieved(paymentMethod: PaymentMethod) {
}
override fun onError(errorCode: Int, errorMessage: String, stripeError: StripeError?) {
}
}
}
| payments-core/src/main/java/com/stripe/android/view/DeletePaymentMethodDialogFactory.kt | 830686128 |
package mswift42.com.github.weatherapp.data
data class ForecastResult(val city: City, val list: List<Forecast>)
data class City(val id: Long, val name: String, val coord: Coordinates,
val country: String, val population: Int)
data class Coordinates(val lon: Float, val lat: Float)
data class Forecast(val dt: Long, val temp: Temperature, val pressure: Float,
val humidity: Int, val weather: List<Weather>,
val speed: Float, val deg: Int, val clouds: Int,
val rain: Float)
data class Temperature(val day: Float, val min: Float, val max: Float,
val night: Float, val eve: Float, val morn: Float)
data class Weather(val id: Long, val main: String, val description: String,
val icon: String)
| WeatherApp/app/src/main/java/mswift42/com/github/weatherapp/data/ResponseClasses.kt | 3063545219 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.traits.Feasible
/**
* Represents the `command.drop-extender` section in the language.yml. Names map practically one-to-one.
*/
interface DropExtenderMessages : Feasible
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/settings/language/command/DropExtenderMessages.kt | 2538753569 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.api.settings.socketing.items
/**
* Represents the `items.socketed-item` section in the socketing.yml. Names map practically one-to-one.
*/
interface SocketedItemOptions {
val socket: String
val lore: List<String>
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/settings/socketing/items/SocketedItemOptions.kt | 3214935425 |
package au.com.codeka.warworlds.server.store
import au.com.codeka.warworlds.server.proto.SuspiciousEvent
import au.com.codeka.warworlds.server.store.base.BaseStore
import java.util.*
/**
* Store for keep track of suspicious events.
*/
class SuspiciousEventStore(fileName: String) : BaseStore(fileName) {
fun add(events: Collection<SuspiciousEvent>) {
newTransaction().use { t ->
val writer = newWriter(t)
.stmt("INSERT INTO suspicious_events (" +
"timestamp, day, empire_id, event) " +
"VALUES (?, ?, ?, ?)")
for (event in events) {
writer
.param(0, event.timestamp)
.param(1, StatsHelper.timestampToDay(event.timestamp))
.param(2, event.modification.empire_id)
.param(3, event.encode())
.execute()
}
t.commit()
}
}
fun query( /* TODO: search? */): Collection<SuspiciousEvent> {
newReader()
.stmt("SELECT event FROM suspicious_events ORDER BY timestamp DESC")
.query().use { res ->
val events: ArrayList<SuspiciousEvent> = ArrayList<SuspiciousEvent>()
while (res.next()) {
events.add(SuspiciousEvent.ADAPTER.decode(res.getBytes(0)))
}
return events
}
}
override fun onOpen(diskVersion: Int): Int {
var version = diskVersion
if (version == 0) {
newWriter()
.stmt(
"CREATE TABLE suspicious_events (" +
" timestamp INTEGER," +
" day INTEGER," +
" empire_id INTEGER," +
" event BLOB)")
.execute()
newWriter()
.stmt("CREATE INDEX IX_suspicious_events_day ON suspicious_events (day)")
.execute()
version++
}
return version
}
} | server/src/main/kotlin/au/com/codeka/warworlds/server/store/SuspiciousEventStore.kt | 997954640 |
package abi43_0_0.host.exp.exponent.modules.api.screens
import abi43_0_0.com.facebook.react.bridge.ReactContext
import abi43_0_0.com.facebook.react.uimanager.LayoutShadowNode
import abi43_0_0.com.facebook.react.uimanager.NativeViewHierarchyManager
import abi43_0_0.com.facebook.react.uimanager.NativeViewHierarchyOptimizer
import abi43_0_0.com.facebook.react.uimanager.UIManagerModule
internal class ScreensShadowNode(private var mContext: ReactContext) : LayoutShadowNode() {
override fun onBeforeLayout(nativeViewHierarchyOptimizer: NativeViewHierarchyOptimizer) {
super.onBeforeLayout(nativeViewHierarchyOptimizer)
(mContext.getNativeModule(UIManagerModule::class.java))?.addUIBlock { nativeViewHierarchyManager: NativeViewHierarchyManager ->
val view = nativeViewHierarchyManager.resolveView(reactTag)
if (view is ScreenContainer<*>) {
view.performUpdates()
}
}
}
}
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/screens/ScreensShadowNode.kt | 2675275586 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.templating
import kotlin.math.max
import kotlin.math.min
object RandTemplate : Template("rand") {
private const val dashPatternString = "\\s*[-]\\s*"
private val dashPattern = dashPatternString.toRegex()
override fun invoke(arguments: String): String {
if (arguments.isBlank()) {
return arguments
}
val split = arguments.split(dashPattern).mapNotNull { it.trim() }.filter(String::isNotEmpty)
val first = split[0].toIntOrNull() ?: return arguments
val second = split[1].toIntOrNull() ?: return arguments
val minVal = min(first, second)
val maxVal = max(first, second)
return (minVal..maxVal).random().toString()
}
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/templating/RandTemplate.kt | 3535131422 |
package com.twitter.meil_mitu.twitter4hk.exception
class IncorrectException(message: String) : RuntimeException(message)
| library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/exception/IncorrectException.kt | 2876273324 |
package com.teamwizardry.librarianlib.mosaic
import com.teamwizardry.librarianlib.math.Matrix4d
import net.minecraft.client.render.RenderLayer
import net.minecraft.util.Identifier
import java.awt.Color
public class PinnedWrapper(
public val wrapped: Sprite,
override val pinTop: Boolean,
override val pinBottom: Boolean,
override val pinLeft: Boolean,
override val pinRight: Boolean
): Sprite {
override fun minU(animFrames: Int): Float = wrapped.minU(animFrames)
override fun minU(): Float = wrapped.minU()
override fun minV(animFrames: Int): Float = wrapped.minV(animFrames)
override fun minV(): Float = wrapped.minV()
override fun maxU(animFrames: Int): Float = wrapped.maxU(animFrames)
override fun maxU(): Float = wrapped.maxU()
override fun maxV(animFrames: Int): Float = wrapped.maxV(animFrames)
override fun maxV(): Float = wrapped.maxV()
override fun draw(matrix: Matrix4d, x: Float, y: Float, animTicks: Int, tint: Color) {
wrapped.draw(matrix, x, y, animTicks, tint)
}
override fun draw(matrix: Matrix4d, x: Float, y: Float, width: Float, height: Float, animTicks: Int, tint: Color) {
wrapped.draw(matrix, x, y, width, height, animTicks, tint)
}
override fun pinnedWrapper(top: Boolean, bottom: Boolean, left: Boolean, right: Boolean): Sprite {
return wrapped.pinnedWrapper(top, bottom, left, right)
}
override val texture: Identifier get() = wrapped.texture
override val width: Int get() = wrapped.width
override val height: Int get() = wrapped.height
override val uSize: Float get() = wrapped.uSize
override val vSize: Float get() = wrapped.vSize
override val frameCount: Int get() = wrapped.frameCount
override val minUCap: Float get() = wrapped.minUCap
override val minVCap: Float get() = wrapped.minVCap
override val maxUCap: Float get() = wrapped.maxUCap
override val maxVCap: Float get() = wrapped.maxVCap
override val rotation: Int get() = wrapped.rotation
} | modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/PinnedWrapper.kt | 3452378252 |
package me.ebonjaeger.novusbroadcast.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandCompletion
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Subcommand
import me.ebonjaeger.novusbroadcast.NovusBroadcast
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
@CommandAlias("novusbroadcast|nb")
class SendCommand(private val plugin: NovusBroadcast) : BaseCommand()
{
@Subcommand("send")
@CommandCompletion("@messageLists")
@CommandPermission("novusbroadcast.send")
@Description("Immediately send the message at the given index to all players.")
fun onSend(sender: CommandSender, listName: String, index: Int)
{
val messageList = plugin.messageLists[listName]
if (messageList == null)
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}No list with name '$listName' found!")
return
}
if (messageList.hasMessageAtIndex(index))
{
messageList.sendMessage(index)
} else
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}No message at index '$index'!")
}
}
}
| src/main/kotlin/me/ebonjaeger/novusbroadcast/commands/SendCommand.kt | 1912334382 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import org.rust.cargo.project.model.CargoProjectActionBase
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.model.guessAndSetupRustProject
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.hasCargoProject
import org.rust.ide.notifications.confirmLoadingUntrustedProject
import org.rust.openapiext.saveAllDocuments
class RefreshCargoProjectsAction : CargoProjectActionBase() {
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabled = project != null && project.toolchain != null && project.hasCargoProject
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (!project.confirmLoadingUntrustedProject()) return
saveAllDocuments()
if (project.toolchain == null || !project.hasCargoProject) {
guessAndSetupRustProject(project, explicitRequest = true)
} else {
project.cargoProjects.refreshAllProjects()
}
}
}
| src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectsAction.kt | 4199725629 |
package org.jetbrains.fortran.lang.parser
import com.intellij.lang.PsiBuilder
import org.jetbrains.fortran.lang.FortranTypes.IDENTIFIER
import org.jetbrains.fortran.lang.parser.FortranParserUtil.consumeToken
import org.jetbrains.fortran.lang.parser.FortranParserUtil.enter_section_
import org.jetbrains.fortran.lang.parser.FortranParserUtil.exit_section_
import org.jetbrains.fortran.lang.parser.FortranParserUtil.recursion_guard_
import org.jetbrains.fortran.lang.psi.FortranTokenSets
import org.jetbrains.fortran.lang.psi.FortranTokenType
class IdentifierParser : FortranParserUtil.Parser {
override fun parse(builder: PsiBuilder, level: Int): Boolean {
if (!recursion_guard_(builder, level, "Identifier")) return false
var result: Boolean
val marker = enter_section_(builder)
result = consumeToken(builder, IDENTIFIER)
if (!result) {
val tokenType = builder.tokenType
if (tokenType === FortranTokenType.WORD || FortranTokenSets.KEYWORDS.contains(tokenType)) {
builder.remapCurrentToken(FortranParserUtil.cloneTTwithBase(tokenType, IDENTIFIER))
result = consumeToken(builder, IDENTIFIER)
}
}
exit_section_(builder, marker, null, result)
return result
}
}
| src/main/kotlin/org/jetbrains/fortran/lang/parser/IdentifierParser.kt | 623228655 |
package com.teamwizardry.librarianlib.facade.test.screens
import com.teamwizardry.librarianlib.facade.FacadeScreen
import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents
import com.teamwizardry.librarianlib.facade.layers.SpriteLayer
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.mosaic.Mosaic
import net.minecraft.text.Text
import net.minecraft.util.Identifier
class LayerTransformTestScreen(title: Text): FacadeScreen(title) {
init {
val dirt = Mosaic(Identifier("minecraft:textures/block/dirt.png"), 16, 16).getSprite("")
val stone = Mosaic(Identifier("minecraft:textures/block/stone.png"), 16, 16).getSprite("")
val layer = SpriteLayer(dirt)
layer.pos = vec(32, 32)
layer.rotation = Math.toRadians(15.0)
val layer2 = SpriteLayer(dirt)
layer2.pos = vec(32, 32)
layer2.rotation = Math.toRadians(-15.0)
layer.add(layer2)
layer.BUS.hook<GuiLayerEvents.MouseMove> {
layer.sprite = if (layer.mouseOver) stone else dirt
}
layer2.BUS.hook<GuiLayerEvents.MouseMove> {
layer2.sprite = if (layer2.mouseOver) stone else dirt
}
facade.root.add(layer)
}
} | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/LayerTransformTestScreen.kt | 914619380 |
/*
Copyright 2017-2020 Charles Korn.
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 batect.docker.pull
import batect.testutils.createForEachTest
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import batect.testutils.runNullableForEachTest
import batect.utils.Json
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DockerImageProgressReporterSpec : Spek({
describe("a Docker image pull progress reporter") {
val reporter by createForEachTest { DockerImageProgressReporter() }
mapOf(
"an empty event" to "{}",
"an 'image pull starting' event" to """{"status":"Pulling from library/node","id":"10-stretch"}""",
"a 'layer already exists' event" to """{"status":"Already exists","progressDetail":{},"id":"55cbf04beb70"}""",
"a 'layer pull starting' event" to """{"status":"Pulling fs layer","progressDetail":{},"id":"d6cd23cd1a2c"}""",
"a 'waiting to pull layer' event" to """{"status":"Waiting","progressDetail":{},"id":"4c60885e4f94"}""",
"an 'image digest' event" to """{"status":"Digest: sha256:e6b798f4eeb4e6334d195cdeabc18d07dc5158aa88ad5d83670462852b431a71"}""",
"a 'downloaded newer image' event" to """{"status":"Status: Downloaded newer image for node:10-stretch"}""",
"an 'image up to date' event" to """{"status":"Status: Image is up to date for node:10-stretch"}"""
).forEach { (description, json) ->
given(description) {
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("does not return an update") {
assertThat(progressUpdate, absent())
}
}
}
}
given("a single 'layer downloading' event") {
val json = """{"status":"Downloading","progressDetail":{"current":329,"total":4159},"id":"d6cd23cd1a2c"}"""
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 329, 4159)))
}
}
}
given("a single 'layer extracting' event") {
val json = """{"status":"Extracting","progressDetail":{"current":329,"total":4159},"id":"d6cd23cd1a2c"}"""
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("extracting", 329, 4159)))
}
}
}
given("a single 'verifying checksum' event without any previous events for that layer") {
val json = """{"status":"Verifying Checksum","progressDetail":{},"id":"d6cd23cd1a2c"}"""
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("verifying checksum", 0, 0)))
}
}
}
given("a single 'layer downloading' event has been processed") {
beforeEachTest {
reporter.processRawProgressUpdate("""{"status":"Downloading","progressDetail":{"current":329,"total":4159},"id":"d6cd23cd1a2c"}""")
}
on("processing another 'layer downloading' event for the same layer") {
val json = """{"status":"Downloading","progressDetail":{"current":900,"total":4159},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 900, 4159)))
}
}
on("processing another 'layer downloading' event for the same layer that does not result in updated information") {
val json = """{"status":"Downloading","progressDetail":{"current":329,"total":4159},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("does not return an update") {
assertThat(progressUpdate, absent())
}
}
on("processing a 'verifying checksum' event for the same layer") {
// Note that the 'status' field for a 'verifying checksum' event has the S capitalised, while
// every other kind of event uses lowercase for later words in the description.
val json = """{"status":"Verifying Checksum","progressDetail":{},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("verifying checksum", 0, 4159)))
}
}
on("processing a 'download complete' event for the same layer") {
val json = """{"status":"Download complete","progressDetail":{},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("download complete", 4159, 4159)))
}
}
on("processing an 'extracting' event for the same layer") {
val json = """{"status":"Extracting","progressDetail":{"current":1000,"total":4159},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("extracting", 1000, 4159)))
}
}
on("processing a 'pull complete' event for the same layer") {
val json = """{"status":"Pull complete","progressDetail":{},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("pull complete", 4159, 4159)))
}
}
on("processing a 'layer downloading' event for another layer") {
val json = """{"status":"Downloading","progressDetail":{"current":900,"total":7000},"id":"b59856e9f0ab"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns a progress update combining the state of both layers") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 329 + 900, 4159 + 7000)))
}
}
given("a 'layer downloading' event for another layer has been processed") {
beforeEachTest {
reporter.processRawProgressUpdate("""{"status":"Downloading","progressDetail":{"current":900,"total":7000},"id":"b59856e9f0ab"}""")
}
mapOf(
"verifying checksum" to """{"status":"Verifying Checksum","progressDetail":{},"id":"b59856e9f0ab"}""",
"download complete" to """{"status":"Download complete","progressDetail":{},"id":"b59856e9f0ab"}""",
"extracting" to """{"status":"Extracting","progressDetail":{"current":1000,"total":7000},"id":"b59856e9f0ab"}""",
"pull complete" to """{"status":"Pull complete","progressDetail":{},"id":"b59856e9f0ab"}"""
).forEach { (eventType, json) ->
on("processing a '$eventType' event for that other layer") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns a progress update combining the state of both layers") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 329 + 7000, 4159 + 7000)))
}
}
}
}
given("a 'pull complete' event has been processed") {
beforeEachTest {
reporter.processRawProgressUpdate("""{"status":"Pull complete","progressDetail":{},"id":"d6cd23cd1a2c"}""")
}
on("processing a 'layer downloading' event for another layer") {
val json = """{"status":"Downloading","progressDetail":{"current":900,"total":7000},"id":"b59856e9f0ab"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns a progress update combining the state of both layers") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 4159 + 900, 4159 + 7000)))
}
}
}
}
given("a single 'verifying checksum' event has been processed") {
beforeEachTest {
reporter.processRawProgressUpdate("""{"status":"Verifying Checksum","progressDetail":{},"id":"d6cd23cd1a2c"}""")
}
on("processing another 'verifying checksum' event for the same layer") {
val json = """{"status":"Verifying Checksum","progressDetail":{},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("does not return an update") {
assertThat(progressUpdate, absent())
}
}
on("processing a 'layer downloading' event for the same layer") {
val json = """{"status":"Downloading","progressDetail":{"current":900,"total":4159},"id":"d6cd23cd1a2c"}"""
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 900, 4159)))
}
}
}
given("a single 'downloading' event that is not for a layer") {
val json = """{"status":"Downloading","progressDetail":{"current":329,"total":4159}}"""
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 329, 4159)))
}
}
}
given("a single 'downloading' event with an unknown number of total bytes") {
val json = """{"status":"Downloading","progressDetail":{"current":329,"total":-1}}"""
on("processing the event") {
val progressUpdate by runNullableForEachTest { reporter.processRawProgressUpdate(json) }
it("returns an appropriate progress update") {
assertThat(progressUpdate, equalTo(DockerImageProgress("downloading", 329, 0)))
}
}
}
}
})
private fun DockerImageProgressReporter.processRawProgressUpdate(json: String): DockerImageProgress? {
val parsedJson = Json.parser.parseJson(json).jsonObject
return this.processProgressUpdate(parsedJson)
}
| app/src/unitTest/kotlin/batect/docker/pull/DockerImageProgressReporterSpec.kt | 4251587581 |
package com.openconference.speakerdetails
import android.support.annotation.DrawableRes
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import de.droidcon.berlin2018.R
/**
* ViewHolder for icon text combination
*
* @author Hannes Dorfmann
*/
open class SpeakerDetailsViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val icon = v.findViewById<ImageView>(R.id.icon)
val text = v.findViewById<TextView>(R.id.text)
inline fun bind(@DrawableRes iconRes: Int?, t: String) {
if (iconRes == null) {
icon.visibility = View.INVISIBLE
} else {
icon.setImageDrawable(itemView.resources.getDrawable(iconRes))
}
text.text = t
}
}
| app/src/main/java/de/droidcon/berlin2018/ui/speakerdetail/SpeakerDetailsViewHolder.kt | 2284278202 |
package taiwan.no1.app.ssfm.models.data.remote.services.v2
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.QueryMap
import taiwan.no1.app.ssfm.models.data.remote.config.Music4Config
import taiwan.no1.app.ssfm.models.entities.v2.HotPlaylistEntity
import taiwan.no1.app.ssfm.models.entities.v2.MusicEntity
import taiwan.no1.app.ssfm.models.entities.v2.MusicRankEntity
import taiwan.no1.app.ssfm.models.entities.v2.SongListEntity
/**
* @author jieyi
* @since 11/20/17
*/
interface MusicV2Service {
@GET("${Music4Config.API_REQUEST}/rank_song_list")
fun musicRanking(@QueryMap queries: Map<String, String>): Observable<MusicRankEntity>
@GET("${Music4Config.API_REQUEST}/search")
fun searchMusic(@QueryMap queries: Map<String, String>): Observable<MusicEntity>
@GET("${Music4Config.API_REQUEST}/hot_song_list")
fun hotPlaylist(@QueryMap queries: Map<String, String>): Observable<HotPlaylistEntity>
@GET("${Music4Config.API_REQUEST}/song_list")
fun playlistDetail(@QueryMap queries: Map<String, String>): Observable<SongListEntity>
} | app/src/main/kotlin/taiwan/no1/app/ssfm/models/data/remote/services/v2/MusicV2Service.kt | 3590187809 |
/*
* 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.runtime
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlin.coroutines.EmptyCoroutineContext
/**
* Schedule [effect] to run when the current composition completes successfully and applies
* changes. [SideEffect] can be used to apply side effects to objects managed by the
* composition that are not backed by [snapshots][androidx.compose.runtime.snapshots.Snapshot] so
* as not to leave those objects in an inconsistent state if the current composition operation
* fails.
*
* [effect] will always be run on the composition's apply dispatcher and appliers are never run
* concurrent with themselves, one another, applying changes to the composition tree, or running
* [RememberObserver] event callbacks. [SideEffect]s are always run after [RememberObserver]
* event callbacks.
*
* A [SideEffect] runs after **every** recomposition. To launch an ongoing task spanning
* potentially many recompositions, see [LaunchedEffect]. To manage an event subscription or other
* object lifecycle, see [DisposableEffect].
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun SideEffect(
effect: () -> Unit
) {
currentComposer.recordSideEffect(effect)
}
/**
* Receiver scope for [DisposableEffect] that offers the [onDispose] clause that should be
* the last statement in any call to [DisposableEffect].
*/
class DisposableEffectScope {
/**
* Provide [onDisposeEffect] to the [DisposableEffect] to run when it leaves the composition
* or its key changes.
*/
inline fun onDispose(
crossinline onDisposeEffect: () -> Unit
): DisposableEffectResult = object : DisposableEffectResult {
override fun dispose() {
onDisposeEffect()
}
}
}
interface DisposableEffectResult {
fun dispose()
}
private val InternalDisposableEffectScope = DisposableEffectScope()
private class DisposableEffectImpl(
private val effect: DisposableEffectScope.() -> DisposableEffectResult
) : RememberObserver {
private var onDispose: DisposableEffectResult? = null
override fun onRemembered() {
onDispose = InternalDisposableEffectScope.effect()
}
override fun onForgotten() {
onDispose?.dispose()
onDispose = null
}
override fun onAbandoned() {
// Nothing to do as [onRemembered] was not called.
}
}
private const val DisposableEffectNoParamError =
"DisposableEffect must provide one or more 'key' parameters that define the identity of " +
"the DisposableEffect and determine when its previous effect should be disposed and " +
"a new effect started for the new key."
private const val LaunchedEffectNoParamError =
"LaunchedEffect must provide one or more 'key' parameters that define the identity of " +
"the LaunchedEffect and determine when its previous effect coroutine should be cancelled " +
"and a new effect launched for the new key."
/**
* A side effect of composition that must be reversed or cleaned up if the [DisposableEffect]
* leaves the composition.
*
* It is an error to call [DisposableEffect] without at least one `key` parameter.
*/
// This deprecated-error function shadows the varargs overload so that the varargs version
// is not used without key parameters.
@Composable
@NonRestartableComposable
@Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER")
@Deprecated(DisposableEffectNoParamError, level = DeprecationLevel.ERROR)
fun DisposableEffect(
effect: DisposableEffectScope.() -> DisposableEffectResult
): Unit = error(DisposableEffectNoParamError)
/**
* A side effect of composition that must run for any new unique value of [key1] and must be
* reversed or cleaned up if [key1] changes or if the [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [key1] or [key2]
* and must be reversed or cleaned up if [key1] or [key2] changes, or if the
* [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver]
* event callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
key2: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1, key2) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [key1], [key2]
* or [key3] and must be reversed or cleaned up if [key1], [key2] or [key3]
* changes, or if the [DisposableEffect] leaves the composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
fun DisposableEffect(
key1: Any?,
key2: Any?,
key3: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(key1, key2, key3) { DisposableEffectImpl(effect) }
}
/**
* A side effect of composition that must run for any new unique value of [keys] and must
* be reversed or cleaned up if any [keys] change or if the [DisposableEffect] leaves the
* composition.
*
* A [DisposableEffect]'s _key_ is a value that defines the identity of the
* [DisposableEffect]. If a key changes, the [DisposableEffect] must
* [dispose][DisposableEffectScope.onDispose] its current [effect] and reset by calling [effect]
* again. Examples of keys include:
*
* * Observable objects that the effect subscribes to
* * Unique request parameters to an operation that must cancel and retry if those parameters change
*
* [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize
* when a different key is provided, performing cleanup for the old operation before
* initializing the new. For example:
*
* @sample androidx.compose.runtime.samples.disposableEffectSample
*
* A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause
* as the final statement in its [effect] block. If your operation does not require disposal
* it might be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should
* be managed by the composition.
*
* There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call
* to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run
* on the composition's apply dispatcher and appliers are never run concurrent with themselves,
* one another, applying changes to the composition tree, or running [RememberObserver] event
* callbacks.
*/
@Composable
@NonRestartableComposable
@Suppress("ArrayReturn")
fun DisposableEffect(
vararg keys: Any?,
effect: DisposableEffectScope.() -> DisposableEffectResult
) {
remember(*keys) { DisposableEffectImpl(effect) }
}
internal class LaunchedEffectImpl(
parentCoroutineContext: CoroutineContext,
private val task: suspend CoroutineScope.() -> Unit
) : RememberObserver {
private val scope = CoroutineScope(parentCoroutineContext)
private var job: Job? = null
override fun onRemembered() {
job?.cancel("Old job was still running!")
job = scope.launch(block = task)
}
override fun onForgotten() {
job?.cancel()
job = null
}
override fun onAbandoned() {
job?.cancel()
job = null
}
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] when the [LaunchedEffect]
* leaves the composition.
*
* It is an error to call [LaunchedEffect] without at least one `key` parameter.
*/
// This deprecated-error function shadows the varargs overload so that the varargs version
// is not used without key parameters.
@Deprecated(LaunchedEffectNoParamError, level = DeprecationLevel.ERROR)
@Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER")
@Composable
fun LaunchedEffect(
block: suspend CoroutineScope.() -> Unit
): Unit = error(LaunchedEffectNoParamError)
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key1]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1] or [key2]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
key2: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1, key2) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with a different [key1], [key2] or [key3].
* The coroutine will be [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
key1: Any?,
key2: Any?,
key3: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(key1, key2, key3) { LaunchedEffectImpl(applyContext, block) }
}
/**
* When [LaunchedEffect] enters the composition it will launch [block] into the composition's
* [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when
* [LaunchedEffect] is recomposed with any different [keys]. The coroutine will be
* [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition.
*
* This function should **not** be used to (re-)launch ongoing tasks in response to callback
* events by way of storing callback data in [MutableState] passed to [key]. Instead, see
* [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs
* scoped to the composition in response to event callbacks.
*/
@Composable
@NonRestartableComposable
@Suppress("ArrayReturn")
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
vararg keys: Any?,
block: suspend CoroutineScope.() -> Unit
) {
val applyContext = currentComposer.applyCoroutineContext
remember(*keys) { LaunchedEffectImpl(applyContext, block) }
}
@PublishedApi
internal class CompositionScopedCoroutineScopeCanceller(
val coroutineScope: CoroutineScope
) : RememberObserver {
override fun onRemembered() {
// Nothing to do
}
override fun onForgotten() {
coroutineScope.cancel()
}
override fun onAbandoned() {
coroutineScope.cancel()
}
}
@PublishedApi
@OptIn(InternalComposeApi::class)
internal fun createCompositionCoroutineScope(
coroutineContext: CoroutineContext,
composer: Composer
) = if (coroutineContext[Job] != null) {
CoroutineScope(
Job().apply {
completeExceptionally(
IllegalArgumentException(
"CoroutineContext supplied to " +
"rememberCoroutineScope may not include a parent job"
)
)
}
)
} else {
val applyContext = composer.applyCoroutineContext
CoroutineScope(applyContext + Job(applyContext[Job]) + coroutineContext)
}
/**
* Return a [CoroutineScope] bound to this point in the composition using the optional
* [CoroutineContext] provided by [getContext]. [getContext] will only be called once and the same
* [CoroutineScope] instance will be returned across recompositions.
*
* This scope will be [cancelled][CoroutineScope.cancel] when this call leaves the composition.
* The [CoroutineContext] returned by [getContext] may not contain a [Job] as this scope is
* considered to be a child of the composition.
*
* The default dispatcher of this scope if one is not provided by the context returned by
* [getContext] will be the applying dispatcher of the composition's [Recomposer].
*
* Use this scope to launch jobs in response to callback events such as clicks or other user
* interaction where the response to that event needs to unfold over time and be cancelled if the
* composable managing that process leaves the composition. Jobs should never be launched into
* **any** coroutine scope as a side effect of composition itself. For scoped ongoing jobs
* initiated by composition, see [LaunchedEffect].
*
* This function will not throw if preconditions are not met, as composable functions do not yet
* fully support exceptions. Instead the returned scope's [CoroutineScope.coroutineContext] will
* contain a failed [Job] with the associated exception and will not be capable of launching
* child jobs.
*/
@Composable
inline fun rememberCoroutineScope(
crossinline getContext: @DisallowComposableCalls () -> CoroutineContext =
{ EmptyCoroutineContext }
): CoroutineScope {
val composer = currentComposer
val wrapper = remember {
CompositionScopedCoroutineScopeCanceller(
createCompositionCoroutineScope(getContext(), composer)
)
}
return wrapper.coroutineScope
}
| compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/Effects.kt | 427533861 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.dialog
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.testutils.assertIsEqualTo
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.hasClickAction
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipeRight
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.test.filters.SdkSuppress
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.LocalContentColor
import androidx.wear.compose.material.LocalTextStyle
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.TEST_TAG
import androidx.wear.compose.material.TestImage
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.assertContainsColor
import androidx.wear.compose.material.setContentWithTheme
import androidx.wear.compose.material.setContentWithThemeForSizeAssertions
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
internal const val ICON_TAG = "icon"
internal const val TITLE_TAG = "Title"
internal const val BODY_TAG = "Body"
internal const val BUTTON_TAG = "Button"
internal const val CHIP_TAG = "Chip"
class DialogBehaviourTest {
@get:Rule
val rule = createComposeRule()
@Test
fun supports_testtag_on_alert_with_buttons() {
rule.setContentWithTheme {
Alert(
title = {},
negativeButton = {},
positiveButton = {},
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun supports_testtag_on_alert_with_chips() {
rule.setContentWithTheme {
Alert(
title = {},
message = {},
content = {},
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun supports_testtag_on_confirmation() {
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
icon = {},
content = {},
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_icon_on_alert_with_buttons() {
rule.setContentWithTheme {
Alert(
icon = { TestImage(TEST_TAG) },
title = {},
negativeButton = {},
positiveButton = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_icon_on_alert_with_chips() {
rule.setContentWithTheme {
Alert(
icon = { TestImage(TEST_TAG) },
title = {},
message = {},
content = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_icon_on_confirmation() {
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
icon = { TestImage(TEST_TAG) },
content = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_title_on_alert_with_buttons() {
rule.setContentWithTheme {
Alert(
title = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
negativeButton = {},
positiveButton = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_title_on_alert_with_chips() {
rule.setContentWithTheme {
Alert(
icon = {},
title = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
message = {},
content = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_title_on_confirmation() {
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
icon = {},
content = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_bodymessage_on_alert_with_buttons() {
rule.setContentWithTheme {
Alert(
title = {},
negativeButton = {},
positiveButton = {},
content = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_bodymessage_on_alert_with_chips() {
rule.setContentWithTheme {
Alert(
icon = {},
title = {},
message = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
content = {},
)
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun displays_buttons_on_alert_with_buttons() {
val buttonTag1 = "Button1"
val buttonTag2 = "Button2"
rule.setContentWithTheme {
Alert(
title = {},
negativeButton = {
Button(onClick = {}, modifier = Modifier.testTag(buttonTag1), content = {})
},
positiveButton = {
Button(onClick = {}, modifier = Modifier.testTag(buttonTag2), content = {})
},
content = {},
)
}
rule.onNodeWithTag(buttonTag1).assertExists()
rule.onNodeWithTag(buttonTag2).assertExists()
}
@Test
fun supports_swipetodismiss_on_wrapped_alertdialog_with_buttons() {
rule.setContentWithTheme {
Box {
var showDialog by remember { mutableStateOf(true) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Start Screen")
}
Dialog(
showDialog = showDialog,
onDismissRequest = { showDialog = false },
) {
Alert(
title = {},
negativeButton = {
Button(onClick = {}, content = {})
},
positiveButton = {
Button(onClick = {}, content = {})
},
content = { Text("Dialog", modifier = Modifier.testTag(TEST_TAG)) },
)
}
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.onNodeWithTag(TEST_TAG).assertDoesNotExist()
}
@Test
fun supports_swipetodismiss_on_wrapped_alertdialog_with_chips() {
rule.setContentWithTheme {
Box {
var showDialog by remember { mutableStateOf(true) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Label")
}
Dialog(
showDialog = showDialog,
onDismissRequest = { showDialog = false },
) {
Alert(
icon = {},
title = {},
message = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
content = {},
)
}
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.onNodeWithTag(TEST_TAG).assertDoesNotExist()
}
@Test
fun supports_swipetodismiss_on_wrapped_confirmationdialog() {
rule.setContentWithTheme {
Box {
var showDialog by remember { mutableStateOf(true) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Label")
}
Dialog(
showDialog = showDialog,
onDismissRequest = { showDialog = false },
) {
Confirmation(
onTimeout = { showDialog = false },
icon = {},
content = { Text("Dialog", modifier = Modifier.testTag(TEST_TAG)) },
)
}
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.onNodeWithTag(TEST_TAG).assertDoesNotExist()
}
@Test
fun shows_dialog_when_showdialog_equals_true() {
rule.setContentWithTheme {
Box {
var showDialog by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Chip(onClick = { showDialog = true }, label = { Text("Show") })
}
Dialog(
showDialog = showDialog,
onDismissRequest = { showDialog = false },
) {
Alert(
icon = {},
title = {},
message = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
content = {},
)
}
}
}
rule.onNode(hasClickAction()).performClick()
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun calls_ondismissrequest_when_dialog_is_swiped() {
val dismissedText = "Dismissed"
rule.setContentWithTheme {
Box {
var dismissed by remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(if (dismissed) dismissedText else "Label")
}
Dialog(
showDialog = !dismissed,
onDismissRequest = { dismissed = true },
) {
Alert(
icon = {},
title = {},
message = { Text("Text", modifier = Modifier.testTag(TEST_TAG)) },
content = {},
)
}
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.onNodeWithText(dismissedText).assertExists()
}
}
class DialogContentSizeAndPositionTest {
@get:Rule
val rule = createComposeRule()
@Test
fun spaces_icon_and_title_correctly_on_alert_with_buttons() {
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
negativeButton = {
Button(onClick = {}, modifier = Modifier.testTag(BUTTON_TAG)) {}
},
positiveButton = { Button(onClick = {}) {} },
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val iconBottom = rule.onNodeWithTag(ICON_TAG).getUnclippedBoundsInRoot().bottom
val titleTop = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().top
titleTop.assertIsEqualTo(iconBottom + DialogDefaults.IconSpacing)
}
@Test
fun spaces_title_and_buttons_correctly_on_alert_with_buttons() {
var titlePadding = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
titlePadding = DialogDefaults.TitlePadding.calculateBottomPadding()
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
negativeButton = {
Button(onClick = {}, modifier = Modifier.testTag(BUTTON_TAG)) {}
},
positiveButton = { Button(onClick = {}) {} },
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val titleBottom = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().bottom
val buttonTop = rule.onNodeWithTag(BUTTON_TAG).getUnclippedBoundsInRoot().top
buttonTop.assertIsEqualTo(titleBottom + titlePadding)
}
@Test
fun spaces_icon_and_title_correctly_on_alert_with_chips() {
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
content = {
item {
Chip(
label = { Text("Chip") },
onClick = {},
modifier = Modifier.testTag(CHIP_TAG)
)
}
},
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val iconBottom = rule.onNodeWithTag(ICON_TAG).getUnclippedBoundsInRoot().bottom
val titleTop = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().top
titleTop.assertIsEqualTo(iconBottom + DialogDefaults.IconSpacing)
}
@Test
fun spaces_title_and_chips_correctly_on_alert_with_chips() {
var titlePadding = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
titlePadding = DialogDefaults.TitlePadding.calculateBottomPadding()
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
content = {
item {
Chip(
label = { Text("Chip") },
onClick = {},
modifier = Modifier.testTag(CHIP_TAG)
)
}
},
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val titleBottom = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().bottom
val chipTop = rule.onNodeWithTag(CHIP_TAG).getUnclippedBoundsInRoot().top
chipTop.assertIsEqualTo(titleBottom + titlePadding)
}
@Test
fun spaces_icon_and_title_correctly_on_confirmation() {
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
Confirmation(
onTimeout = {},
icon = { TestImage(ICON_TAG) },
content = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val iconBottom = rule.onNodeWithTag(ICON_TAG).getUnclippedBoundsInRoot().bottom
val titleTop = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().top
titleTop.assertIsEqualTo(iconBottom + DialogDefaults.IconSpacing)
}
@Test
fun spaces_title_and_body_correctly_on_alert_with_buttons() {
var titleSpacing = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
titleSpacing = DialogDefaults.TitlePadding.calculateBottomPadding()
Alert(
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
negativeButton = {
Button(onClick = {}, modifier = Modifier.testTag(BUTTON_TAG)) {}
},
positiveButton = { Button(onClick = {}) {} },
content = { Text("Body", modifier = Modifier.testTag(BODY_TAG)) },
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val titleBottom = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().bottom
val bodyTop = rule.onNodeWithTag(BODY_TAG).getUnclippedBoundsInRoot().top
bodyTop.assertIsEqualTo(titleBottom + titleSpacing)
}
@Test
fun spaces_title_and_body_correctly_on_alert_with_chips() {
var titleSpacing = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
titleSpacing = DialogDefaults.TitlePadding.calculateBottomPadding()
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
message = { Text("Message", modifier = Modifier.testTag(BODY_TAG)) },
content = {
item {
Chip(
label = { Text("Chip") },
onClick = {},
modifier = Modifier.testTag(CHIP_TAG)
)
}
},
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val titleBottom = rule.onNodeWithTag(TITLE_TAG).getUnclippedBoundsInRoot().bottom
val bodyTop = rule.onNodeWithTag(BODY_TAG).getUnclippedBoundsInRoot().top
bodyTop.assertIsEqualTo(titleBottom + titleSpacing)
}
@Test
fun spaces_body_and_buttons_correctly_on_alert_with_buttons() {
var bodyPadding = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
bodyPadding = DialogDefaults.BodyPadding.calculateBottomPadding()
Alert(
icon = {},
title = {},
negativeButton = {
Button(onClick = {}, modifier = Modifier.testTag(BUTTON_TAG)) {}
},
positiveButton = {
Button(onClick = {}) {}
},
content = { Text("Body", modifier = Modifier.testTag(BODY_TAG)) },
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val bodyBottom = rule.onNodeWithTag(BODY_TAG).getUnclippedBoundsInRoot().bottom
val buttonTop = rule.onNodeWithTag(BUTTON_TAG).getUnclippedBoundsInRoot().top
buttonTop.assertIsEqualTo(bodyBottom + bodyPadding)
}
@Test
fun spaces_body_and_chips_correctly_on_alert_with_chips() {
var bodyPadding = 0.dp
rule
.setContentWithThemeForSizeAssertions(useUnmergedTree = true) {
bodyPadding = DialogDefaults.BodyPadding.calculateBottomPadding()
Alert(
icon = { TestImage(ICON_TAG) },
title = { Text("Title", modifier = Modifier.testTag(TITLE_TAG)) },
message = { Text("Message", modifier = Modifier.testTag(BODY_TAG)) },
content = {
item {
Chip(
label = { Text("Chip") },
onClick = {},
modifier = Modifier.testTag(CHIP_TAG)
)
}
},
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.CenterVertically),
modifier = Modifier.testTag(TEST_TAG),
)
}
val bodyBottom = rule.onNodeWithTag(BODY_TAG).getUnclippedBoundsInRoot().bottom
val chipTop = rule.onNodeWithTag(CHIP_TAG).getUnclippedBoundsInRoot().top
chipTop.assertIsEqualTo(bodyBottom + bodyPadding)
}
}
class DialogContentColorTest {
@get:Rule
val rule = createComposeRule()
@Test
fun gives_icon_onbackground_on_alert_for_buttons() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Alert(
icon = { actualColor = LocalContentColor.current },
title = {},
negativeButton = {},
positiveButton = {},
content = {},
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_icon_onbackground_on_alert_for_chips() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Alert(
icon = { actualColor = LocalContentColor.current },
title = {},
message = {},
content = {},
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_icon_onbackground_on_confirmation() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Confirmation(
onTimeout = {},
icon = { actualColor = LocalContentColor.current },
content = {},
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_custom_icon_on_alert_for_buttons() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
iconColor = overrideColor,
icon = { actualColor = LocalContentColor.current },
title = {},
negativeButton = {},
positiveButton = {},
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_custom_icon_on_alert_for_chips() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
iconColor = overrideColor,
icon = { actualColor = LocalContentColor.current },
title = {},
message = {},
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_custom_icon_on_confirmation() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
iconColor = overrideColor,
icon = { actualColor = LocalContentColor.current },
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_title_onbackground_on_alert_for_buttons() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Alert(
title = { actualColor = LocalContentColor.current },
negativeButton = {},
positiveButton = {},
content = {},
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_title_onbackground_on_alert_for_chips() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Alert(
title = { actualColor = LocalContentColor.current },
message = {},
content = {},
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_title_onbackground_on_confirmation() {
var expectedColor = Color.Transparent
var actualColor = Color.Transparent
rule.setContentWithTheme {
expectedColor = MaterialTheme.colors.onBackground
Confirmation(
onTimeout = {},
content = { actualColor = LocalContentColor.current },
)
}
assertEquals(expectedColor, actualColor)
}
@Test
fun gives_custom_title_on_alert_for_buttons() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
titleColor = overrideColor,
title = { actualColor = LocalContentColor.current },
negativeButton = {},
positiveButton = {},
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_custom_title_on_alert_for_chips() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
titleColor = overrideColor,
title = { actualColor = LocalContentColor.current },
message = {},
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_custom_title_on_confirmation() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
contentColor = overrideColor,
content = { actualColor = LocalContentColor.current },
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_bodymessage_onbackground_on_alert_for_buttons() {
var expectedContentColor = Color.Transparent
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
expectedContentColor = MaterialTheme.colors.onBackground
Alert(
title = {},
negativeButton = {},
positiveButton = {},
content = { actualContentColor = LocalContentColor.current },
)
}
assertEquals(expectedContentColor, actualContentColor)
}
@Test
fun gives_bodymessage_onbackground_on_alert_for_chips() {
var expectedContentColor = Color.Transparent
var actualContentColor = Color.Transparent
rule.setContentWithTheme {
expectedContentColor = MaterialTheme.colors.onBackground
Alert(
title = {},
message = { actualContentColor = LocalContentColor.current },
content = {},
)
}
assertEquals(expectedContentColor, actualContentColor)
}
@Test
fun gives_custom_bodymessage_on_alert_for_buttons() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
title = {},
negativeButton = {},
positiveButton = {},
contentColor = overrideColor,
content = { actualColor = LocalContentColor.current },
)
}
assertEquals(overrideColor, actualColor)
}
@Test
fun gives_custom_bodymessage_on_alert_for_chips() {
val overrideColor = Color.Yellow
var actualColor = Color.Transparent
rule.setContentWithTheme {
Alert(
title = {},
messageColor = overrideColor,
message = { actualColor = LocalContentColor.current },
content = {},
)
}
assertEquals(overrideColor, actualColor)
}
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_correct_background_color_on_alert_for_buttons() {
verifyBackgroundColor(expected = { MaterialTheme.colors.background }) {
Alert(
title = {},
negativeButton = {},
positiveButton = {},
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_correct_background_color_on_alert_for_chips() {
verifyBackgroundColor(expected = { MaterialTheme.colors.background }) {
Alert(
title = {},
message = {},
content = {},
modifier = Modifier.testTag(TEST_TAG)
)
}
}
@RequiresApi(Build.VERSION_CODES.O)
@Test
fun gives_correct_background_color_on_confirmation() {
verifyBackgroundColor(expected = { MaterialTheme.colors.background }) {
Confirmation(
onTimeout = {},
content = {},
modifier = Modifier.testTag(TEST_TAG),
)
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun gives_custom_background_color_on_alert_for_buttons() {
val overrideColor = Color.Yellow
rule.setContentWithTheme {
Alert(
title = {},
negativeButton = {},
positiveButton = {},
content = {},
backgroundColor = overrideColor,
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(overrideColor, 100.0f)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun gives_custom_background_color_on_alert_for_chips() {
val overrideColor = Color.Yellow
rule.setContentWithTheme {
Alert(
title = {},
message = {},
content = {},
backgroundColor = overrideColor,
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(overrideColor, 100.0f)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun gives_custom_background_color_on_confirmation() {
val overrideColor = Color.Yellow
rule.setContentWithTheme {
Confirmation(
onTimeout = {},
content = {},
backgroundColor = overrideColor,
modifier = Modifier.testTag(TEST_TAG),
)
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(overrideColor, 100.0f)
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
private fun verifyBackgroundColor(
expected: @Composable () -> Color,
content: @Composable () -> Unit
) {
val testBackground = Color.White
var expectedBackground = Color.Transparent
rule.setContentWithTheme {
Box(modifier = Modifier.fillMaxSize().background(testBackground)) {
expectedBackground = expected()
content()
}
}
rule.onNodeWithTag(TEST_TAG)
.captureToImage()
.assertContainsColor(expectedBackground, 100.0f)
}
}
class DialogTextStyleTest {
@get:Rule
val rule = createComposeRule()
@Test
fun gives_title_correct_textstyle_on_alert_for_buttons() {
var actualTextStyle = TextStyle.Default
var expectedTextStyle = TextStyle.Default
rule.setContentWithTheme {
expectedTextStyle = MaterialTheme.typography.title3
Alert(
title = { actualTextStyle = LocalTextStyle.current },
negativeButton = {},
positiveButton = {},
)
}
assertEquals(expectedTextStyle, actualTextStyle)
}
@Test
fun gives_title_correct_textstyle_on_alert_for_chips() {
var actualTextStyle = TextStyle.Default
var expectedTextStyle = TextStyle.Default
rule.setContentWithTheme {
expectedTextStyle = MaterialTheme.typography.title3
Alert(
title = { actualTextStyle = LocalTextStyle.current },
message = {},
content = {},
)
}
assertEquals(expectedTextStyle, actualTextStyle)
}
@Test
fun gives_body_correct_textstyle_on_alert_for_buttons() {
var actualTextStyle = TextStyle.Default
var expectedTextStyle = TextStyle.Default
rule.setContentWithTheme {
expectedTextStyle = MaterialTheme.typography.body2
Alert(
title = { Text("Title") },
negativeButton = {},
positiveButton = {},
content = { actualTextStyle = LocalTextStyle.current }
)
}
assertEquals(expectedTextStyle, actualTextStyle)
}
@Test
fun gives_body_correct_textstyle_on_alert_for_chips() {
var actualTextStyle = TextStyle.Default
var expectedTextStyle = TextStyle.Default
rule.setContentWithTheme {
expectedTextStyle = MaterialTheme.typography.body2
Alert(
title = { Text("Title") },
message = { actualTextStyle = LocalTextStyle.current },
content = {},
)
}
assertEquals(expectedTextStyle, actualTextStyle)
}
@Test
fun gives_title_correct_textstyle_on_confirmation() {
var actualTextStyle = TextStyle.Default
var expectedTextStyle = TextStyle.Default
rule.setContentWithTheme {
expectedTextStyle = MaterialTheme.typography.title3
Confirmation(
onTimeout = {},
content = { actualTextStyle = LocalTextStyle.current },
)
}
assertEquals(expectedTextStyle, actualTextStyle)
}
}
| wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/dialog/DialogTest.kt | 2317523923 |
package de.droidcon.berlin2018.clock
import org.threeten.bp.Instant
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
/**
* The clock used to get the time of the system
*
* @author Hannes Dorfmann
*/
interface Clock {
/**
* Get the current time
*/
fun now(): Instant
/**
* Get the zone where the conference takes place
*/
fun getZoneConferenceTakesPlace(): ZoneId
/**
* now in the timezone the conference takes place
*/
fun nowInConferenceTimeZone(): LocalDateTime
}
| businesslogic/clock/src/main/java/de/droidcon/berlin2018/clock/Clock.kt | 840070319 |
package ii_collections
import java.util.HashSet
import util.TODO
/*
* This part of workshop was inspired by:
* https://github.com/goldmansachs/gs-collections-kata
*/
/*
* There are many operations that help to transform one collection into another, starting with 'to'
*/
fun example0(list: List<Int>) {
list.toSet()
val set = HashSet<Int>()
list.to(set)
}
fun Shop.getSetOfCustomers(): Set<Customer> {
// Return a set containing all the customers of this shop
return this.customers.toSet()
}
| src/ii_collections/_13_Introduction_.kt | 3149951653 |
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.database
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import org.andstatus.app.data.DbUtils
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.ActorEndpointTable
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.database.table.AudienceTable
import org.andstatus.app.database.table.CommandTable
import org.andstatus.app.database.table.DownloadTable
import org.andstatus.app.database.table.GroupMembersTable
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.database.table.OriginTable
import org.andstatus.app.database.table.TimelineTable
import org.andstatus.app.database.table.UserTable
import org.andstatus.app.util.MyLog
/**
* @author [email protected]
*/
class DatabaseCreator(private val db: SQLiteDatabase) {
/**
* On data types in SQLite see [Datatypes In SQLite Version 3](http://www.sqlite.org/datatype3.html).
* See also [SQLite Autoincrement](http://sqlite.org/autoinc.html).
*/
fun create(): DatabaseCreator {
MyLog.i(this, "Creating tables")
OriginTable.create(db)
NoteTable.create(db)
UserTable.create(db)
ActorTable.create(db)
AudienceTable.create(db)
GroupMembersTable.create(db)
DownloadTable.create(db)
TimelineTable.create(db)
ActivityTable.create(db)
CommandTable.create(db)
ActorEndpointTable.create(db)
return this
}
fun insertData() {
val sqlIns = ("INSERT INTO " + OriginTable.TABLE_NAME + " ("
+ BaseColumns._ID + ","
+ OriginTable.ORIGIN_TYPE_ID + ","
+ OriginTable.ORIGIN_NAME + ","
+ OriginTable.ORIGIN_URL + ","
+ OriginTable.SSL + ","
+ OriginTable.SSL_MODE + ","
+ OriginTable.ALLOW_HTML + ","
+ OriginTable.TEXT_LIMIT
+ ") VALUES ("
+ "%s"
+ ")")
val values = arrayOf<String>(
java.lang.Long.toString(ORIGIN_ID_TWITTER) +
", 1,'Twitter', 'https://api.twitter.com', 1, 1, 0, 280",
" 2, 2,'Pump.io', '', 1, 1, 1, 0", // turned off " 3, 3,'Quitter.se', 'https://quitter.se', 1, 1, 1, 0",
" 4, 3,'LoadAverage', 'https://loadaverage.org', 1, 1, 1, 0",
" 6, 3,'GNUsocial.de', 'https://gnusocial.de', 1, 1, 1, 0",
" 7, 3,'GNUsocial.no', 'https://gnusocial.no', 1, 1, 1, 0", // turned off " 8, 3,'Quitter.no', 'https://quitter.no', 1, 1, 1, 0",
" 9, 3,'Quitter.is', 'https://quitter.is', 1, 1, 1, 0",
"10, 3,'Quitter.Espana', 'https://quitter.es', 1, 1, 1, 0",
"11, 4,'Mastodon.social','https://mastodon.social', 1, 1, 1, 0",
"12, 4,'Mastodon.cloud', 'https://mastodon.cloud', 1, 1, 1, 0",
"13, 4,'mstdn.jp', 'https://mstdn.jp', 1, 1, 1, 0",
"14, 4,'Pawoo', 'https://pawoo.net', 1, 1, 1, 0",
"15, 4,'friends.nico', 'https://friends.nico', 1, 1, 1, 0",
"16, 4,'Mastodon.xyz', 'https://mastodon.xyz', 1, 1, 1, 0",
"17, 5,'ActivityPub', '', 1, 1, 1, 0"
)
for (value in values) {
DbUtils.execSQL(db, sqlIns.replace("%s", value))
}
}
companion object {
/**
* Current database scheme version, defined by AndStatus developers.
* This is used to check (and upgrade if necessary) existing database after application update.
*
* v.54 2020-04-13 Add timeline_position to ActivityTable.
* Fix type of endpoint_uri in ActorEndpointTable.
* v.51 2019-07-23 ActorTable holds Groups also. GroupMembersTable instead of FriendshipTable
* v.50 2019-05-26 Summary and "Sensitive" properties added. https://github.com/andstatus/andstatus/issues/507
* v.48 2019-04-21 Accounts renamed to: username@hostName/originTypeOrOriginName
* v.47 2019-02-24 Username for Pump.io and ActivityPub doesn't have "@host" anymore, but "uniqueNameInOrigin" does.
* Previews added to DownloadTable.
* v.44 2018-10-30 ActorEndpointTable added.
* v.42 2018-09-05 DownloadTable added (returned) "content_type" to filter attachments that can be shown
* v.40 2018-06-05 DownloadTable added "downloaded_date" to decide, when to prune the download
* v.38 2018-04-01 app.v.38 DownloadTable update to support Video. NoteTable - added Note's Name
* v.37 2018-02-19 app.v.37 UserTable added, one-to-many linked to ActorTable. Renaming fields.
* v.27 2017-11-04 app.v.36 Moving to ActivityStreams data model.
* ActivityTable and AudienceTable added, MsOfUserTable dropped. Others refactored.
* v.26 2016-11-27 app.v.31 Conversation ID added to MsgTable, see https://github.com/andstatus/andstatus/issues/361
* v.25 2016-06-07 app.v.27 TimelineTable and CommandTable added
* v.24 2016-02-27 app.v.23 several attributes added to User, https://github.com/andstatus/andstatus/issues/320
* v.23 2015-09-02 app.v.19 msg_status added for Unsent messages
* v.22 2015-04-04 app.v.17 use_legacy_http added to Origin
* v.21 2015-03-14 app.v.16 mention_as_webfinger_id added to Origin,
* index on [NoteTable.IN_REPLY_TO_NOTE_ID] added.
* v.20 2015-02-04 app.v.15 SslMode added to Origin
* v.19 2014-11-15 Index on sent date added to messages
* v.18 2014-09-21 Duplicated User.USERNAME allowed
* v.17 2014-09-05 Attachment added. Origin "URL" instead of "host"
* v.16 2014-05-03 Account persistence changed
* v.15 2014-02-16 Public timeline added
* v.14 2013-12-15 Origin table added
* v.13 2013-12-06 Avatar table added
* v.12 2013-08-30 Adapting for Pump.Io
* v.11 2013-05-18 FollowingUser table added. User table extended with a column
* to store the date the list of Following users was loaded.
* v.10 2013-03-23 User table extended with columns to store information on timelines loaded.
* v.9 2012-02-26 Totally new database design using table joins.
* All messages are in the same table.
* Allows to have multiple User Accounts in different Originating systems (twitter.com etc. )
*/
const val DATABASE_VERSION = 54
const val ORIGIN_ID_TWITTER = 1L
}
}
| app/src/main/kotlin/org/andstatus/app/database/DatabaseCreator.kt | 789511524 |
package me.proxer.app.news.widget
import android.os.Parcel
import android.os.Parcelable
import com.squareup.moshi.JsonClass
import me.proxer.app.util.extension.readStringSafely
import org.threeten.bp.Instant
/**
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class SimpleNews(
val id: String,
val threadId: String,
val categoryId: String,
val subject: String,
val category: String,
val date: Instant
) : Parcelable {
companion object {
@Suppress("unused")
@JvmField
val CREATOR = object : Parcelable.Creator<SimpleNews> {
override fun createFromParcel(parcel: Parcel) = SimpleNews(parcel)
override fun newArray(size: Int): Array<SimpleNews?> = arrayOfNulls(size)
}
}
constructor(parcel: Parcel) : this(
parcel.readStringSafely(),
parcel.readStringSafely(),
parcel.readStringSafely(),
parcel.readStringSafely(),
parcel.readStringSafely(),
Instant.ofEpochMilli(parcel.readLong())
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(id)
parcel.writeString(threadId)
parcel.writeString(categoryId)
parcel.writeString(subject)
parcel.writeString(category)
parcel.writeLong(date.toEpochMilli())
}
override fun describeContents() = 0
}
| src/main/kotlin/me/proxer/app/news/widget/SimpleNews.kt | 3662308560 |
package me.proxer.app.chat.prv.message
import androidx.lifecycle.MediatorLiveData
import com.gojuno.koptional.rxjava2.filterSome
import com.gojuno.koptional.toOptional
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import me.proxer.app.base.PagedViewModel
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.chat.prv.sync.MessengerErrorEvent
import me.proxer.app.chat.prv.sync.MessengerWorker
import me.proxer.app.exception.ChatMessageException
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.data.ResettingMutableLiveData
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
/**
* @author Ruben Gees
*/
class MessengerViewModel(initialConference: LocalConference) : PagedViewModel<LocalMessage>() {
override val isLoginRequired = true
override val itemsOnPage = MessengerWorker.MESSAGES_ON_PAGE
@Suppress("UNUSED_PARAMETER")
override var hasReachedEnd
get() = safeConference.isFullyLoaded
set(value) = Unit
override val data = MediatorLiveData<List<LocalMessage>>()
val conference = MediatorLiveData<LocalConference>()
val draft = ResettingMutableLiveData<String?>()
override val dataSingle: Single<List<LocalMessage>>
get() = Single.fromCallable { validators.validateLogin() }
.flatMap {
when (page) {
0 -> messengerDao.markConferenceAsRead(safeConference.id)
else -> if (!hasReachedEnd) MessengerWorker.enqueueMessageLoad(safeConference.id)
}
Single.never()
}
private val dataSource: (List<LocalMessage>?) -> Unit = {
if (it != null && storageHelper.isLoggedIn) {
if (it.isEmpty()) {
if (!hasReachedEnd) {
MessengerWorker.enqueueMessageLoad(safeConference.id)
}
} else {
if (error.value == null) {
dataDisposable?.dispose()
page = it.size / itemsOnPage
isLoading.value = false
error.value = null
data.value = it
Completable.fromAction { messengerDao.markConferenceAsRead(safeConference.id) }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
}
}
private val conferenceSource: (LocalConference?) -> Unit = {
if (it != null) conference.value = it
}
private val messengerDao by safeInject<MessengerDao>()
private val safeConference: LocalConference
get() = requireNotNull(conference.value)
private var draftDisposable: Disposable? = null
init {
conference.value = initialConference
data.addSource(messengerDao.getMessagesLiveDataForConference(initialConference.id), dataSource)
conference.addSource(messengerDao.getConferenceLiveData(initialConference.id), conferenceSource)
disposables += bus.register(MessengerErrorEvent::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { event: MessengerErrorEvent ->
if (event.error is ChatMessageException) {
dataDisposable?.dispose()
isLoading.value = false
error.value = ErrorUtils.handle(event.error)
}
}
}
override fun onCleared() {
draftDisposable?.dispose()
draftDisposable = null
super.onCleared()
}
fun loadDraft() {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable { storageHelper.getMessageDraft(safeConference.id.toString()).toOptional() }
.filterSome()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { draft.value = it }
}
fun updateDraft(draft: String) {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable {
if (draft.isBlank()) {
storageHelper.deleteMessageDraft(safeConference.id.toString())
} else {
storageHelper.putMessageDraft(safeConference.id.toString(), draft)
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
fun sendMessage(text: String) {
val safeUser = requireNotNull(storageHelper.user)
disposables += Single
.fromCallable { messengerDao.insertMessageToSend(safeUser, text, safeConference.id) }
.doOnSuccess { if (!MessengerWorker.isRunning) MessengerWorker.enqueueSynchronization() }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
| src/main/kotlin/me/proxer/app/chat/prv/message/MessengerViewModel.kt | 94422544 |
package com.github.nitrico.lastadapter_sample.ui
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.view.Menu
import android.view.MenuItem
import com.github.nitrico.lastadapter_sample.data.Data
import com.github.nitrico.lastadapter_sample.R
import com.github.nitrico.lastadapter_sample.data.Header
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val random = Random()
private var randomPosition: Int = 0
get() = random.nextInt(Data.items.size-1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
pager.adapter = ViewPagerAdapter(supportFragmentManager)
tabs.setupWithViewPager(pager)
}
override fun onCreateOptionsMenu(menu: Menu) = consume { menuInflater.inflate(R.menu.main, menu) }
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.addFirst -> consume {
Data.items.add(0, Header("New Header"))
}
R.id.addLast -> consume {
Data.items.add(Data.items.size, Header("New header"))
}
R.id.addRandom -> consume {
Data.items.add(randomPosition, Header("New Header"))
}
R.id.removeFirst -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(0)
}
R.id.removeLast -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(Data.items.size-1)
}
R.id.removeRandom -> consume {
if (Data.items.isNotEmpty()) Data.items.removeAt(randomPosition)
}
else -> super.onOptionsItemSelected(item)
}
private fun consume(f: () -> Unit): Boolean {
f()
return true
}
class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount() = 2
override fun getItem(i: Int) = if (i == 0) KotlinListFragment() else JavaListFragment()
override fun getPageTitle(i: Int) = if (i == 0) "Kotlin" else "Java"
}
}
| app/src/main/java/com/github/nitrico/lastadapter_sample/ui/MainActivity.kt | 1439707842 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.test.completion
class TestShouldBe : TestCompletionBase() {
fun `test issue #298`() {
doTest("""
--- test_issue_298.lua
---@overload fun(t:{aaa: string, bbb: string, ccc: string})
---@param aaa string
---@param bbb string
---@param ccc string
---@return number
function test(aaa, bbb, ccc)
end
test {
a--[[caret]]
}
""".trimIndent()) {
assertTrue("aaa = " in it)
}
}
} | src/test/kotlin/com/tang/intellij/test/completion/TestShouldBe.kt | 16300707 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api
import com.google.gson.JsonElement
internal fun interface ApiResponseParser<T> {
fun parseResponse(json: JsonElement): T
}
| api/src/main/java/com/vk/sdk/api/ApiResponseParser.kt | 3533496724 |
package com.nobrain.android.lottiefiles.repository.local.dao
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import com.nobrain.android.lottiefiles.repository.local.entities.Lottie
import io.reactivex.Flowable
import io.reactivex.Observable
@Dao
interface LottieDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(vararg item: Lottie)
@Delete
fun delete(vararg item: Lottie)
@Query("SELECT * FROM lottie")
fun getAll(): LiveData<List<Lottie>>
@Query("SELECT * FROM lottie ORDER BY id desc")
fun getAllOnRx(): Flowable<List<Lottie>>
@Query("SELECT * FROM lottie WHERE starred = 1")
fun getStarred(): List<Lottie>
@Query("SELECT COUNT(*) FROM lottie WHERE id = :id")
fun getCount(id:String) : Int
@Query("SELECT * FROM lottie WHERE title LIKE :keyword")
fun query(keyword: String) : Flowable<List<Lottie>>
} | app/src/main/kotlin/com/nobrain/android/lottiefiles/repository/local/dao/LottieDao.kt | 502537662 |
package reagent.source
import reagent.Task
internal class TaskJust<out I>(private val item: I) : Task<I>() {
override suspend fun produce() = item
}
| reagent/common/src/main/kotlin/reagent/source/TaskJust.kt | 3921925448 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.users.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
/**
* @param skype - User's Skype nickname
* @param facebook - User's Facebook account
* @param twitter - User's Twitter account
* @param instagram - User's Instagram account
* @param facebookName - User's Facebook name
* @param livejournal - User's Livejournal account
*/
data class UsersUserConnections(
@SerializedName("skype")
val skype: String,
@SerializedName("facebook")
val facebook: String,
@SerializedName("twitter")
val twitter: String,
@SerializedName("instagram")
val instagram: String,
@SerializedName("facebook_name")
val facebookName: String? = null,
@SerializedName("livejournal")
val livejournal: String? = null
)
| api/src/main/java/com/vk/sdk/api/users/dto/UsersUserConnections.kt | 731496754 |
package com.mxt.anitrend.view.fragment.detail
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.mxt.anitrend.BuildConfig
import com.mxt.anitrend.R
import com.mxt.anitrend.base.custom.fragment.FragmentBase
import com.mxt.anitrend.presenter.base.BasePresenter
import com.mxt.anitrend.util.DialogUtil
import mehdi.sakout.aboutpage.AboutPage
import mehdi.sakout.aboutpage.Element
/**
* Created by max on 2018/03/04.
* Application about screen
*/
class AboutFragment : FragmentBase<Void, BasePresenter, Void>() {
private val aboutPage by lazy(LazyThreadSafetyMode.NONE) {
AboutPage(activity)
.setImage(R.mipmap.ic_launcher)
.addGroup(getString(R.string.text_about_general_information))
.setDescription(getString(R.string.app_description))
.addItem(Element().setTitle(getString(R.string.text_about_appication_version, BuildConfig.VERSION_NAME)))
.addPlayStore("com.mxt.anitrend")
.addTwitter("anitrend_app")
.addGroup(getString(R.string.text_about_additional_information))
.addGitHub("AniTrend")
.addWebsite("https://anitrend.co")
.addItem(Element().setTitle(getString(R.string.text_what_is_new))
.setOnClickListener { DialogUtil.createChangeLog(activity) }
.setIconDrawable(R.drawable.ic_fiber_new_white_24dp))
.addItem(Element().setTitle(getString(R.string.text_about_frequently_asked_questions))
.setIconDrawable(R.drawable.ic_help_grey_600_24dp)
.setIntent(Intent(Intent.ACTION_VIEW,
Uri.parse(
"https://anitrend.gitbook.io/project/faq"
))))
.addGroup(getString(R.string.text_about_legal_information))
.addItem(Element().setTitle(getString(R.string.text_about_terms_and_conditions))
.setIconDrawable(R.drawable.ic_privacy_grey_600_24dp)
.setIntent(Intent(Intent.ACTION_VIEW,
Uri.parse(
"https://github.com/AniTrend/anitrend-app/blob/develop/TERMS_OF_SERVICE.md"
)
)))
.addItem(Element().setTitle(getString(R.string.text_about_code_of_conduct))
.setIconDrawable(R.drawable.ic_privacy_grey_600_24dp)
.setIntent(Intent(Intent.ACTION_VIEW,
Uri.parse(
"https://github.com/AniTrend/anitrend-app/blob/develop/CODE_OF_CONDUCT.md"
)
)))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setPresenter(BasePresenter(context))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return aboutPage.create()
}
override fun updateUI() {
}
override fun makeRequest() {
}
override fun onChanged(model: Void?) {
}
companion object {
fun newInstance(): AboutFragment {
return AboutFragment()
}
}
}
| app/src/main/java/com/mxt/anitrend/view/fragment/detail/AboutFragment.kt | 3264000294 |
package ktx.tiled
import com.badlogic.gdx.maps.MapLayer
import com.badlogic.gdx.maps.MapObject
import com.badlogic.gdx.maps.tiled.TiledMap
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
class TiledMapTest {
private val tiledMap = TiledMap().apply {
properties.apply {
put("width", 16)
put("height", 8)
put("tilewidth", 32)
put("tileheight", 32)
put("backgroundcolor", "#ffffff")
put("orientation", "orthogonal")
put("hexsidelength", 0)
put("staggeraxis", "Y")
put("staggerindex", "Odd")
}
layers.add(
MapLayer().apply {
name = "layer-1"
objects.apply {
add(MapObject())
add(MapObject())
add(MapObject())
}
}
)
layers.add(
MapLayer().apply {
name = "layer-2"
}
)
}
@Test
fun `should retrieve properties from TiledMap`() {
assertEquals(16, tiledMap.property<Int>("width"))
}
@Test
fun `should retrieve properties from TiledMap with default value`() {
assertEquals(16, tiledMap.property("width", 0))
assertEquals(-1, tiledMap.property("x", -1))
}
@Test
fun `should retrieve properties from TiledMap without default value`() {
assertNull(tiledMap.propertyOrNull("x"))
assertEquals(16, tiledMap.propertyOrNull<Int>("width"))
}
@Test
fun `should check if property from TiledMap exists`() {
assertTrue(tiledMap.containsProperty("width"))
assertFalse(tiledMap.containsProperty("x"))
}
@Test
fun `should retrieve standard properties of TiledMap`() {
assertEquals(16, tiledMap.width)
assertEquals(8, tiledMap.height)
assertEquals(32, tiledMap.tileWidth)
assertEquals(32, tiledMap.tileHeight)
assertEquals((16 * 32), tiledMap.totalWidth())
assertEquals((8 * 32), tiledMap.totalHeight())
assertEquals("#ffffff", tiledMap.backgroundColor)
assertEquals("orthogonal", tiledMap.orientation)
assertEquals(0, tiledMap.hexSideLength)
assertEquals("Y", tiledMap.staggerAxis)
assertEquals("Odd", tiledMap.staggerIndex)
}
@Test(expected = MissingPropertyException::class)
fun `should not retrieve non-existing property from TiledMap`() {
tiledMap.property<String>("non-existing")
}
@Test
fun `should retrieve existing layer from TiledMap`() {
assertEquals("layer-1", tiledMap.layer("layer-1").name)
}
@Test(expected = MissingLayerException::class)
fun `should not retrieve non-existing layer from TiledMap`() {
tiledMap.layer("non-existing")
}
@Test
fun `should check if layer exists in TiledMap`() {
assertTrue(tiledMap.contains("layer-1"))
assertFalse(tiledMap.contains("non-existing"))
assertTrue("layer-1" in tiledMap)
assertFalse("non-existing" in tiledMap)
}
@Test
fun `should execute action per object of a layer`() {
var counter = 0
tiledMap.forEachMapObject("layer-1") {
it.isVisible = false
counter++
}
assertEquals(3, counter)
assertTrue(tiledMap.layers["layer-1"].objects.all { !it.isVisible })
}
@Test
fun `should not execute any action for empty layer`() {
tiledMap.forEachMapObject("layer-2") {
fail()
}
}
@Test
fun `should not execute any action for non-existing layer`() {
tiledMap.forEachMapObject("non-existing") {
fail()
}
}
@Test
fun `should not execute lambda when there is no layer for the given type`() {
tiledMap.forEachLayer<TiledMapTileLayer> {
fail()
}
}
@Test
fun `should execute lambda when there is a layer for the given type`() {
var counter = 0
tiledMap.forEachLayer<MapLayer> {
it.isVisible = false
++counter
}
assertEquals(2, counter)
assertTrue(tiledMap.layers.all { !it.isVisible })
}
}
| tiled/src/test/kotlin/ktx/tiled/TiledMapTest.kt | 2508254549 |
package com.google.samples.snippet.kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.firebase.installations.FirebaseInstallations
import com.google.samples.snippet.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
logInstallationAuthToken()
logInstallationID()
}
private fun logInstallationAuthToken() {
// [START get_installation_token]
FirebaseInstallations.getInstance().getToken(/* forceRefresh */ true)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("Installations", "Installation auth token: " + task.result?.token)
} else {
Log.e("Installations", "Unable to get Installation auth token")
}
}
// [END get_installation_token]
}
private fun logInstallationID() {
// [START get_installation_id]
FirebaseInstallations.getInstance().id.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("Installations", "Installation ID: " + task.result)
} else {
Log.e("Installations", "Unable to get Installation ID")
}
}
// [END get_installation_id]
}
private fun deleteInstallation() {
// [START delete_installation]
FirebaseInstallations.getInstance().delete().addOnCompleteListener { task ->
if (task.isComplete) {
Log.d("Installations", "Installation deleted")
} else {
Log.e("Installations", "Unable to delete Installation")
}
}
// [END delete_installation]
}
}
| installations/app/src/main/java/com/google/samples/snippet/kotlin/MainActivity.kt | 3910353299 |
/*
* Copyright (C) 2018, 2020 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.psi.impl.plugin
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginNonDeterministicFunctionCall
class PluginNonDeterministicFunctionCallPsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node), PluginNonDeterministicFunctionCall, XpmSyntaxValidationElement {
// region XpmExpression
override val expressionElement: PsiElement
get() = children().filterIsInstance<XPathArgumentList>().first()
// endregion
// region XpmSyntaxValidationElement
override val conformanceElement: PsiElement
get() = firstChild
// endregion
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginNonDeterministicFunctionCallPsiImpl.kt | 1611303084 |
/*
* 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 `MapNodeTest` node in the XQuery AST.
*
* Because the child nodes of an `MapNodeTest` are only referenced
* from the `MapNodeTest` node in the grammar, the
* `MapNodeTest` nodes are stored as instances of the child nodes
* instead of as distinct nodes themselves.
*/
interface PluginMapNodeTest : XPathKindTest
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/plugin/PluginMapNodeTest.kt | 677959819 |
/*
* Copyright (C) 2016 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.xpath.psi.impl.xpath
import com.intellij.lang.ASTNode
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathAtomicType
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathSimpleTypeName
class XPathSimpleTypeNamePsiImpl(node: ASTNode) : XPathTypeNamePsiImpl(node), XPathSimpleTypeName, XPathAtomicType
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathSimpleTypeNamePsiImpl.kt | 1726891579 |
/*
* Copyright (C) 2020 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.xpm.psi.shadow
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlTag
import org.jetbrains.annotations.TestOnly
import uk.co.reecedunn.intellij.plugin.core.extensions.PluginDescriptorProvider
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtension
import uk.co.reecedunn.intellij.plugin.core.extensions.registerExtensionPointBean
import uk.co.reecedunn.intellij.plugin.core.xml.psi.qname
import javax.xml.namespace.QName
interface XpmShadowPsiElementFactory {
companion object {
val EP_NAME: ExtensionPointName<XpmShadowPsiElementFactoryBean> = ExtensionPointName.create(
"uk.co.reecedunn.intellij.shadowPsiElementFactory"
)
private val factories: Sequence<XpmShadowPsiElementFactoryBean>
get() = EP_NAME.extensionList.asSequence()
private val SHADOW_PSI_ELEMENT: Key<Pair<QName?, XpmShadowPsiElement>> = Key.create("SHADOW_PSI_ELEMENT")
fun create(element: PsiElement): XpmShadowPsiElement? {
val name = (element as? XmlTag)?.qname() ?: (element as? XmlAttribute)?.qname()
element.getUserData(SHADOW_PSI_ELEMENT)?.let {
if (it.first == name && it.second.isValid) {
return it.second
}
}
factories.map { it.getInstance().create(element, name) }.firstOrNull()?.let {
element.putUserData(SHADOW_PSI_ELEMENT, name to it)
return it
}
return factories.map { it.getInstance().createDefault(element) }.firstOrNull()?.let {
element.putUserData(SHADOW_PSI_ELEMENT, name to it)
return it
}
}
@TestOnly
@Suppress("UsePropertyAccessSyntax")
fun register(
plugin: PluginDescriptorProvider,
factory: XpmShadowPsiElementFactory,
fieldName: String = "INSTANCE"
) {
val bean = XpmShadowPsiElementFactoryBean()
bean.implementationClass = factory.javaClass.name
bean.fieldName = fieldName
bean.setPluginDescriptor(plugin.pluginDescriptor)
val app = ApplicationManager.getApplication()
app.registerExtensionPointBean(EP_NAME, XpmShadowPsiElementFactoryBean::class.java, plugin.pluginDisposable)
app.registerExtension(EP_NAME, bean, plugin.pluginDisposable)
}
}
fun create(element: PsiElement, name: QName?): XpmShadowPsiElement?
fun createDefault(element: PsiElement): XpmShadowPsiElement?
}
| src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/psi/shadow/XpmShadowPsiElementFactory.kt | 2570515006 |
package org.stepik.android.domain.course_revenue.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.domain.course_revenue.model.CourseBenefit
import java.util.Locale
class CourseBenefitClickedEvent(
benefitId: Long,
benefitStatus: CourseBenefit.Status,
courseId: Long,
courseTitle: String?
) : AnalyticEvent {
companion object {
private const val PARAM_BENEFIT = "benefit"
private const val PARAM_STATUS = "status"
private const val PARAM_COURSE = "course"
private const val PARAM_COURSE_TITLE = "course_title"
}
override val name: String =
"Course benefit clicked"
override val params: Map<String, Any> =
mapOf(
PARAM_BENEFIT to benefitId,
PARAM_STATUS to benefitStatus.name.toLowerCase(Locale.ROOT),
PARAM_COURSE to courseId,
PARAM_COURSE_TITLE to courseTitle.orEmpty()
)
} | app/src/main/java/org/stepik/android/domain/course_revenue/analytic/CourseBenefitClickedEvent.kt | 1986100210 |
package org.stepik.android.data.download.repository
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.toObservable
import org.stepic.droid.persistence.downloads.progress.mapper.DownloadProgressStatusMapper
import org.stepic.droid.persistence.model.DownloadItem
import org.stepic.droid.persistence.model.DownloadProgress
import org.stepic.droid.persistence.model.PersistentItem
import org.stepic.droid.persistence.model.PersistentState
import org.stepic.droid.persistence.model.Structure
import org.stepic.droid.persistence.model.SystemDownloadRecord
import org.stepic.droid.persistence.storage.dao.PersistentItemDao
import org.stepic.droid.persistence.storage.dao.SystemDownloadsDao
import ru.nobird.android.core.model.mapToLongArray
import org.stepic.droid.util.plus
import org.stepik.android.data.download.source.DownloadCacheDataSource
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.domain.download.repository.DownloadRepository
import org.stepik.android.model.Course
import org.stepik.android.view.injection.download.DownloadsProgressStatusMapper
import javax.inject.Inject
class DownloadRepositoryImpl
@Inject
constructor(
private val updatesObservable: Observable<Structure>,
private val intervalUpdatesObservable: Observable<Unit>,
private val systemDownloadsDao: SystemDownloadsDao,
private val persistentItemDao: PersistentItemDao,
private val courseRepository: CourseRepository,
@DownloadsProgressStatusMapper
private val downloadProgressStatusMapper: DownloadProgressStatusMapper,
private val downloadCacheDataSource: DownloadCacheDataSource
) : DownloadRepository {
override fun getDownloads(): Observable<DownloadItem> =
Observable
.merge(
downloadCacheDataSource
.getDownloadedCoursesIds()
.flatMapObservable { it.toObservable() },
updatesObservable
.map { it.course }
)
.flatMapSingle { courseId -> persistentItemDao.getItemsByCourse(courseId).map { courseId to it } }
.flatMap { (courseId, items) -> getDownloadItem(courseId, items) }
private fun getDownloadItem(courseId: Long, items: List<PersistentItem>): Observable<DownloadItem> =
(resolveCourse(courseId, items).toObservable() +
intervalUpdatesObservable
.switchMapSingle { persistentItemDao.getItemsByCourse(courseId) }
.switchMapSingle { resolveCourse(courseId, it) }
)
.takeUntil { it.status !is DownloadProgress.Status.InProgress }
private fun resolveCourse(courseId: Long, items: List<PersistentItem>): Single<DownloadItem> =
Singles.zip(
courseRepository.getCourse(courseId).toSingle(),
getStorageRecords(items)
) { course, records ->
resolveDownloadItem(course, items, records)
}
private fun getStorageRecords(items: List<PersistentItem>): Single<List<SystemDownloadRecord>> =
Single
.fromCallable { items.filter { it.status == PersistentItem.Status.IN_PROGRESS || it.status == PersistentItem.Status.FILE_TRANSFER } }
.flatMap { systemDownloadsDao.get(*it.mapToLongArray(PersistentItem::downloadId)) }
private fun resolveDownloadItem(course: Course, items: List<PersistentItem>, records: List<SystemDownloadRecord>): DownloadItem =
DownloadItem(course, downloadProgressStatusMapper.countItemProgress(items, records, PersistentState.State.CACHED))
} | app/src/main/java/org/stepik/android/data/download/repository/DownloadRepositoryImpl.kt | 2959245698 |
package br.com.edsilfer.kotlin_support.service.communication
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import javax.activation.DataSource
/**
* Created by efernandes on 06/12/16.
*/
class ByteArrayDataSource(data: ByteArray, type: String) : DataSource {
private var data: ByteArray? = data
private var type: String? = type
override fun getContentType(): String {
if (type == null)
return EmailManager.ARG_CONTENT_TYPE
else
return type!!
}
@Throws(IOException::class)
override fun getInputStream(): InputStream {
return ByteArrayInputStream(data)
}
override fun getName(): String {
return EmailManager.ARG_NAME
}
@Throws(IOException::class)
override fun getOutputStream(): OutputStream {
throw IOException("Not Supported")
}
}
| kotlin-support/src/main/java/br/com/edsilfer/kotlin_support/service/communication/ByteArrayDataSource.kt | 3568991322 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.target.util
import android.os.Looper
import android.view.MotionEvent
import androidx.tracing.Trace
import curtains.Curtains
import curtains.OnRootViewAddedListener
import curtains.OnTouchEventListener
import curtains.phoneWindow
import curtains.touchEventInterceptors
import curtains.windowAttachCount
/**
* Logs async trace sections that track the duration of click handling in the app, i.e. the
* duration from MotionEvent.ACTION_UP to OnClick callbacks.
*/
object ClickTrace {
private const val SECTION_NAME = "ClickTrace"
private var clickInProgress = false
private val isMainThread: Boolean get() = Looper.getMainLooper().thread === Thread.currentThread()
/**
* Ends a trace started when a ACTION_UP motion event was received.
*/
fun onClickPerformed() {
Trace.endAsyncSection(SECTION_NAME, 0)
checkMainThread()
clickInProgress = false
}
/**
* Leverages the [Curtains] library to intercept all ACTION_UP motion events sent to all
* windows in the app, starting an async trace that will end when [onClickPerformed] is called.
*/
fun install() {
checkMainThread()
// Listen to every new attached root view.
Curtains.onRootViewsChangedListeners += OnRootViewAddedListener { rootView ->
// If a root is attached, detached and reattached we don't want to do this again.
if (rootView.windowAttachCount == 0) {
// Not all root views have a window associated to them.
rootView.phoneWindow?.let { window ->
// Adds a touch event interceptor to the window callback
window.touchEventInterceptors += OnTouchEventListener { event ->
if (event.action == MotionEvent.ACTION_UP) {
Trace.beginAsyncSection(SECTION_NAME, 0)
clickInProgress = true
}
}
}
}
}
}
private fun checkMainThread() {
check(isMainThread) {
"Should be called from the main thread, not ${Thread.currentThread()}"
}
}
} | MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/util/ClickTrace.kt | 3886911831 |
package com.apollographql.apollo3.internal
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.Query
import com.apollographql.apollo3.api.ResponseField
import com.apollographql.apollo3.api.cache.http.HttpCachePolicy
import com.apollographql.apollo3.api.cache.http.HttpCachePolicy.FetchStrategy
import com.apollographql.apollo3.api.json.JsonWriter
import com.apollographql.apollo3.fetcher.ApolloResponseFetchers
import com.google.common.truth.Truth
import okhttp3.OkHttpClient
import org.junit.Test
class ResponseFetcherTest {
private val emptyQuery = object : Query<Query.Data> {
var operationName: String ="emptyQuery"
override fun document(): String {
return ""
}
override fun serializeVariables(writer: JsonWriter, responseAdapterCache: ResponseAdapterCache) {
writer.beginObject()
writer.endObject()
}
override fun adapter() = throw UnsupportedOperationException()
override fun name(): String {
return operationName
}
override fun id(): String {
return ""
}
override fun responseFields(): List<ResponseField.FieldSet> {
return emptyList()
}
}
@Test
fun setDefaultCachePolicy() {
val apolloClient = ApolloClient.builder()
.serverUrl("http://google.com")
.okHttpClient(OkHttpClient())
.defaultHttpCachePolicy(HttpCachePolicy.CACHE_ONLY)
.defaultResponseFetcher(ApolloResponseFetchers.NETWORK_ONLY)
.build()
val realApolloCall = apolloClient.query(emptyQuery) as RealApolloCall<*>
Truth.assertThat(realApolloCall.httpCachePolicy!!.fetchStrategy).isEqualTo(FetchStrategy.CACHE_ONLY)
Truth.assertThat(realApolloCall.responseFetcher).isEqualTo(ApolloResponseFetchers.NETWORK_ONLY)
}
@Test
fun defaultCacheControl() {
val apolloClient = ApolloClient.builder()
.serverUrl("http://google.com")
.okHttpClient(OkHttpClient())
.build()
val realApolloCall = apolloClient.query(emptyQuery) as RealApolloCall<*>
Truth.assertThat(realApolloCall.httpCachePolicy!!.fetchStrategy).isEqualTo(FetchStrategy.NETWORK_ONLY)
Truth.assertThat(realApolloCall.responseFetcher).isEqualTo(ApolloResponseFetchers.CACHE_FIRST)
}
}
| apollo-runtime/src/test/java/com/apollographql/apollo3/internal/ResponseFetcherTest.kt | 4180139746 |
package com.apollographql.apollo3.integration
import java.io.File
import java.io.FileNotFoundException
actual fun readFile(path: String): String {
return File(path).readText()
}
actual fun checkTestFixture(actualText: String, name: String) {
val expectedText = try {
readTestFixture(name)
} catch (e: FileNotFoundException) {
println("$name is not found do not throw here as we can update the fixtures below")
""
}
val expected = File("../integration-tests/testFixtures/$name")
expected.parentFile.mkdirs()
if (actualText != expectedText) {
when (System.getProperty("updateTestFixtures")?.trim()) {
"on", "true", "1" -> {
expected.writeText(actualText)
}
else -> {
throw java.lang.Exception("""generatedText doesn't match the expectedText.
|If you changed the compiler recently, you need to update the testFixtures.
|Run the tests with `-DupdateTestFixtures=true` to do so.
|generatedText: $actualText
|expectedText : $expectedText""".trimMargin())
}
}
}
}
| composite/integration-tests-kotlin/src/jvmTest/kotlin/com/apollographql/apollo3/integration/Platform.kt | 4201753085 |
package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
@Database(
entities = [HistoryRecordEntity::class],
exportSchema = false,
version = DashHistoryDatabase.VERSION
)
@TypeConverters(Converters::class)
abstract class DashHistoryDatabase : RoomDatabase() {
abstract fun historyRecordDao(): HistoryRecordDao
companion object {
const val VERSION = 3
fun build(context: Context) =
Room.databaseBuilder(
context.applicationContext,
DashHistoryDatabase::class.java,
"omnipod_dash_history_database.db",
)
.fallbackToDestructiveMigration()
.build()
}
}
| omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt | 1790821249 |
package abi42_0_0.expo.modules.permissions.requesters
import android.os.Bundle
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.CAN_ASK_AGAIN_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.EXPIRES_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.GRANTED_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.PERMISSION_EXPIRES_NEVER
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.STATUS_KEY
import abi42_0_0.expo.modules.interfaces.permissions.PermissionsStatus
/**
* Used for representing CAMERA, CONTACTS, AUDIO_RECORDING, SMS
*/
class SimpleRequester(vararg val permission: String) : PermissionRequester {
override fun getAndroidPermissions(): List<String> = permission.toList()
override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return Bundle().apply {
// combined status is equal:
// granted when all needed permissions have been granted
// denied when all needed permissions have been denied
// undetermined if exist permission with undetermined status
val permissionsStatus = when {
getAndroidPermissions().all { permissionsResponse.getValue(it).status == PermissionsStatus.GRANTED } -> PermissionsStatus.GRANTED
getAndroidPermissions().all { permissionsResponse.getValue(it).status == PermissionsStatus.DENIED } -> PermissionsStatus.DENIED
else -> PermissionsStatus.UNDETERMINED
}
putString(STATUS_KEY, permissionsStatus.status)
putString(EXPIRES_KEY, PERMISSION_EXPIRES_NEVER)
putBoolean(CAN_ASK_AGAIN_KEY, getAndroidPermissions().all { permissionsResponse.getValue(it).canAskAgain })
putBoolean(GRANTED_KEY, permissionsStatus == PermissionsStatus.GRANTED)
}
}
}
| android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/permissions/requesters/SimpleRequester.kt | 1032300037 |
package info.nightscout.androidaps.plugins.general.automation.elements
import android.content.Context
import android.graphics.Typeface
import android.text.format.DateFormat
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.interfaces.ResourceHelper
import java.util.*
class InputDateTime(private val rh: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() {
override fun addToLayout(root: LinearLayout) {
val px = rh.dpToPx(10)
root.addView(
LinearLayout(root.context).apply {
orientation = LinearLayout.HORIZONTAL
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addView(
TextView(root.context).apply {
text = rh.gs(R.string.atspecifiedtime, "")
setTypeface(typeface, Typeface.BOLD)
setPadding(px, px, px, px)
})
addView(
TextView(root.context).apply {
text = dateUtil.dateString(value)
setPadding(px, px, px, px)
setOnClickListener {
getFragmentManager(root.context)?.let { fm ->
MaterialDatePicker.Builder.datePicker()
.setTheme(R.style.DatePicker)
.setSelection(dateUtil.timeStampToUtcDateMillis(value))
.build()
.apply {
addOnPositiveButtonClickListener { selection ->
value = dateUtil.mergeUtcDateToTimestamp(value, selection)
text = dateUtil.dateString(value)
}
}
.show(fm, "input_date_picker")
}
}
})
addView(
TextView(root.context).apply {
text = dateUtil.timeString(value)
setPadding(px, px, px, px)
setOnClickListener {
getFragmentManager(root.context)?.let { fm ->
val cal = Calendar.getInstance().apply { timeInMillis = value }
val clockFormat = if (DateFormat.is24HourFormat(context)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H
val timePicker = MaterialTimePicker.Builder()
.setTheme(R.style.TimePicker)
.setTimeFormat(clockFormat)
.setHour(cal.get(Calendar.HOUR_OF_DAY))
.setMinute(cal.get(Calendar.MINUTE))
.build()
timePicker.addOnPositiveButtonClickListener {
value = dateUtil.mergeHourMinuteToTimestamp(value, timePicker.hour, timePicker.minute)
text = dateUtil.timeString(value)
}
timePicker.show(fm, "input_time_picker")
}
}
}
)
})
}
private fun getFragmentManager(context: Context?): FragmentManager? {
return when (context) {
is AppCompatActivity -> context.supportFragmentManager
is ContextThemeWrapper -> getFragmentManager(context.baseContext)
else -> null
}
}
}
| automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt | 1135203629 |
package arcs.showcase.queries
import arcs.jvm.host.TargetHost
typealias Product = AbstractProductDatabase.Product
/**
* This particle generates dummy data that is used in testing queries.
* @see ProductClassifier
*/
@TargetHost(arcs.android.integration.IntegrationHost::class)
class ProductDatabase : AbstractProductDatabase() {
override fun onFirstStart() {
handles.products.storeAll(
listOf(
Product(name = "Pencil", price = 2.5),
Product(name = "Ice cream", price = 3.0),
Product(name = "Chocolate", price = 3.0),
Product(name = "Blueberries", price = 4.0),
Product(name = "Sandwich", price = 4.50),
Product(name = "Scarf", price = 20.0),
Product(name = "Hat", price = 25.0),
Product(name = "Stop sign", price = 100.0)
)
)
}
}
| javatests/arcs/showcase/queries/ProductDatabase.kt | 3284364982 |
package biz.eventually.atpl.di.module
import android.arch.persistence.room.Room
import android.content.Context
import android.os.Debug
import biz.eventually.atpl.data.DataProvider
import biz.eventually.atpl.data.dao.*
import biz.eventually.atpl.ui.questions.QuestionRepository
import biz.eventually.atpl.ui.source.SourceRepository
import biz.eventually.atpl.ui.subject.SubjectRepository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Created by Thibault de Lambilly on 17/10/17.
*/
@Module
class DatabaseModule {
@Singleton
@Provides
fun provideDatabase(context: Context) : AppDatabase {
val builder = Room.databaseBuilder(context, AppDatabase::class.java, "aeroknow.db").fallbackToDestructiveMigration()
// if (Debug.isDebuggerConnected()) {
// builder.allowMainThreadQueries()
// }
return builder.build()
}
/**
* Dao
*/
@Singleton
@Provides
fun provideSourceDao(db: AppDatabase) : SourceDao = db.sourceDao()
@Singleton
@Provides
fun provideSubjectDao(db: AppDatabase) : SubjectDao = db.subjectDao()
@Singleton
@Provides
fun provideTopicDao(db: AppDatabase) : TopicDao = db.topicDao()
@Singleton
@Provides
fun provideQuestionDao(db: AppDatabase) : QuestionDao = db.questionDao()
@Singleton
@Provides
fun provideLastCallDao(db: AppDatabase) : LastCallDao = db.lastCallDao()
/**
* Repositories
*/
@Singleton
@Provides
fun provideSourceRepository(dataProvider: DataProvider, dao: SourceDao, lastDao: LastCallDao): SourceRepository =
SourceRepository(dataProvider, dao, lastDao)
@Singleton
@Provides
fun provideSubjectRepository(dataProvider: DataProvider, dao: SubjectDao,tDao: TopicDao, lastDao: LastCallDao): SubjectRepository =
SubjectRepository(dataProvider, dao, tDao, lastDao)
@Singleton
@Provides
fun provideQuestionRepository(dataProvider: DataProvider, dao: QuestionDao, lastDao: LastCallDao): QuestionRepository =
QuestionRepository(dataProvider, dao, lastDao)
} | app/src/main/java/biz/eventually/atpl/di/module/DatabaseModule.kt | 10874724 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import icons.JetgroovyIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter.*
import javax.swing.Icon
class GroovyColorSettingsPage : ColorSettingsPage {
private companion object {
val attributes = mapOf(
"Annotations//Annotation attribute name" to ANNOTATION_ATTRIBUTE_NAME,
"Annotations//Annotation name" to ANNOTATION,
"Braces and Operators//Braces" to BRACES,
"Braces and Operators//Closure expression braces and arrow" to CLOSURE_ARROW_AND_BRACES,
"Braces and Operators//Lambda expression braces and arrow " to LAMBDA_ARROW_AND_BRACES,
"Braces and Operators//Brackets" to BRACKETS,
"Braces and Operators//Parentheses" to PARENTHESES,
"Braces and Operators//Operator sign" to OPERATION_SIGN,
"Comments//Line comment" to LINE_COMMENT,
"Comments//Block comment" to BLOCK_COMMENT,
"Comments//Groovydoc//Text" to DOC_COMMENT_CONTENT,
"Comments//Groovydoc//Tag" to DOC_COMMENT_TAG,
"Classes and Interfaces//Class" to CLASS_REFERENCE,
"Classes and Interfaces//Abstract class" to ABSTRACT_CLASS_NAME,
"Classes and Interfaces//Anonymous class" to ANONYMOUS_CLASS_NAME,
"Classes and Interfaces//Interface" to INTERFACE_NAME,
"Classes and Interfaces//Trait" to TRAIT_NAME,
"Classes and Interfaces//Enum" to ENUM_NAME,
"Classes and Interfaces//Type parameter" to TYPE_PARAMETER,
"Methods//Method declaration" to METHOD_DECLARATION,
"Methods//Constructor declaration" to CONSTRUCTOR_DECLARATION,
"Methods//Instance method call" to METHOD_CALL,
"Methods//Static method call" to STATIC_METHOD_ACCESS,
"Methods//Constructor call" to CONSTRUCTOR_CALL,
"Fields//Instance field" to INSTANCE_FIELD,
"Fields//Static field" to STATIC_FIELD,
"Variables and Parameters//Local variable" to LOCAL_VARIABLE,
"Variables and Parameters//Reassigned local variable" to REASSIGNED_LOCAL_VARIABLE,
"Variables and Parameters//Parameter" to PARAMETER,
"Variables and Parameters//Reassigned parameter" to REASSIGNED_PARAMETER,
"References//Instance property reference" to INSTANCE_PROPERTY_REFERENCE,
"References//Static property reference" to STATIC_PROPERTY_REFERENCE,
"References//Unresolved reference" to UNRESOLVED_ACCESS,
"Strings//String" to STRING,
"Strings//GString" to GSTRING,
"Strings//Valid string escape" to VALID_STRING_ESCAPE,
"Strings//Invalid string escape" to INVALID_STRING_ESCAPE,
"Keyword" to KEYWORD,
"Number" to NUMBER,
"Bad character" to BAD_CHARACTER,
"List/map to object conversion" to LITERAL_CONVERSION,
"Map key/Named argument" to MAP_KEY,
"Label" to LABEL
).map { AttributesDescriptor(it.key, it.value) }.toTypedArray()
val additionalTags = mapOf(
"annotation" to ANNOTATION,
"annotationAttribute" to ANNOTATION_ATTRIBUTE_NAME,
"groovydoc" to DOC_COMMENT_CONTENT,
"groovydocTag" to DOC_COMMENT_TAG,
"class" to CLASS_REFERENCE,
"abstractClass" to ABSTRACT_CLASS_NAME,
"anonymousClass" to ANONYMOUS_CLASS_NAME,
"interface" to INTERFACE_NAME,
"trait" to TRAIT_NAME,
"enum" to ENUM_NAME,
"typeParameter" to TYPE_PARAMETER,
"method" to METHOD_DECLARATION,
"constructor" to CONSTRUCTOR_DECLARATION,
"instanceMethodCall" to METHOD_CALL,
"staticMethodCall" to STATIC_METHOD_ACCESS,
"constructorCall" to CONSTRUCTOR_CALL,
"instanceField" to INSTANCE_FIELD,
"staticField" to STATIC_FIELD,
"localVariable" to LOCAL_VARIABLE,
"reassignedVariable" to REASSIGNED_LOCAL_VARIABLE,
"parameter" to PARAMETER,
"reassignedParameter" to REASSIGNED_PARAMETER,
"instanceProperty" to INSTANCE_PROPERTY_REFERENCE,
"staticProperty" to STATIC_PROPERTY_REFERENCE,
"unresolved" to UNRESOLVED_ACCESS,
"keyword" to KEYWORD,
"literalConstructor" to LITERAL_CONVERSION,
"mapKey" to MAP_KEY,
"label" to LABEL,
"validEscape" to VALID_STRING_ESCAPE,
"invalidEscape" to INVALID_STRING_ESCAPE,
"closureBraces" to CLOSURE_ARROW_AND_BRACES,
"lambdaBraces" to LAMBDA_ARROW_AND_BRACES
)
}
override fun getDisplayName(): String = GroovyBundle.message("language.groovy")
override fun getIcon(): Icon = JetgroovyIcons.Groovy.Groovy_16x16
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter(): GroovySyntaxHighlighter = GroovySyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> = additionalTags
@NonNls
override fun getDemoText(): String = """<keyword>package</keyword> highlighting
###
<groovydoc>/**
* This is Groovydoc comment
* <groovydocTag>@see</groovydocTag> java.lang.String#equals
*/</groovydoc>
<annotation>@Annotation</annotation>(<annotationAttribute>parameter</annotationAttribute> = 'value')
<keyword>class</keyword> <class>C</class> {
<keyword>def</keyword> <instanceField>property</instanceField> = <keyword>new</keyword> <anonymousClass>I</anonymousClass>() {}
<keyword>static</keyword> <keyword>def</keyword> <staticField>staticProperty</staticField> = []
<constructor>C</constructor>() {}
<keyword>def</keyword> <<typeParameter>T</typeParameter>> <typeParameter>T</typeParameter> <method>instanceMethod</method>(T <parameter>parameter</parameter>, <reassignedParameter>reassignedParameter</reassignedParameter>) {
<reassignedParameter>reassignedParameter</reassignedParameter> = 1
//This is a line comment
<keyword>return</keyword> <parameter>parameter</parameter>
}
<keyword>def</keyword> <method>getStuff</method>() { 42 }
<keyword>static</keyword> <keyword>boolean</keyword> <method>isStaticStuff</method>() { true }
<keyword>static</keyword> <keyword>def</keyword> <method>staticMethod</method>(<keyword>int</keyword> <parameter>i</parameter>) {
/* This is a block comment */
<interface>Map</interface> <localVariable>map</localVariable> = [<mapKey>key1</mapKey>: 1, <mapKey>key2</mapKey>: 2, (22): 33]
<keyword>def</keyword> <localVariable>cl</localVariable> = <closureBraces>{</closureBraces> <parameter>a</parameter> <closureBraces>-></closureBraces> <parameter>a</parameter> <closureBraces>}</closureBraces>
<keyword>def</keyword> <localVariable>lambda</localVariable> = <parameter>b</parameter> <lambdaBraces>-></lambdaBraces> <lambdaBraces>{</lambdaBraces> <parameter>b</parameter> <lambdaBraces>}</lambdaBraces>
<class>File</class> <localVariable>f</localVariable> = <literalConstructor>[</literalConstructor>'path'<literalConstructor>]</literalConstructor>
<keyword>def</keyword> <reassignedVariable>a</reassignedVariable> = 'JetBrains'.<instanceMethodCall>matches</instanceMethodCall>(/Jw+Bw+/)
<label>label</label>:
<keyword>for</keyword> (<localVariable>entry</localVariable> <keyword>in</keyword> <localVariable>map</localVariable>) {
<keyword>if</keyword> (<localVariable>entry</localVariable>.value > 1 && <parameter>i</parameter> < 2) {
<reassignedVariable>a</reassignedVariable> = <unresolved>unresolvedReference</unresolved>
<keyword>continue</keyword> label
} <keyword>else</keyword> {
<reassignedVariable>a</reassignedVariable> = <localVariable>entry</localVariable>
}
}
<instanceMethodCall>print</instanceMethodCall> <localVariable>map</localVariable>.<mapKey>key1</mapKey>
}
}
<keyword>def</keyword> <localVariable>c</localVariable> = <keyword>new</keyword> <constructorCall>C</constructorCall>()
<localVariable>c</localVariable>.<instanceMethodCall>instanceMethod</instanceMethodCall>("Hello<validEscape>\n</validEscape>", 'world<invalidEscape>\x</invalidEscape>')
<instanceMethodCall>println</instanceMethodCall> <localVariable>c</localVariable>.<instanceProperty>stuff</instanceProperty>
<class>C</class>.<staticMethodCall>staticMethod</staticMethodCall>(<mapKey>namedArg</mapKey>: 1)
<class>C</class>.<staticProperty>staticStuff</staticProperty>
<keyword>abstract</keyword> <keyword>class</keyword> <abstractClass>AbstractClass</abstractClass> {}
<keyword>interface</keyword> <interface>I</interface> {}
<keyword>trait</keyword> <trait>T</trait> {}
<keyword>enum</keyword> <enum>E</enum> {}
@<keyword>interface</keyword> <annotation>Annotation</annotation> {
<class>String</class> <method>parameter</method>()
}
"""
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovyColorSettingsPage.kt | 1109194343 |
package arcs.android.storage
import arcs.android.util.decodeProto
/** Decodes a [StorageServiceMessageProto] from the [ByteArray]. */
fun ByteArray.decodeStorageServiceMessageProto(): StorageServiceMessageProto {
return decodeProto(this, StorageServiceMessageProto.getDefaultInstance())
}
| java/arcs/android/storage/StorageServiceMessageProto.kt | 3324458091 |
package com.johnny.gank.main
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.alibaba.sdk.android.feedback.impl.FeedbackAPI
import com.google.android.material.navigation.NavigationView
import com.johnny.gank.R
import com.johnny.gank.about.AboutActivity
import com.johnny.gank.search.SearchActivity
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import org.jetbrains.anko.startActivity
/**
* @author Johnny Shieh
* @version 1.0
*/
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener
{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
replaceFragment(R.id.fragment_container, TodayGankFragment(), TodayGankFragment.TAG)
}
override fun onResume() {
super.onResume()
MobclickAgent.onResume(this)
}
override fun onPause() {
super.onPause()
MobclickAgent.onPause(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_search) {
startActivity(SearchActivity.newIntent(this))
return true
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.nav_today -> {
if(null == supportFragmentManager.findFragmentByTag(TodayGankFragment.TAG)) {
replaceFragment(R.id.fragment_container, TodayGankFragment(), TodayGankFragment.TAG)
setTitle(R.string.app_name)
}
}
R.id.nav_welfare -> {
if(null == supportFragmentManager.findFragmentByTag(WelfareFragment.TAG)) {
replaceFragment(R.id.fragment_container, WelfareFragment(), WelfareFragment.TAG)
setTitle(R.string.nav_welfare)
}
}
R.id.nav_android -> {
if(null == supportFragmentManager.findFragmentByTag(AndroidFragment.TAG)) {
replaceFragment(R.id.fragment_container, AndroidFragment(), AndroidFragment.TAG)
setTitle(R.string.nav_android)
}
}
R.id.nav_ios -> {
if(null == supportFragmentManager.findFragmentByTag(IOSFragment.TAG)) {
replaceFragment(R.id.fragment_container, IOSFragment(), IOSFragment.TAG)
setTitle(R.string.nav_ios)
}
}
R.id.nav_front_end -> {
if(null == supportFragmentManager.findFragmentByTag(FrontEndFragment.TAG)) {
replaceFragment(R.id.fragment_container, FrontEndFragment(), FrontEndFragment.TAG)
setTitle(R.string.nav_front_end)
}
}
R.id.nav_video -> {
if(null == supportFragmentManager.findFragmentByTag(VideoFragment.TAG)) {
replaceFragment(R.id.fragment_container, VideoFragment(), VideoFragment.TAG)
setTitle(R.string.nav_video)
}
}
R.id.nav_about -> {
startActivity<AboutActivity>()
}
R.id.nav_feedback -> {
startFeedbackActivity()
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
private fun replaceFragment(containerViewId: Int, fragment: Fragment, tag: String) {
if (null == supportFragmentManager.findFragmentByTag(tag)) {
supportFragmentManager.beginTransaction()
.replace(containerViewId, fragment, tag)
.commit()
}
}
private fun startFeedbackActivity() {
val uiCustomInfoMap = mutableMapOf<String, String>()
uiCustomInfoMap.plus("enableAudio" to "0")
uiCustomInfoMap.plus("themeColor" to "#00acc1")
uiCustomInfoMap.plus("hideLoginSuccess" to "true")
uiCustomInfoMap.plus("pageTitle" to getString(R.string.nav_feedback))
FeedbackAPI.setUICustomInfo(uiCustomInfoMap)
FeedbackAPI.setCustomContact("Contact", true)
FeedbackAPI.openFeedbackActivity(this)
}
}
| app/src/main/kotlin/com/johnny/gank/main/MainActivity.kt | 3965952167 |
package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
import java.util.*
class Day05 : Day(title = "Alchemical Reduction") {
override fun first(input: Sequence<String>): Any =
input.head
.run { collapsed(initialStackSize = length) }
.size
override fun second(input: Sequence<String>): Any = input.head
.collapsed()
.joinToString("")
.let { newPolymer ->
('a'..'z')
.asSequence()
.filter { it in newPolymer || it.toUpperCase() in newPolymer }
.map { c -> newPolymer.collapsed(c, newPolymer.length).size }
.min() ?: throw IllegalStateException()
}
private fun Char.oppositeOf(other: Char?): Boolean =
other?.minus(this) == 32 || other?.minus(this) == -32
private fun String.collapsed(lowerCaseBadChar: Char? = null, initialStackSize: Int = 10000) =
this.fold(ArrayDeque<Char>(initialStackSize)) { stack, current ->
when {
lowerCaseBadChar != null && current.toLowerCase() == lowerCaseBadChar -> Unit
current.oppositeOf(stack.peek()) -> stack.removeFirst()
else -> stack.addFirst(current)
}
stack
}
}
| aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day05.kt | 2676849899 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.listener
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.motion.select.SelectToggleVisualMode
import com.maddyhome.idea.vim.group.visual.VimVisualTimer
import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.newapi.vim
/**
* A collection of hacks to improve the interaction with fancy AppCode templates
*/
object AppCodeTemplates {
private val facedAppCodeTemplate = Key.create<IntRange>("FacedAppCodeTemplate")
private const val TEMPLATE_START = "<#T##"
private const val TEMPLATE_END = "#>"
class ActionListener : AnActionListener {
private var editor: Editor? = null
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
if (!VimPlugin.isEnabled()) return
val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR)
if (hostEditor != null) {
editor = hostEditor
}
}
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
if (!VimPlugin.isEnabled()) return
if (ActionManager.getInstance().getId(action) == IdeActions.ACTION_CHOOSE_LOOKUP_ITEM) {
val myEditor = editor
if (myEditor != null) {
VimVisualTimer.doNow()
if (myEditor.inVisualMode) {
SelectToggleVisualMode.toggleMode(myEditor.vim)
KeyHandler.getInstance().partialReset(myEditor.vim)
}
}
}
}
}
@JvmStatic
fun onMovement(
editor: Editor,
caret: Caret,
toRight: Boolean,
) {
val offset = caret.offset
val offsetRightEnd = offset + TEMPLATE_START.length
val offsetLeftEnd = offset - 1
val templateRange = caret.getUserData(facedAppCodeTemplate)
if (templateRange == null) {
if (offsetRightEnd < editor.fileSize &&
editor.document.charsSequence.subSequence(offset, offsetRightEnd).toString() == TEMPLATE_START
) {
caret.shake()
val templateEnd = editor.findTemplateEnd(offset) ?: return
caret.putUserData(facedAppCodeTemplate, offset..templateEnd)
}
if (offsetLeftEnd >= 0 &&
offset + 1 <= editor.fileSize &&
editor.document.charsSequence.subSequence(offsetLeftEnd, offset + 1).toString() == TEMPLATE_END
) {
caret.shake()
val templateStart = editor.findTemplateStart(offsetLeftEnd) ?: return
caret.putUserData(facedAppCodeTemplate, templateStart..offset)
}
} else {
if (offset in templateRange) {
if (toRight) {
caret.moveToOffset(templateRange.last + 1)
} else {
caret.moveToOffset(templateRange.first)
}
}
caret.putUserData(facedAppCodeTemplate, null)
caret.shake()
}
}
fun Editor.appCodeTemplateCaptured(): Boolean {
return this.caretModel.allCarets.any { it.getUserData(facedAppCodeTemplate) != null }
}
private fun Caret.shake() {
moveCaretRelatively(1, 0, false, false)
moveCaretRelatively(-1, 0, false, false)
}
private fun Editor.findTemplateEnd(start: Int): Int? {
val charSequence = this.document.charsSequence
val length = charSequence.length
for (i in start until length - 1) {
if (charSequence[i] == TEMPLATE_END[0] && charSequence[i + 1] == TEMPLATE_END[1]) {
return i + 1
}
}
return null
}
private fun Editor.findTemplateStart(start: Int): Int? {
val charSequence = this.document.charsSequence
val templateLastIndex = TEMPLATE_START.length
for (i in start downTo templateLastIndex) {
if (charSequence.subSequence(i - templateLastIndex, i).toString() == TEMPLATE_START) {
return i - templateLastIndex
}
}
return null
}
}
| src/main/java/com/maddyhome/idea/vim/listener/AppCodeTemplates.kt | 2384370441 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.functionalities.initializers
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.ReLU
import com.kotlinnlp.simplednn.core.functionalities.activations.Sigmoid
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.FixedRangeRandom
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import java.util.*
/**
* An initializer of dense arrays with the 'Glorot Initialization', as explained by Xavier Glorot.
*
* References:
* [Understanding the difficulty of training deep feedforward neural networks]
* (http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf)
*
* @param gain the gain that determines the scale of the generated values (default = 1.0)
* @param enablePseudoRandom if true use pseudo-random with a seed (default = true)
* @param seed seed used for the pseudo-random (default = 743)
*/
class GlorotInitializer(
private val gain: Double = 1.0,
private val enablePseudoRandom: Boolean = true,
private val seed: Long = 743
) : Initializer {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
/**
* @param activationFunction the activation function of a layer (can be null)
*
* @return the gain to apply to a [GlorotInitializer] in relation to the given [activationFunction]
*/
fun getGain(activationFunction: ActivationFunction?): Double = when (activationFunction) {
is ReLU -> 0.5
is Sigmoid -> 4.0
else -> 1.0
}
}
/**
* The random generator of seeds for the pseudo-random initialization.
*/
private val seedGenerator = Random(this.seed)
/**
* Initialize the values of the given [array].
*
* @param array a dense array
*/
override fun initialize(array: DenseNDArray) {
val randomGenerator = FixedRangeRandom(
radius = this.gain * Math.sqrt(6.0 / (array.rows + array.columns)),
enablePseudoRandom = this.enablePseudoRandom,
seed = this.seedGenerator.nextLong())
array.randomize(randomGenerator)
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/functionalities/initializers/GlorotInitializer.kt | 3122707946 |
package org.wordpress.android.ui.stats.refresh.utils
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS
import org.wordpress.android.fluxc.network.utils.StatsGranularity.MONTHS
import org.wordpress.android.fluxc.network.utils.StatsGranularity.WEEKS
import org.wordpress.android.fluxc.network.utils.StatsGranularity.YEARS
import org.wordpress.android.util.LocaleManagerWrapper
import org.wordpress.android.viewmodel.ResourceProvider
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
class StatsDateFormatterTest : BaseUnitTest() {
@Mock lateinit var localeManagerWrapper: LocaleManagerWrapper
@Mock lateinit var resourceProvider: ResourceProvider
private lateinit var statsDateFormatter: StatsDateFormatter
@Before
fun setUp() {
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.US)
statsDateFormatter = StatsDateFormatter(localeManagerWrapper, resourceProvider)
}
@Test
fun `parses a date`() {
val unparsedDate = "2018-11-25"
val parsedDate = statsDateFormatter.printDate(unparsedDate)
assertThat(parsedDate).isEqualTo("Nov 25, 2018")
}
@Test
fun `prints a day date`() {
val unparsedDate = "2018-11-25"
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, DAYS)
assertThat(parsedDate).isEqualTo("Nov 25, 2018")
}
@Test
fun `prints a week date in string format`() {
val unparsedDate = "2018W12W19"
val result = "Dec 17 - Dec 23"
whenever(
resourceProvider.getString(
R.string.stats_from_to_dates_in_week_label,
"Dec 17",
"Dec 23"
)
).thenReturn(result)
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, WEEKS)
assertThat(parsedDate).isEqualTo("Dec 17 - Dec 23")
}
@Test
fun `prints a week date`() {
val calendar = Calendar.getInstance()
calendar.set(2018, Calendar.DECEMBER, 20)
val result = "Dec 17 - Dec 23"
whenever(
resourceProvider.getString(
R.string.stats_from_to_dates_in_week_label,
"Dec 17",
"Dec 23"
)
).thenReturn(result)
val parsedDate = statsDateFormatter.printGranularDate(calendar.time, WEEKS)
assertThat(parsedDate).isEqualTo("Dec 17 - Dec 23")
}
@Test
fun `prints a week date with year when week overlaps years`() {
val unparsedDate = "2011W12W31"
val result = "Dec 26, 2011 - Jan 1, 2012"
whenever(
resourceProvider.getString(
R.string.stats_from_to_dates_in_week_label,
"Dec 26, 2011",
"Jan 1, 2012"
)
).thenReturn(result)
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, WEEKS)
assertThat(parsedDate).isEqualTo(result)
}
@Test
fun `prints a month date`() {
val unparsedDate = "2018-12"
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, MONTHS)
assertThat(parsedDate).isEqualTo("Dec, 2018")
}
@Test
fun `prints a year date`() {
val unparsedDate = "2018-12-01"
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, YEARS)
assertThat(parsedDate).isEqualTo("2018")
}
@Test
fun `parses a date in another language`() {
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.forLanguageTag("cs"))
val unparsedDate = "2018-11-25"
val parsedDate = statsDateFormatter.printDate(unparsedDate)
assertThat(parsedDate).`as`("Are you using the correct version of JDK?").isEqualTo("25. 11. 2018")
}
@Test
fun `prints a day date in another language`() {
val unparsedDate = "2018-11-25"
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.forLanguageTag("cs"))
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, DAYS)
assertThat(parsedDate).`as`("Are you using the correct version of JDK?").isEqualTo("25. 11. 2018")
}
@Test
fun `prints a week date in another language`() {
val result = "17.12 - 23.12"
whenever(
resourceProvider.getString(
R.string.stats_from_to_dates_in_week_label,
"17. 12",
"23. 12"
)
).thenReturn(result)
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.forLanguageTag("cs"))
val unparsedDate = "2018W12W19"
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, WEEKS)
assertThat(parsedDate).isEqualTo(result)
}
@Test
fun `prints a month date in another language`() {
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.forLanguageTag("cs"))
val unparsedDate = "2018-12"
val parsedDate = statsDateFormatter.printGranularDate(unparsedDate, MONTHS)
assertThat(parsedDate).isEqualTo("Pro, 2018")
}
@Test
fun `prints neutral UTC when site timezone does not match current timezone and site timezone is GMT`() {
val site = SiteModel()
site.timezone = "GMT"
whenever(localeManagerWrapper.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT-5:30"))
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.US)
val expectedTimeZone = "UTC"
whenever(resourceProvider.getString(any(), any())).thenReturn(expectedTimeZone)
val printedTimeZone = statsDateFormatter.printTimeZone(site)
assertThat(printedTimeZone).isEqualTo(expectedTimeZone)
verify(resourceProvider).getString(eq(R.string.stats_site_neutral_utc), eq("0"))
}
@Test
fun `prints negative UTC when site timezone does not match current timezone and site timezone is negative GMT`() {
val site = SiteModel()
site.timezone = "-1.5"
whenever(localeManagerWrapper.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT-5:30"))
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.US)
val expectedTimeZone = "UTC"
whenever(resourceProvider.getString(any(), any())).thenReturn(expectedTimeZone)
val printedTimeZone = statsDateFormatter.printTimeZone(site)
assertThat(printedTimeZone).isEqualTo(expectedTimeZone)
verify(resourceProvider).getString(eq(R.string.stats_site_negative_utc), eq("1:30"))
}
@Test
fun `prints positive UTC when site timezone does not match current timezone and site timezone is positive GMT`() {
val site = SiteModel()
site.timezone = "2.25"
whenever(localeManagerWrapper.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT-5:30"))
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.US)
val expectedTimeZone = "UTC"
whenever(resourceProvider.getString(any(), any())).thenReturn(expectedTimeZone)
val printedTimeZone = statsDateFormatter.printTimeZone(site)
assertThat(printedTimeZone).isEqualTo(expectedTimeZone)
verify(resourceProvider).getString(eq(R.string.stats_site_positive_utc), eq("2:15"))
}
@Test
fun `returns empty timezone when the site timezone matches current timezone`() {
val site = SiteModel()
site.timezone = "GMT"
whenever(localeManagerWrapper.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT"))
whenever(localeManagerWrapper.getLocale()).thenReturn(Locale.US)
val printedTimeZone = statsDateFormatter.printTimeZone(site)
assertThat(printedTimeZone).isNull()
}
}
| WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/utils/StatsDateFormatterTest.kt | 2052914532 |
package forpdateam.ru.forpda.ui.fragments.devdb.device.posts
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.entity.remote.devdb.Device
import forpdateam.ru.forpda.ui.fragments.devdb.brand.DevicesFragment
import forpdateam.ru.forpda.ui.fragments.devdb.device.SubDeviceFragment
/**
* Created by radiationx on 09.08.17.
*/
class PostsFragment : SubDeviceFragment() {
private var source = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.device_fragment_specs, container, false)
//view.setBackgroundColor(App.getColorFromAttr(getContext(), R.attr.background_for_lists));
val recyclerView = view.findViewById<View>(R.id.base_list) as androidx.recyclerview.widget.RecyclerView
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(recyclerView.context)
val adapter = PostsAdapter { item -> presenter.onPostClick(item, source) }
adapter.setSource(source)
adapter.addAll(getList())
recyclerView.adapter = adapter
recyclerView.addItemDecoration(DevicesFragment.SpacingItemDecoration(App.px8, true))
return view
}
private fun getList(): List<Device.PostItem> = when (source) {
SRC_DISCUSSIONS -> device.discussions
SRC_FIRMWARES -> device.firmwares
SRC_NEWS -> device.news
else -> emptyList()
}
fun setSource(source: Int): SubDeviceFragment {
this.source = source
return this
}
companion object {
const val SRC_DISCUSSIONS = 1
const val SRC_FIRMWARES = 2
const val SRC_NEWS = 3
}
}
| app/src/main/java/forpdateam/ru/forpda/ui/fragments/devdb/device/posts/PostsFragment.kt | 2857822828 |
/*
* Copyright (C) 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 com.android.example.livedata
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.IdlingResource
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.example.livedatabuilder.LiveDataActivity
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Simple UI test.
*/
@RunWith(AndroidJUnit4::class)
class BasicUiTest {
@get:Rule
var activityScenarioRule = ActivityScenarioRule(LiveDataActivity::class.java)
private lateinit var dataBindingIdlingResource: IdlingResource
@Before
fun registerIdlingResources() {
dataBindingIdlingResource = DataBindingIdlingResource(activityScenarioRule)
IdlingRegistry.getInstance().register(dataBindingIdlingResource)
}
@After
fun unregisterIdlingResources() {
IdlingRegistry.getInstance().unregister(dataBindingIdlingResource)
}
@Test
fun activityLaunches() {
onView(withId(R.id.time_transformed)).check(matches(isDisplayed()))
}
}
| LiveDataSample/app/src/androidTest/java/com/android/example/livedata/BasicUiTest.kt | 2234383222 |
package v_builders.examples
import java.util.*
fun todoTask38(): Nothing = TODO(
"""
Task 38.
The previous examples can be rewritten with the library function 'apply' (see examples below).
Write your own implementation of the function 'apply' named 'myApply'.
"""
)
fun <T> T.myApply(f: T.() -> Unit): T {
this.f()
return this
}
//fun StringBuilder.myApply(f: StringBuilder.() -> Unit): String{
// val str = StringBuilder()
// str.f()
// return str.toString()
//}
//
//fun Map<Int, String>.myApply(f: HashMap<Int, String>.() -> Unit): Map<Int, String>{
// val map = hashMapOf<Int, String>()
// map.f()
// return map
//}
fun buildString(): String {
return StringBuilder().myApply {
append("Numbers: ")
for (i in 1..10) {
append(i)
}
}.toString()
}
fun buildMap(): Map<Int, String> {
return hashMapOf<Int, String>().myApply {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
} | src/v_builders/_38_TheFunctionApply.kt | 4217205878 |
package com.safframework.utils
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Uri
import android.net.wifi.WifiManager
import java.io.File
/**
* Created by Tony Shen on 2017/1/17.
*/
/**
* 调用该方法需要申请权限
* <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
*/
fun isWiFiActive(context: Context): Boolean {
var wm: WifiManager? = null
try {
wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
} catch (e: Exception) {
e.printStackTrace()
}
return wm!=null && wm.isWifiEnabled
}
/**
* 安装apk
* @param fileName apk文件的绝对路径
*
* @param context
*/
fun installAPK(fileName: String, context: Context) {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.fromFile(File(fileName)), "application/vnd.android.package-archive")
context.startActivity(intent)
}
/**
* 检测网络状态
* @param context
*
* @return
*/
fun checkNetworkStatus(context: Context): Boolean {
var resp = false
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetInfo = connMgr.activeNetworkInfo
if (activeNetInfo != null && activeNetInfo.isAvailable) {
resp = true
}
return resp
}
/**
* 检测gps状态
* @param context
*
* @return
*/
fun checkGPSStatus(context: Context): Boolean {
var resp = false
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
resp = true
}
return resp
}
/**
* 生成app日志tag
* 可以这样使用: SAFUtils.makeLogTag(this.getClass());
* @param cls
*
* @return
*/
fun makeLogTag(cls: Class<*>): String {
return cls.simpleName
}
/**
* 获取AndroidManifest.xml中<meta-data>元素的值
* @param context
*
* @param name
*
* @return
*/
fun <T> getMetaData(context: Context, name: String): T? {
try {
val ai = context.packageManager.getApplicationInfo(context.packageName,
PackageManager.GET_META_DATA)
return ai.metaData?.get(name) as T
} catch (e: Exception) {
print("Couldn't find meta-data: " + name)
}
return null
} | saf-kotlin-utils/src/main/java/com/safframework/utils/SAFUtils.kt | 1872038255 |
package com.kelsos.mbrc.ui.navigation.playlists
import toothpick.config.Module
class PlaylistModule : Module() {
init {
bind(PlaylistPresenter::class.java).to(PlaylistPresenterImpl::class.java).singletonInScope()
}
}
| app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/playlists/PlaylistModule.kt | 109173734 |
fun Int.foo(<caret>a: Int, b: Int) {
}
fun bar() {
10.foo(b = 1, a = 2)
} | plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameter/extNamedParam2.kt | 1957052424 |
/*
* 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.java.codeInspection
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.codeInspection.java19modules.Java9ModuleExportsPackageToItselfInspection
import com.intellij.java.analysis.JavaAnalysisBundle
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor
import org.intellij.lang.annotations.Language
/**
* @author Pavel.Dolgov
*/
class Java9ModuleExportsPackageToItselfTest : LightJava9ModulesCodeInsightFixtureTestCase() {
private val message = JavaAnalysisBundle.message("inspection.module.exports.package.to.itself")
private val fix1 = JavaAnalysisBundle.message("exports.to.itself.delete.statement.fix")
private val fix2 = JavaAnalysisBundle.message("exports.to.itself.delete.module.ref.fix", "M")
override fun setUp() {
super.setUp()
myFixture.enableInspections(Java9ModuleExportsPackageToItselfInspection())
addFile("module-info.java", "module M2 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2)
addFile("module-info.java", "module M4 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M4)
addFile("pkg/main/C.java", "package pkg.main; public class C {}")
}
fun testNoSelfModule() {
highlight("module M {\n exports pkg.main to M2, M4;\n opens pkg.main to M2, M4;\n}")
}
fun testOnlySelfExport() {
highlight("module M { exports pkg.main to <warning descr=\"$message\">M</warning>; }")
fix("module M { exports pkg.main to <caret>M; }",
"module M {\n}")
}
fun testOnlySelfOpen() {
highlight("module M { opens pkg.main to <warning descr=\"$message\">M</warning>; }")
fix("module M { opens pkg.main to <caret>M; }",
"module M {\n}")
}
fun testOnlySelfModuleWithComments() {
fix("module M { exports pkg.main to /*a*/ <caret>M /*b*/; }",
"module M { /*a*/ /*b*/\n}")
}
fun testSelfModuleInList() {
highlight("module M { exports pkg.main to M2, <warning descr=\"$message\">M</warning>, M4; }")
fix("module M { exports pkg.main to M2, <caret>M , M4; }",
"module M { exports pkg.main to M2, M4; }")
}
fun testSelfModuleInListWithComments() {
fix("module M { exports pkg.main to M2, /*a*/ <caret>M /*b*/,/*c*/ M4; }",
"module M { exports pkg.main to M2, /*a*/ /*b*//*c*/ M4; }")
}
private fun highlight(text: String) {
myFixture.configureByText("module-info.java", text)
myFixture.checkHighlighting()
}
private fun fix(textBefore: String, @Language("JAVA") textAfter: String) {
myFixture.configureByText("module-info.java", textBefore)
val action = myFixture.filterAvailableIntentions(fix1).firstOrNull() ?: myFixture.filterAvailableIntentions(fix2).first()
myFixture.launchAction(action)
myFixture.checkHighlighting() // no warning
myFixture.checkResult("module-info.java", textAfter, false)
}
} | java/java-tests/testSrc/com/intellij/java/codeInspection/Java9ModuleExportsPackageToItselfTest.kt | 2434424861 |
/*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.internal
actual typealias AtomicInteger = java.util.concurrent.atomic.AtomicInteger
actual typealias AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean
| thrifty-runtime/src/jvmMain/kotlin/com/microsoft/thrifty/internal/-Atomics.kt | 908346609 |
package net.squanchy.support.system
import android.content.Context
import android.preference.PreferenceManager
import androidx.core.content.edit
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
class FreezableCurrentTime(context: Context) : CurrentTime {
private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
override fun currentDateTime(): ZonedDateTime {
return preferences.getString(KEY_FROZEN_TIME, null)?.let {
ZonedDateTime.parse(it, DATE_TIME_FORMATTER)
} ?: ZonedDateTime.now()
}
fun freeze(frozenDateTime: ZonedDateTime) {
preferences.edit { putString(KEY_FROZEN_TIME, frozenDateTime.format(DATE_TIME_FORMATTER)) }
}
fun unfreeze() {
preferences.edit { remove(KEY_FROZEN_TIME) }
}
fun isTimeFrozen() = preferences.contains(KEY_FROZEN_TIME)
companion object {
private const val KEY_FROZEN_TIME = "FROZEN_TIME"
private val DATE_TIME_FORMATTER = DateTimeFormatter.ISO_DATE_TIME
}
}
| app/src/debug/java/net/squanchy/support/system/FreezableCurrentTime.kt | 3793490654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.