content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.ext.parent
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.AbortStage
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
@Component
class AbortStageHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val clock: Clock
) : OrcaMessageHandler<AbortStage> {
override fun handle(message: AbortStage) {
message.withStage { stage ->
if (stage.status in setOf(RUNNING, NOT_STARTED)) {
stage.status = TERMINAL
stage.endTime = clock.millis()
repository.storeStage(stage)
queue.push(CancelStage(message))
if (stage.parentStageId == null) {
queue.push(CompleteExecution(message))
} else {
queue.push(CompleteStage(stage.parent()))
}
publisher.publishEvent(StageComplete(this, stage))
}
}
}
override val messageType = AbortStage::class.java
}
| orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/AbortStageHandler.kt | 2131964461 |
package exh.source
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import java.lang.RuntimeException
abstract class DelegatedHttpSource(val delegate: HttpSource): HttpSource() {
/**
* Returns the request for the popular manga given the page.
*
* @param page the page number to retrieve.
*/
override fun popularMangaRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for the search manga given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun searchMangaRequest(page: Int, query: String, filters: FilterList)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for latest manga given the page.
*
* @param page the page number to retrieve.
*/
override fun latestUpdatesRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
override val baseUrl get() = delegate.baseUrl
/**
* Whether the source has support for latest updates.
*/
override val supportsLatest get() = delegate.supportsLatest
/**
* Name of the source.
*/
final override val name get() = delegate.name
// ===> OPTIONAL FIELDS
/**
* Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string: sourcename/language/versionId
* Note the generated id sets the sign bit to 0.
*/
override val id get() = delegate.id
/**
* Default network client for doing requests.
*/
final override val client get() = delegate.client
/**
* You must NEVER call super.client if you override this!
*/
open val baseHttpClient: OkHttpClient? = null
open val networkHttpClient: OkHttpClient get() = network.client
open val networkCloudflareClient: OkHttpClient get() = network.cloudflareClient
/**
* Visible name of the source.
*/
override fun toString() = delegate.toString()
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchPopularManga(page)
}
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchSearchManga(page, query, filters)
}
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchLatestUpdates(page)
}
/**
* Returns an observable with the updated details for a manga. Normally it's not needed to
* override this method.
*
* @param manga the manga to be updated.
*/
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
ensureDelegateCompatible()
return delegate.fetchMangaDetails(manga)
}
/**
* Returns the request for the details of a manga. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param manga the manga to be updated.
*/
override fun mangaDetailsRequest(manga: SManga): Request {
ensureDelegateCompatible()
return delegate.mangaDetailsRequest(manga)
}
/**
* Returns an observable with the updated chapter list for a manga. Normally it's not needed to
* override this method. If a manga is licensed an empty chapter list observable is returned
*
* @param manga the manga to look for chapters.
*/
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
ensureDelegateCompatible()
return delegate.fetchChapterList(manga)
}
/**
* Returns an observable with the page list for a chapter.
*
* @param chapter the chapter whose page list has to be fetched.
*/
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
ensureDelegateCompatible()
return delegate.fetchPageList(chapter)
}
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @param page the page whose source image has to be fetched.
*/
override fun fetchImageUrl(page: Page): Observable<String> {
ensureDelegateCompatible()
return delegate.fetchImageUrl(page)
}
/**
* Called before inserting a new chapter into database. Use it if you need to override chapter
* fields, like the title or the chapter number. Do not change anything to [manga].
*
* @param chapter the chapter to be added.
* @param manga the manga of the chapter.
*/
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
ensureDelegateCompatible()
return delegate.prepareNewChapter(chapter, manga)
}
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = delegate.getFilterList()
private fun ensureDelegateCompatible() {
if(versionId != delegate.versionId
|| lang != delegate.lang) {
throw IncompatibleDelegateException("Delegate source is not compatible (versionId: $versionId <=> ${delegate.versionId}, lang: $lang <=> ${delegate.lang})!")
}
}
class IncompatibleDelegateException(message: String) : RuntimeException(message)
init {
delegate.bindDelegate(this)
}
} | app/src/main/java/exh/source/DelegatedHttpSource.kt | 3943842716 |
/**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.account.presenter
import android.util.Log
import com.savvasdalkitsis.gameframe.feature.account.R
import com.savvasdalkitsis.gameframe.feature.account.view.AccountView
import com.savvasdalkitsis.gameframe.feature.analytics.Analytics
import com.savvasdalkitsis.gameframe.feature.authentication.model.Account
import com.savvasdalkitsis.gameframe.feature.authentication.model.SignedInAccount
import com.savvasdalkitsis.gameframe.feature.authentication.usecase.AuthenticationUseCase
import com.savvasdalkitsis.gameframe.feature.message.MessageDisplay
import com.savvasdalkitsis.gameframe.feature.workspace.model.SaveContainer
import com.savvasdalkitsis.gameframe.feature.workspace.model.WorkspaceItem
import com.savvasdalkitsis.gameframe.feature.workspace.storage.WorkspaceStorage
import com.savvasdalkitsis.gameframe.feature.workspace.usecase.WorkspaceUseCase
import com.savvasdalkitsis.gameframe.infra.base.BasePresenter
import com.savvasdalkitsis.gameframe.infra.base.plusAssign
import com.savvasdalkitsis.gameframe.infra.rx.RxTransformers
import com.savvasdalkitsis.gameframe.infra.rx.logErrors
import io.reactivex.Flowable
private val TAG = AccountPresenter<*>::javaClass.name
class AccountPresenter<in AuthenticationData>(private val authenticationUseCase: AuthenticationUseCase<AuthenticationData>,
private val workspaceUseCase: WorkspaceUseCase,
private val remoteWorkspaceStorage: WorkspaceStorage,
private val messageDisplay: MessageDisplay,
private val analytics: Analytics) : BasePresenter<AccountView>() {
fun start() {
view?.displayLoading()
managedStreams += authenticationUseCase.accountState()
.compose(RxTransformers.schedulersFlowable<Account>())
.subscribe(::accountRetrieved, ::accountRetrieveFailed)
}
fun logIn() {
analytics.logEvent("log_in")
authenticationUseCase.signIn()
}
fun logOut() {
analytics.logEvent("log_out")
authenticationUseCase.signOut()
}
fun reUpload() {
analytics.logEvent("re_upload")
uploadLocallySavedProjects()
}
fun deleteAccount() {
analytics.logEvent("delete_account")
view?.askUserToVerifyAccountDeletion {
analytics.logEvent("delete_account_verified")
authenticationUseCase.deleteAccount()
}
}
private fun accountRetrieved(account: Account) {
when (account) {
is SignedInAccount -> {
view?.displaySignedInAccount(account)
uploadLocallySavedProjects()
}
else -> view?.displaySignedOut()
}
}
private fun accountRetrieveFailed(error: Throwable) {
Log.w(TAG, "Could not load account details", error)
view?.displayErrorLoadingAccount()
}
private fun uploadLocallySavedProjects() {
workspaceUseCase.locallySavedProjects()
.compose(RxTransformers.schedulers<List<WorkspaceItem>>())
.subscribe(::savedProjectsLoaded, logErrors())
}
private fun savedProjectsLoaded(projects: List<WorkspaceItem>) {
if (!projects.isEmpty()) {
view?.askUserToUploadSavedProjects {
messageDisplay.show(R.string.projects_upload_started)
Flowable.fromIterable(projects)
.flatMapCompletable { (name, model) ->
remoteWorkspaceStorage.saveWorkspace(name, SaveContainer(model))
}
.compose(RxTransformers.schedulers())
.subscribe({
messageDisplay.show(R.string.projects_upload_finished)
}, {
Log.w(TAG, "Failed to upload some projects", it)
messageDisplay.show(R.string.projects_failed_to_upload)
})
}
} else {
messageDisplay.show(R.string.no_projects_to_upload)
}
}
fun handleResultForLoginRequest(requestCode: Int, resultCode: Int, authenticationData: AuthenticationData?) {
authenticationUseCase.handleResult(requestCode, resultCode, authenticationData)
}
} | account/src/main/java/com/savvasdalkitsis/gameframe/feature/account/presenter/AccountPresenter.kt | 104122865 |
package su.jfdev.anci.geography.region
import su.jfdev.anci.geography.*
/**
* Jamefrus and his team on 26.06.2016.
*/
abstract class RegionSpec(included: Collection<Vec3i>,
excluded: Collection<Vec3i>,
coverage: Collection<Vec3i>,
size: Int): CoverageSpec<Vec3i>(included, excluded, coverage) {
init {
"should have given size" {
coverage.size shouldBe size
}
}
}
| geography/src/test/kotlin/su/jfdev/anci/geography/region/RegionSpec.kt | 1592437734 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.textured
import android.content.res.AssetManager
import android.util.Log
import com.google.android.filament.*
import com.google.android.filament.VertexBuffer.AttributeType.*
import com.google.android.filament.VertexBuffer.VertexAttribute.*
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import java.nio.channels.ReadableByteChannel
data class Mesh(
@Entity val renderable: Int,
val indexBuffer: IndexBuffer,
val vertexBuffer: VertexBuffer,
val aabb: Box)
fun destroyMesh(engine: Engine, mesh: Mesh) {
engine.destroyEntity(mesh.renderable)
engine.destroyIndexBuffer(mesh.indexBuffer)
engine.destroyVertexBuffer(mesh.vertexBuffer)
EntityManager.get().destroy(mesh.renderable)
}
fun loadMesh(assets: AssetManager, name: String,
materials: Map<String, MaterialInstance>, engine: Engine): Mesh {
// See tools/filamesh/README.md for a description of the filamesh file format
assets.open(name).use { input ->
val header = readHeader(input)
val channel = Channels.newChannel(input)
val vertexBufferData = readSizedData(channel, header.verticesSizeInBytes)
val indexBufferData = readSizedData(channel, header.indicesSizeInBytes)
val parts = readParts(header, input)
val definedMaterials = readMaterials(input)
val indexBuffer = createIndexBuffer(engine, header, indexBufferData)
val vertexBuffer = createVertexBuffer(engine, header, vertexBufferData)
val renderable = createRenderable(
engine, header, indexBuffer, vertexBuffer, parts, definedMaterials, materials)
return Mesh(renderable, indexBuffer, vertexBuffer, header.aabb)
}
}
private const val FILAMESH_FILE_IDENTIFIER = "FILAMESH"
private const val MAX_UINT32 = 4294967295
private const val HEADER_FLAG_INTERLEAVED = 0x1L
private const val HEADER_FLAG_SNORM16_UV = 0x2L
private const val HEADER_FLAG_COMPRESSED = 0x4L
private class Header {
var valid = false
var versionNumber = 0L
var parts = 0L
var aabb = Box()
var flags = 0L
var posOffset = 0L
var positionStride = 0L
var tangentOffset = 0L
var tangentStride = 0L
var colorOffset = 0L
var colorStride = 0L
var uv0Offset = 0L
var uv0Stride = 0L
var uv1Offset = 0L
var uv1Stride = 0L
var totalVertices = 0L
var verticesSizeInBytes = 0L
var indices16Bit = 0L
var totalIndices = 0L
var indicesSizeInBytes = 0L
}
private class Part {
var offset = 0L
var indexCount = 0L
var minIndex = 0L
var maxIndex = 0L
var materialID = 0L
var aabb = Box()
}
private fun readMagicNumber(input: InputStream): Boolean {
val temp = ByteArray(FILAMESH_FILE_IDENTIFIER.length)
input.read(temp)
val tempS = String(temp, Charset.forName("UTF-8"))
return tempS == FILAMESH_FILE_IDENTIFIER
}
private fun readHeader(input: InputStream): Header {
val header = Header()
if (!readMagicNumber(input)) {
Log.e("Filament", "Invalid filamesh file.")
return header
}
header.versionNumber = readUIntLE(input)
header.parts = readUIntLE(input)
header.aabb = Box(
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input),
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input))
header.flags = readUIntLE(input)
header.posOffset = readUIntLE(input)
header.positionStride = readUIntLE(input)
header.tangentOffset = readUIntLE(input)
header.tangentStride = readUIntLE(input)
header.colorOffset = readUIntLE(input)
header.colorStride = readUIntLE(input)
header.uv0Offset = readUIntLE(input)
header.uv0Stride = readUIntLE(input)
header.uv1Offset = readUIntLE(input)
header.uv1Stride = readUIntLE(input)
header.totalVertices = readUIntLE(input)
header.verticesSizeInBytes = readUIntLE(input)
header.indices16Bit = readUIntLE(input)
header.totalIndices = readUIntLE(input)
header.indicesSizeInBytes = readUIntLE(input)
header.valid = true
return header
}
private fun readSizedData(channel: ReadableByteChannel, sizeInBytes: Long): ByteBuffer {
val buffer = ByteBuffer.allocateDirect(sizeInBytes.toInt())
buffer.order(ByteOrder.LITTLE_ENDIAN)
channel.read(buffer)
buffer.flip()
return buffer
}
private fun readParts(header: Header, input: InputStream): List<Part> {
return List(header.parts.toInt()) {
val p = Part()
p.offset = readUIntLE(input)
p.indexCount = readUIntLE(input)
p.minIndex = readUIntLE(input)
p.maxIndex = readUIntLE(input)
p.materialID = readUIntLE(input)
p.aabb = Box(
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input),
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input))
p
}
}
private fun readMaterials(input: InputStream): List<String> {
return List(readUIntLE(input).toInt()) {
val data = ByteArray(readUIntLE(input).toInt())
input.read(data)
// Skip null terminator
input.skip(1)
data.toString(Charset.forName("UTF-8"))
}
}
private fun createIndexBuffer(engine: Engine, header: Header, data: ByteBuffer): IndexBuffer {
val indexType = if (header.indices16Bit != 0L) {
IndexBuffer.Builder.IndexType.USHORT
} else {
IndexBuffer.Builder.IndexType.UINT
}
return IndexBuffer.Builder()
.bufferType(indexType)
.indexCount(header.totalIndices.toInt())
.build(engine)
.apply { setBuffer(engine, data) }
}
private fun uvNormalized(header: Header) = header.flags and HEADER_FLAG_SNORM16_UV != 0L
private fun createVertexBuffer(engine: Engine, header: Header, data: ByteBuffer): VertexBuffer {
val uvType = if (!uvNormalized(header)) {
HALF2
} else {
SHORT2
}
val vertexBufferBuilder = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(header.totalVertices.toInt())
// We store colors as unsigned bytes (0..255) but the shader wants values in the 0..1
// range so we must mark this attribute normalized
.normalized(COLOR)
// The same goes for the tangent frame: we store it as a signed short, but we want
// values in 0..1 in the shader
.normalized(TANGENTS)
.attribute(POSITION, 0, HALF4, header.posOffset.toInt(), header.positionStride.toInt())
.attribute(TANGENTS, 0, SHORT4, header.tangentOffset.toInt(), header.tangentStride.toInt())
.attribute(COLOR, 0, UBYTE4, header.colorOffset.toInt(), header.colorStride.toInt())
// UV coordinates are stored as normalized 16-bit integers or half-floats depending on
// the range they span. When stored as half-float, there is only enough precision for
// sub-pixel addressing in textures that are <= 1024x1024
.attribute(UV0, 0, uvType, header.uv0Offset.toInt(), header.uv0Stride.toInt())
// When UV coordinates are stored as 16-bit integers we must normalize them (we want
// values in the range -1..1)
.normalized(UV0, uvNormalized(header))
if (header.uv1Offset != MAX_UINT32 && header.uv1Stride != MAX_UINT32) {
vertexBufferBuilder
.attribute(UV1, 0, uvType, header.uv1Offset.toInt(), header.uv1Stride.toInt())
.normalized(UV1, uvNormalized(header))
}
return vertexBufferBuilder.build(engine).apply { setBufferAt(engine, 0, data) }
}
private fun createRenderable(
engine: Engine,
header: Header,
indexBuffer: IndexBuffer,
vertexBuffer: VertexBuffer,
parts: List<Part>,
definedMaterials: List<String>,
materials: Map<String, MaterialInstance>): Int {
val builder = RenderableManager.Builder(header.parts.toInt()).boundingBox(header.aabb)
repeat(header.parts.toInt()) { i ->
builder.geometry(i,
RenderableManager.PrimitiveType.TRIANGLES,
vertexBuffer,
indexBuffer,
parts[i].offset.toInt(),
parts[i].minIndex.toInt(),
parts[i].maxIndex.toInt(),
parts[i].indexCount.toInt())
// Find a material in the supplied material map, otherwise we fall back to
// the default material named "DefaultMaterial"
val material = materials[definedMaterials[parts[i].materialID.toInt()]]
material?.let {
builder.material(i, material)
} ?: builder.material(i, materials["DefaultMaterial"]!!)
}
return EntityManager.get().create().apply { builder.build(engine, this) }
}
| android/samples/sample-textured-object/src/main/java/com/google/android/filament/textured/MeshLoader.kt | 1248724408 |
/*
* Copyright 2017 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nomic.core.fact
import nomic.core.BoxRef
import nomic.core.Fact
import nomic.core.Script
/**
* this fact is associated with 'group' variable in DSL [Script]
*/
data class GroupFact(val group: String) : Fact
/**
* this fact is associated with 'name' variable in DSL [Script].
* The name is unique identifier of every box.
*/
data class NameFact(val name: String) : Fact
/**
* this fact is associated with 'name' variable in DSL [Script].
*/
data class VersionFact(val version: String) : Fact
/**
* this fact determine the box contain nested sub-box in folder
* by name. It's same concept the maven is using
*/
data class ModuleFact(val name: String): Fact
/**
* this fact make a dependency to another box
*/
data class RequireFact(val box: BoxRef): Fact
| nomic-core/src/main/kotlin/nomic/core/fact/Facts.kt | 2113158685 |
package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ActionViewModelBase
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLogger
abstract class PodActivationActionViewModelBase(
injector: HasAndroidInjector,
logger: AAPSLogger,
aapsSchedulers: AapsSchedulers
) : ActionViewModelBase(injector, logger, aapsSchedulers) {
abstract fun isPodInAlarm(): Boolean
abstract fun isPodActivationTimeExceeded(): Boolean
abstract fun isPodDeactivatable(): Boolean
} | omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/PodActivationActionViewModelBase.kt | 3339372462 |
package net.cyclestreets.routing
import android.content.Context
import net.cyclestreets.content.RouteData
internal class LiveRideReplanRoutingTask(routeType: String,
speed: Int,
context: Context) : CycleStreetsRoutingTask(routeType, speed, context, saveRoute = false) {
override fun onPostExecute(route: RouteData?) {
super.onPostExecute(route)
if (route != null)
Route.waypoints().firstWaypointEphemeral = true
}
}
| libraries/cyclestreets-view/src/main/java/net/cyclestreets/routing/LiveRideReplanRoutingTask.kt | 14025196 |
package routeguide
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.Descriptors
import io.grpc.ServiceDescriptor
import io.grpc.ServiceDescriptor.newBuilder
import kotlin.Array
import kotlin.String
import kotlin.collections.Map
import kotlin.collections.Set
import kotlin.jvm.Volatile
public class RouteGuideWireGrpc {
public val SERVICE_NAME: String = "routeguide.RouteGuide"
@Volatile
private var serviceDescriptor: ServiceDescriptor? = null
private val descriptorMap: Map<String, DescriptorProtos.FileDescriptorProto> = mapOf(
"src/test/proto/RouteGuideProto.proto" to descriptorFor(arrayOf(
"CiRzcmMvdGVzdC9wcm90by9Sb3V0ZUd1aWRlUHJvdG8ucHJvdG8SCnJvdXRlZ3VpZGUiLAoFUG9pbnQS",
"EAoIbGF0aXR1ZGUYASABKAUSEQoJbG9uZ2l0dWRlGAIgASgFIkkKCVJlY3RhbmdsZRIdCgJsbxgBIAEo",
"CzIRLnJvdXRlZ3VpZGUuUG9pbnQSHQoCaGkYAiABKAsyES5yb3V0ZWd1aWRlLlBvaW50IjwKB0ZlYXR1",
"cmUSDAoEbmFtZRgBIAEoCRIjCghsb2NhdGlvbhgCIAEoCzIRLnJvdXRlZ3VpZGUuUG9pbnQiNwoPRmVh",
"dHVyZURhdGFiYXNlEiQKB2ZlYXR1cmUYASADKAsyEy5yb3V0ZWd1aWRlLkZlYXR1cmUiQQoJUm91dGVO",
"b3RlEiMKCGxvY2F0aW9uGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIPCgdtZXNzYWdlGAIgASgJImIK",
"DFJvdXRlU3VtbWFyeRITCgtwb2ludF9jb3VudBgBIAEoBRIVCg1mZWF0dXJlX2NvdW50GAIgASgFEhAK",
"CGRpc3RhbmNlGAMgASgFEhQKDGVsYXBzZWRfdGltZRgEIAEoBTL9AQoKUm91dGVHdWlkZRI0CgpHZXRG",
"ZWF0dXJlEhEucm91dGVndWlkZS5Qb2ludBoTLnJvdXRlZ3VpZGUuRmVhdHVyZRI8CgxMaXN0RmVhdHVy",
"ZXMSFS5yb3V0ZWd1aWRlLlJlY3RhbmdsZRoTLnJvdXRlZ3VpZGUuRmVhdHVyZTABEjwKC1JlY29yZFJv",
"dXRlEhEucm91dGVndWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5KAESPQoJUm91dGVD",
"aGF0EhUucm91dGVndWlkZS5Sb3V0ZU5vdGUaFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZSgBMAE=",
)),
)
private fun descriptorFor(`data`: Array<String>): DescriptorProtos.FileDescriptorProto {
val str = data.fold(java.lang.StringBuilder()) { b, s -> b.append(s) }.toString()
val bytes = java.util.Base64.getDecoder().decode(str)
return DescriptorProtos.FileDescriptorProto.parseFrom(bytes)
}
private fun fileDescriptor(path: String, visited: Set<String>): Descriptors.FileDescriptor {
val proto = descriptorMap[path]!!
val deps = proto.dependencyList.filter { !visited.contains(it) }.map { fileDescriptor(it,
visited + path) }
return Descriptors.FileDescriptor.buildFrom(proto, deps.toTypedArray())
}
public fun getServiceDescriptor(): ServiceDescriptor? {
var result = serviceDescriptor
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = serviceDescriptor
if (result == null) {
result = newBuilder(SERVICE_NAME)
.addMethod(getGetFeatureMethod())
.addMethod(getListFeaturesMethod())
.addMethod(getRecordRouteMethod())
.addMethod(getRouteChatMethod())
.setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier {
fileDescriptor("src/test/proto/RouteGuideProto.proto", emptySet())
})
.build()
serviceDescriptor = result
}
}
}
return result
}
}
| wire-library/wire-grpc-server-generator/src/test/golden/ServiceDescriptor.kt | 156854258 |
package tr.xip.scd.tensuu.ui.common.adapter
import android.annotation.SuppressLint
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import io.realm.OrderedRealmCollection
import io.realm.RealmRecyclerViewAdapter
import kotlinx.android.synthetic.main.item_point.view.*
import tr.xip.scd.tensuu.App.Companion.context
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.realm.model.Point
import tr.xip.scd.tensuu.local.Credentials
import tr.xip.scd.tensuu.ui.student.StudentActivity
import tr.xip.scd.tensuu.realm.util.RealmUtils.syncedRealm
import tr.xip.scd.tensuu.common.ext.getLayoutInflater
import tr.xip.scd.tensuu.common.ext.isToday
import tr.xip.scd.tensuu.common.ext.isYesterday
import java.text.SimpleDateFormat
class PointsAdapter(data: OrderedRealmCollection<Point>) : RealmRecyclerViewAdapter<Point, PointsAdapter.ViewHolder>(data, true) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = parent.context.getLayoutInflater().inflate(R.layout.item_point, parent, false)
return ViewHolder(v)
}
@SuppressLint("SimpleDateFormat")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data?.get(position) ?: return
/* 60% alpha if my point and older than a week */
val now = System.currentTimeMillis()
val weekInMillis: Long = 7 * 24 * 60 * 60 * 1000
val olderThanWeek = item.from?.email == Credentials.email &&
(now - (item.timestamp ?: 0)) > weekInMillis
holder.itemView.alpha = if (olderThanWeek) 0.6f else 1f
/* Amount */
holder.itemView.amount.text = "${item.amount ?: ""}"
if ((item.amount ?: 0) < 0) {
holder.itemView.amount.setBackgroundResource(R.drawable.oval_minus)
} else {
holder.itemView.amount.setBackgroundResource(R.drawable.oval_plus)
}
/* To */
holder.itemView.to.text = item.to?.fullName ?: "?"
/* From */
holder.itemView.from.text = item.from?.name ?: "?"
/* Time */
val timestamp = item.timestamp ?: 0
var timeText: String? = null
if (timestamp != 0.toLong()) {
if (timestamp.isToday()) {
timeText = context.getString(R.string.today)
} else if (timestamp.isYesterday()) {
timeText = context.getString(R.string.yesterday)
} else {
timeText = SimpleDateFormat("MMM d, yyyy").format(timestamp)
}
}
if (timeText != null) {
holder.itemView.time.text = timeText
holder.itemView.time.visibility = VISIBLE
} else {
holder.itemView.time.visibility = GONE
}
/* Reason */
if (item.reason != null) {
holder.itemView.reason.text = item.reason
holder.itemView.root.setOnClickListener(reasonClickListener)
holder.itemView.expandIndicator.visibility = VISIBLE
} else {
holder.itemView.root.setOnClickListener(null)
holder.itemView.expandIndicator.visibility = GONE
}
/*
* Options
*/
val menu = PopupMenu(holder.itemView.context, holder.itemView.more, Gravity.BOTTOM)
menu.menuInflater.inflate(R.menu.point, menu.menu)
/*
* - Owners SHOULD be able to edit IF they (still) have modification rights
* - Admins SHOULD be able to edit no matter what
*/
val canEdit =
(item.from?.email == Credentials.email && Credentials.canModify)
|| Credentials.isAdmin
val deleteItem = menu.menu.findItem(R.id.delete)
deleteItem.isVisible = canEdit
deleteItem.isEnabled = canEdit
menu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.go_to_student -> {
StudentActivity.start(context, item.to?.ssid)
}
R.id.delete -> {
syncedRealm().use {
it.executeTransaction {
item.deleteFromRealm()
}
}
}
}
true
}
holder.itemView.more.setOnClickListener {
menu.show()
}
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v)
private object reasonClickListener : View.OnClickListener {
override fun onClick(v: View) {
val expand = v.reasonContainer.visibility == GONE
v.reasonContainer.visibility = if (expand) VISIBLE else GONE
v.expandIndicator.animate()
.rotation(if (expand) 180f else 0f)
.setInterpolator(DecelerateInterpolator())
.setDuration(200)
.start()
}
}
} | app/src/main/java/tr/xip/scd/tensuu/ui/common/adapter/PointsAdapter.kt | 2005451568 |
package tr.xip.scd.tensuu.ui.lists.add
import android.text.Editable
import io.realm.Case
import tr.xip.scd.tensuu.local.Credentials
import tr.xip.scd.tensuu.realm.model.*
import tr.xip.scd.tensuu.common.ui.mvp.RealmPresenter
import tr.xip.scd.tensuu.ui.lists.StudentsAddingAdapter
import tr.xip.scd.tensuu.ui.mypoints.StudentsAutoCompleteAdapter
class ListAddPresenter : RealmPresenter<ListAddView>() {
private var list = StudentList()
private var isEditMode = false
fun init() {
setAdapter()
view?.setAutoCompleteAdapter(
StudentsAutoCompleteAdapter(realm, realm.where(Student::class.java).findAll())
)
}
fun loadList(listName: String) {
isEditMode = true
realm.where(StudentList::class.java).equalTo(StudentListFields.NAME, listName).findFirst()?.let {
list = it
setAdapter()
view?.showExitButton(false)
view?.setName(list.name ?: "")
view?.setPrivate(!list.public)
}
}
private fun setAdapter() {
view?.setAdapter(StudentsAddingAdapter(list.students,
removeClickedListener = {
onStudentRemoveClicked(it)
}
))
}
fun onNameChanged(name: String) {
view?.runOnUi {
realm.executeTransaction {
list.name = if (name.isBlank()) null else name
}
}
}
fun onPrivateChanged(private: Boolean) {
view?.runOnUi {
realm.executeTransaction {
list.public = !private
}
}
}
fun onDoneClicked() {
if (!isEditMode) {
realm.executeTransaction {
// Append a number to the name if a list with the same name already exists
val existing = realm.where(StudentList::class.java).equalTo(StudentListFields.NAME, list.name).findAll()
if (existing.size != 0) list.name = "${list.name} ${existing.size + 1}"
list.owner = it.where(User::class.java)
.equalTo(UserFields.EMAIL, Credentials.email).findFirst()
it.copyToRealm(list)
}
}
view?.die()
}
fun onNewStudentSelected(student: Student) {
if (!list.students.contains(student)) {
view?.runOnUi {
realm.executeTransaction {
list.students.add(student)
}
}
view?.getAdapter()?.notifyItemInserted(list.students.indexOf(student))
}
}
private fun onStudentRemoveClicked(position: Int) {
val adapter = view?.getAdapter() ?: return
val lastIndex = adapter.itemCount - 1
realm.executeTransaction {
adapter.data?.removeAt(position)
}
adapter.notifyItemRemoved(position)
adapter.notifyItemRangeChanged(position, lastIndex)
}
fun onSearchTextChangedInstant(s: Editable?) {
view?.setSearchClearVisible(s?.toString()?.isNotEmpty() ?: false)
}
fun onSearchTextChanged(s: Editable?) {
val q = s?.toString() ?: return
view?.runOnUi {
view?.getAutoCompleteAdapter()?.updateData(
realm.where(Student::class.java)
.beginGroup()
.contains(StudentFields.FULL_NAME, q, Case.INSENSITIVE)
.or()
.contains(StudentFields.FULL_NAME_SIMPLIFIED, q, Case.INSENSITIVE)
.endGroup()
.findAll()
)
}
}
} | app/src/main/java/tr/xip/scd/tensuu/ui/lists/add/ListAddPresenter.kt | 168094468 |
/*
* Copyright 2021 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.whiteboard
import io.grpc.stub.StreamObserver
class WhiteboardImpl : WhiteboardWireGrpc.WhiteboardImplBase() {
override fun Whiteboard(response: StreamObserver<WhiteboardUpdate>): StreamObserver<WhiteboardCommand> {
return object : StreamObserver<WhiteboardCommand> {
override fun onNext(value: WhiteboardCommand?) {
response.onNext(
WhiteboardUpdate(
update_points = WhiteboardUpdate.UpdatePoints(
listOf(
Point(0, 0, 0)
)
)
)
)
}
override fun onError(t: Throwable?) {
response.onCompleted()
}
override fun onCompleted() {
response.onCompleted()
}
}
}
}
| samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardImpl.kt | 2727126272 |
package com.fsck.k9.widget.unread
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.preference.CheckBoxPreference
import androidx.preference.Preference
import com.fsck.k9.Preferences
import com.fsck.k9.R
import com.fsck.k9.activity.ChooseAccount
import com.fsck.k9.search.SearchAccount
import com.fsck.k9.ui.choosefolder.ChooseFolderActivity
import com.takisoft.preferencex.PreferenceFragmentCompat
import org.koin.android.ext.android.inject
class UnreadWidgetConfigurationFragment : PreferenceFragmentCompat() {
private val preferences: Preferences by inject()
private val repository: UnreadWidgetRepository by inject()
private val unreadWidgetUpdater: UnreadWidgetUpdater by inject()
private var appWidgetId: Int = AppWidgetManager.INVALID_APPWIDGET_ID
private lateinit var unreadAccount: Preference
private lateinit var unreadFolderEnabled: CheckBoxPreference
private lateinit var unreadFolder: Preference
private var selectedAccountUuid: String? = null
private var selectedFolderId: Long? = null
private var selectedFolderDisplayName: String? = null
override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) {
setHasOptionsMenu(true)
setPreferencesFromResource(R.xml.unread_widget_configuration, rootKey)
appWidgetId = arguments?.getInt(ARGUMENT_APP_WIDGET_ID) ?: error("Missing argument '$ARGUMENT_APP_WIDGET_ID'")
unreadAccount = findPreference(PREFERENCE_UNREAD_ACCOUNT)!!
unreadAccount.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(requireContext(), ChooseAccount::class.java)
startActivityForResult(intent, REQUEST_CHOOSE_ACCOUNT)
false
}
unreadFolderEnabled = findPreference(PREFERENCE_UNREAD_FOLDER_ENABLED)!!
unreadFolderEnabled.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ ->
unreadFolder.summary = getString(R.string.unread_widget_folder_summary)
selectedFolderId = null
selectedFolderDisplayName = null
true
}
unreadFolder = findPreference(PREFERENCE_UNREAD_FOLDER)!!
unreadFolder.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = ChooseFolderActivity.buildLaunchIntent(
context = requireContext(),
action = ChooseFolderActivity.Action.CHOOSE,
accountUuid = selectedAccountUuid!!,
showDisplayableOnly = true
)
startActivityForResult(intent, REQUEST_CHOOSE_FOLDER)
false
}
if (savedInstanceState != null) {
restoreInstanceState(savedInstanceState)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(STATE_SELECTED_ACCOUNT_UUID, selectedAccountUuid)
outState.putLongIfPresent(STATE_SELECTED_FOLDER_ID, selectedFolderId)
outState.putString(STATE_SELECTED_FOLDER_DISPLAY_NAME, selectedFolderDisplayName)
}
private fun restoreInstanceState(savedInstanceState: Bundle) {
val accountUuid = savedInstanceState.getString(STATE_SELECTED_ACCOUNT_UUID)
if (accountUuid != null) {
handleChooseAccount(accountUuid)
val folderId = savedInstanceState.getLongOrNull(STATE_SELECTED_FOLDER_ID)
val folderSummary = savedInstanceState.getString(STATE_SELECTED_FOLDER_DISPLAY_NAME)
if (folderId != null && folderSummary != null) {
handleChooseFolder(folderId, folderSummary)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && data != null) {
when (requestCode) {
REQUEST_CHOOSE_ACCOUNT -> {
val accountUuid = data.getStringExtra(ChooseAccount.EXTRA_ACCOUNT_UUID)!!
handleChooseAccount(accountUuid)
}
REQUEST_CHOOSE_FOLDER -> {
val folderId = data.getLongExtra(ChooseFolderActivity.RESULT_SELECTED_FOLDER_ID, -1L)
val folderDisplayName = data.getStringExtra(ChooseFolderActivity.RESULT_FOLDER_DISPLAY_NAME)!!
handleChooseFolder(folderId, folderDisplayName)
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun handleChooseAccount(accountUuid: String) {
val userSelectedSameAccount = accountUuid == selectedAccountUuid
if (userSelectedSameAccount) {
return
}
selectedAccountUuid = accountUuid
selectedFolderId = null
selectedFolderDisplayName = null
unreadFolder.summary = getString(R.string.unread_widget_folder_summary)
if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) {
handleSearchAccount()
} else {
handleRegularAccount()
}
}
private fun handleSearchAccount() {
if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) {
unreadAccount.setSummary(R.string.unread_widget_unified_inbox_account_summary)
}
unreadFolderEnabled.isEnabled = false
unreadFolderEnabled.isChecked = false
unreadFolder.isEnabled = false
selectedFolderId = null
selectedFolderDisplayName = null
}
private fun handleRegularAccount() {
val selectedAccount = preferences.getAccount(selectedAccountUuid!!)
?: error("Account $selectedAccountUuid not found")
unreadAccount.summary = selectedAccount.displayName
unreadFolderEnabled.isEnabled = true
unreadFolder.isEnabled = true
}
private fun handleChooseFolder(folderId: Long, folderDisplayName: String) {
selectedFolderId = folderId
selectedFolderDisplayName = folderDisplayName
unreadFolder.summary = folderDisplayName
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.unread_widget_option, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.done -> {
if (validateWidget()) {
updateWidgetAndExit()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun validateWidget(): Boolean {
if (selectedAccountUuid == null) {
Toast.makeText(requireContext(), R.string.unread_widget_account_not_selected, Toast.LENGTH_LONG).show()
return false
} else if (unreadFolderEnabled.isChecked && selectedFolderId == null) {
Toast.makeText(requireContext(), R.string.unread_widget_folder_not_selected, Toast.LENGTH_LONG).show()
return false
}
return true
}
private fun updateWidgetAndExit() {
val configuration = UnreadWidgetConfiguration(appWidgetId, selectedAccountUuid!!, selectedFolderId)
repository.saveWidgetConfiguration(configuration)
unreadWidgetUpdater.update(appWidgetId)
// Let the caller know that the configuration was successful
val resultValue = Intent()
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
val activity = requireActivity()
activity.setResult(Activity.RESULT_OK, resultValue)
activity.finish()
}
private fun Bundle.putLongIfPresent(key: String, value: Long?) {
if (value != null) {
putLong(key, value)
}
}
private fun Bundle.getLongOrNull(key: String): Long? {
return if (containsKey(key)) getLong(key) else null
}
companion object {
private const val ARGUMENT_APP_WIDGET_ID = "app_widget_id"
private const val PREFERENCE_UNREAD_ACCOUNT = "unread_account"
private const val PREFERENCE_UNREAD_FOLDER_ENABLED = "unread_folder_enabled"
private const val PREFERENCE_UNREAD_FOLDER = "unread_folder"
private const val REQUEST_CHOOSE_ACCOUNT = 1
private const val REQUEST_CHOOSE_FOLDER = 2
private const val STATE_SELECTED_ACCOUNT_UUID = "com.fsck.k9.widget.unread.selectedAccountUuid"
private const val STATE_SELECTED_FOLDER_ID = "com.fsck.k9.widget.unread.selectedFolderId"
private const val STATE_SELECTED_FOLDER_DISPLAY_NAME = "com.fsck.k9.widget.unread.selectedFolderDisplayName"
fun create(appWidgetId: Int): UnreadWidgetConfigurationFragment {
return UnreadWidgetConfigurationFragment().apply {
arguments = bundleOf(ARGUMENT_APP_WIDGET_ID to appWidgetId)
}
}
}
}
| app/k9mail/src/main/java/com/fsck/k9/widget/unread/UnreadWidgetConfigurationFragment.kt | 1573756065 |
// 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.gradle.service.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionSorter
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.gradle.config.GradleFileType
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.lang.completion.api.GroovyCompletionConsumer
import org.jetbrains.plugins.groovy.lang.completion.api.GroovyCompletionCustomizer
import org.jetbrains.plugins.groovy.lang.completion.impl.AccumulatingGroovyCompletionConsumer
class GradleCompletionCustomizer : GroovyCompletionCustomizer {
override fun customizeCompletionConsumer(completionParameters: CompletionParameters,
resultSet: CompletionResultSet): CompletionResultSet {
if (completionParameters.originalFile.fileType == GradleFileType) {
val sorter = CompletionSorter.defaultSorter(completionParameters, resultSet.prefixMatcher)
return resultSet.withRelevanceSorter(sorter.weighBefore("templates", GradleLookupWeigher()))
} else {
return resultSet
}
}
override fun generateCompletionConsumer(file: PsiFile, resultSet: CompletionResultSet): GroovyCompletionConsumer? {
if (file.name.endsWith(GradleConstants.EXTENSION)) {
return AccumulatingGroovyCompletionConsumer(resultSet)
}
else {
return null
}
}
} | plugins/gradle/java/src/service/completion/GradleCompletionCustomizer.kt | 329988249 |
package com.livefront.bridgesample.common.view
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.annotation.StringRes
import com.livefront.bridgesample.R
import com.livefront.bridgesample.scenario.activity.SuccessActivity
import com.livefront.bridgesample.util.generateNoisyStripedBitmap
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.generateDataButton
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.headerText
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.imageView
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.navigateButton
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.statusText
/**
* A view that generates a [Bitmap] when clicking on a button. This `Bitmap` can then be retrieved
* as the [generatedBitmap] in order to test saving / restoring it. The
* [onNavigateButtonClickListener] may be set to provide some action when the corresponding button
* is clicked. If no such listener is set, the default behavior is to navigate to the
* [SuccessActivity].
*/
class BitmapGeneratorView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr, defStyleRes) {
var generatedBitmap: Bitmap? = null
/**
* Sets the [Bitmap] to display in this view. This will be considered as "restored" from a
* saved state.
*/
set(value) {
field = value
value?.let {
imageView.setImageBitmap(it)
statusText.setText(R.string.restored_from_saved_state)
}
}
var onBitmapGeneratedListener: ((Bitmap) -> Unit)? = null
var onNavigateButtonClickListener: (() -> Unit)? = null
init {
inflate(context, R.layout.view_bitmap_generator_content, this)
navigateButton.setOnClickListener {
onNavigateButtonClickListener
?.invoke()
?: (context as Activity).startActivity(
Intent(context, SuccessActivity::class.java)
)
}
generateDataButton.setOnClickListener {
generateDataButton.isEnabled = false
generateNoisyStripedBitmap { bitmap ->
generatedBitmap = bitmap
generateDataButton.isEnabled = true
imageView.setImageBitmap(bitmap)
statusText.setText(R.string.image_generated)
onBitmapGeneratedListener?.invoke(bitmap)
}
}
}
fun setHeaderText(@StringRes textRes: Int) {
headerText.setText(textRes)
}
}
| bridgesample/src/main/java/com/livefront/bridgesample/common/view/BitmapGeneratorView.kt | 3205865684 |
package just4fun.holomorph.forms
import just4fun.holomorph.*
import just4fun.holomorph.types.*
import just4fun.holomorph.types.*
/* RAW ARRAY factory */
/** The factory for Array<Any?> serialization form. */
object ArrayFactory: ProduceFactory<Array<*>, Array<*>> {
@Suppress("UNCHECKED_CAST")
val seqType = ArrayType(AnyType, Array<Any>::class) as SequenceType<Array<*>, Any>
override fun invoke(input: Array<*>): EntryProvider<Array<*>> = SequenceProvider(input, seqType)
override fun invoke(): EntryConsumer<Array<*>> = SequenceConsumer(seqType)
}
/* SEQUENCE */
/* Provider */
class SequenceProvider<T: Any, E: Any>(override val input: T, private val seqType: SequenceType<T, E>, private var initial: Boolean = true): EntryProvider<T> {
private val iterator = seqType.iterator(input)
override fun provideNextEntry(entryBuilder: EntryBuilder, provideName: Boolean): Entry {
return if (initial) run { initial = false; entryBuilder.StartEntry(null, false) }
else if (!iterator.hasNext()) entryBuilder.EndEntry()
else {
val v = iterator.next()
seqType.elementType.toEntry(v, null, entryBuilder)
}
}
}
/* Consumer */
class SequenceConsumer<T: Any, E: Any>(private val seqType: SequenceType<T, E>, private var initial: Boolean = true): EntryConsumer<T> {
private var instance: T = seqType.newInstance()
private var size = 0
override fun output(): T = seqType.onComplete(instance, size)
private fun addElement(value: Any?) {
val v = seqType.elementType.asInstance(value, true)
instance = seqType.addElement(v, size, instance)
size++
}
override fun consumeEntries(name: String?, subEntries: EnclosedEntries, expectNames: Boolean) {
if (initial) run { initial = false; subEntries.consume(); return }
addElement(seqType.elementType.fromEntries(subEntries, expectNames))
}
override fun consumeEntry(name: String?, value: ByteArray): Unit = addElement(value)
override fun consumeEntry(name: String?, value: String): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Long): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Int): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Double): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Float): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Boolean): Unit = addElement(value)
override fun consumeNullEntry(name: String?): Unit = addElement(null)
}
/* RAW COLLECTION */
/* Provider */
class RawCollectionProvider(override val input: Collection<Any?>, private var initial: Boolean = true): EntryProvider<Collection<Any?>> {
private val iterator = input.iterator()
override fun provideNextEntry(entryBuilder: EntryBuilder, provideName: Boolean): Entry {
return if (initial) run { initial = false; entryBuilder.StartEntry(null, false) }
else if (!iterator.hasNext()) entryBuilder.EndEntry()
else {
val v = iterator.next()
if (v == null) entryBuilder.NullEntry()
else {
val type = AnyType.detectType(v)
if (type == null) StringType.toEntry(v.toString(), null, entryBuilder)
else type.toEntry(v, null, entryBuilder)
}
}
}
}
/* Consumer */
// todo typeUtils detect type?
class RawCollectionConsumer(private var initial: Boolean = true): EntryConsumer<Collection<Any?>> {
var instance: Collection<Any?> = RawCollectionType.newInstance()
override fun output(): Collection<Any?> {
return RawCollectionType.onComplete(instance, instance.size)
}
override fun consumeEntries(name: String?, subEntries: EnclosedEntries, expectNames: Boolean) {
if (initial) run { initial = false; subEntries.consume(); return }
val v = subEntries.intercept(if (expectNames) RawMapConsumer(false) else RawCollectionConsumer(false))
addElement(v)
}
private fun addElement(value: Any?) {
instance = RawCollectionType.addElement(value, instance.size, instance)
}
override fun consumeEntry(name: String?, value: ByteArray): Unit = addElement(value)
override fun consumeEntry(name: String?, value: String): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Long): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Int): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Double): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Float): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Boolean): Unit = addElement(value)
override fun consumeNullEntry(name: String?): Unit = addElement(null)
}
| src/main/kotlin/just4fun/holomorph/forms/sequence.kt | 1500112382 |
@file:Suppress("ClassName")
package _Self.vcsRoots
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot
object Branch_191_193 : GitVcsRoot({
name = "https://github.com/JetBrains/ideavim (branch 191-193)"
url = "https://github.com/JetBrains/ideavim.git"
branch = "191-193"
useMirrors = false
})
| .teamcity/_Self/vcsRoots/Branch_191_193.kt | 2939957053 |
package _Self.subprojects
import _Self.buildTypes.TestsForIntelliJ20181
import _Self.buildTypes.TestsForIntelliJ20182
import _Self.buildTypes.TestsForIntelliJ20183
import _Self.buildTypes.TestsForIntelliJ20191
import _Self.buildTypes.TestsForIntelliJ20192
import _Self.buildTypes.TestsForIntelliJ20193
import _Self.buildTypes.TestsForIntelliJ20201
import _Self.buildTypes.TestsForIntelliJ20202
import _Self.buildTypes.TestsForIntelliJ20203
import _Self.buildTypes.TestsForIntelliJ20211
import _Self.buildTypes.TestsForIntelliJ20212
import _Self.buildTypes.TestsForIntelliJ20213
import _Self.buildTypes.TestsForIntelliJ20222
import jetbrains.buildServer.configs.kotlin.v2019_2.Project
object OldTests : Project({
name = "Old IdeaVim tests"
description = "Tests for older versions of IJ"
buildType(TestsForIntelliJ20181)
buildType(TestsForIntelliJ20182)
buildType(TestsForIntelliJ20183)
buildType(TestsForIntelliJ20191)
buildType(TestsForIntelliJ20192)
buildType(TestsForIntelliJ20193)
buildType(TestsForIntelliJ20201)
buildType(TestsForIntelliJ20202)
buildType(TestsForIntelliJ20203)
buildType(TestsForIntelliJ20211)
buildType(TestsForIntelliJ20212)
buildType(TestsForIntelliJ20213)
buildType(TestsForIntelliJ20222)
})
| .teamcity/_Self/subprojects/OldTests.kt | 5587765 |
package _Self.buildTypes
import _Self.Constants.DEV_VERSION
import _Self.Constants.EAP_CHANNEL
import _Self.Constants.RELEASE_EAP
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.DslContext
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.vcsLabeling
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.BuildFailureOnMetric
import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.failOnMetricChange
object ReleaseEap : BuildType({
name = "Publish EAP Build"
description = "Build and publish EAP of IdeaVim plugin"
artifactRules = "build/distributions/*"
buildNumberPattern = "$DEV_VERSION-eap.%build.counter%"
params {
param("env.ORG_GRADLE_PROJECT_ideaVersion", RELEASE_EAP)
password(
"env.ORG_GRADLE_PROJECT_publishToken",
"credentialsJSON:61a36031-4da1-4226-a876-b8148bf32bde",
label = "Password"
)
param("env.ORG_GRADLE_PROJECT_version", "%build.number%")
param("env.ORG_GRADLE_PROJECT_downloadIdeaSources", "false")
param("env.ORG_GRADLE_PROJECT_publishChannels", EAP_CHANNEL)
password(
"env.ORG_GRADLE_PROJECT_slackUrl",
"credentialsJSON:a8ab8150-e6f8-4eaf-987c-bcd65eac50b5",
label = "Slack Token"
)
}
vcs {
root(DslContext.settingsRoot)
checkoutMode = CheckoutMode.AUTO
}
steps {
gradle {
tasks = "clean publishPlugin"
buildFile = ""
enableStacktrace = true
param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL")
}
}
features {
vcsLabeling {
vcsRootId = "${DslContext.settingsRoot.id}"
labelingPattern = "%system.build.number%"
successfulOnly = true
branchFilter = ""
}
}
failureConditions {
failOnMetricChange {
metric = BuildFailureOnMetric.MetricType.ARTIFACT_SIZE
threshold = 5
units = BuildFailureOnMetric.MetricUnit.PERCENTS
comparison = BuildFailureOnMetric.MetricComparison.DIFF
compareTo = build {
buildRule = lastSuccessful()
}
}
}
})
| .teamcity/_Self/buildTypes/ReleaseEap.kt | 2730225441 |
package task1
import mpi.MPI
open class RootProcess(val hyperCubeSize: Int, var array: IntArray) {
val p = (2 pow hyperCubeSize).toInt()
private var n = array.size
val elementsOPerProcess = n / p
fun beginProcess() {
sendOutArray()
// collectArray()
}
fun resetArray() {
shuffle(array)
}
fun sendOutArray() {
for (i in 0..p - 1) {
MPI.COMM_WORLD.Isend(array, elementsOPerProcess * (i), elementsOPerProcess,
MPI.INT, i, Operation.INIT_ARRAY_SEND.ordinal)
}
}
fun collectArray() {
var offset = 0
for (i in 0..p - 1) {
val probeStatus = MPI.COMM_WORLD.Probe(i, Operation.COLLECT_ARRAY.ordinal)
var receiveElementNumber = probeStatus.Get_count(MPI.INT)
MPI.COMM_WORLD.Recv(array, offset, n - offset,
MPI.INT, i, Operation.COLLECT_ARRAY.ordinal)
offset += receiveElementNumber
}
}
} | TRPSV/src/main/kotlin/task1/RootProcess.kt | 2553807633 |
package org.ligi.passandroid.ui.pass_view_holder
import android.app.Activity
import androidx.cardview.widget.CardView
import android.view.View
import kotlinx.android.synthetic.main.pass_list_item.view.*
import kotlinx.android.synthetic.main.time_and_nav.view.*
import org.ligi.passandroid.model.PassStore
import org.ligi.passandroid.model.pass.Pass
class CondensedPassViewHolder(view: CardView) : PassViewHolder(view) {
override fun apply(pass: Pass, passStore: PassStore, activity: Activity) {
super.apply(pass, passStore, activity)
val extraString = getExtraString(pass)
if (extraString.isNullOrBlank()) {
view.date.visibility = View.GONE
} else {
view.date.text = extraString
view.date.visibility = View.VISIBLE
}
view.timeAndNavBar.timeButton.text = getTimeInfoString(pass)
}
}
| android/src/main/java/org/ligi/passandroid/ui/pass_view_holder/CondensedPassViewHolder.kt | 2890362369 |
package org.wordpress.android.ui.compose.theme
import android.annotation.SuppressLint
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val green40 = Color(0xff069e08)
private val green50 = Color(0xff008710)
private val red50 = Color(0xffd63638)
private val red30 = Color(0xfff86368)
private val white = Color(0xffffffff)
private val black = Color(0xff000000)
private val darkGray = Color(0xff121212)
@SuppressLint("ConflictingOnColor")
val JpLightColorPalette = lightColors(
primary = green50,
primaryVariant = green40,
secondary = green50,
secondaryVariant = green40,
background = white,
surface = white,
error = red50,
onPrimary = white,
onSecondary = white,
onBackground = black,
onSurface = black,
onError = white
)
@SuppressLint("ConflictingOnColor")
val JpDarkColorPalette = darkColors(
primary = green40,
primaryVariant = green50,
secondary = green40,
secondaryVariant = green50,
background = darkGray,
surface = darkGray,
error = red30,
onPrimary = black,
onSecondary = white,
onBackground = white,
onSurface = white,
onError = black
)
@Composable
fun JpColorPalette(isDarkTheme: Boolean = isSystemInDarkTheme()) = when (isDarkTheme) {
true -> JpDarkColorPalette
else -> JpLightColorPalette
}
| WordPress/src/main/java/org/wordpress/android/ui/compose/theme/JetpackColors.kt | 4289713982 |
package org.wordpress.android.ui.mysite.cards.dashboard.posts
enum class PostCardType(val id: Int) {
CREATE_FIRST(0),
CREATE_NEXT(1),
DRAFT(2),
SCHEDULED(3)
}
| WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/dashboard/posts/PostCardType.kt | 3046248463 |
package com.intellij.ide.actions.searcheverywhere.ml.features.statistician
data class SearchEverywhereStatisticianStats(val useCount: Int,
val isMostPopular: Boolean,
val recency: Int) {
val isMostRecent = recency == 0
}
| plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereStatisticianStats.kt | 2044374286 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.local.wizard
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.local.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.wizard.withVisualPadding
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ui.configuration.validateJavaVersion
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.dsl.builder.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded
import org.jdom.Element
import java.io.File
import java.net.SocketTimeoutException
import java.nio.file.Files
import java.nio.file.Path
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
open class StarterInitialStep(contextProvider: StarterContextProvider) : CommonStarterInitialStep(
contextProvider.wizardContext,
contextProvider.starterContext,
contextProvider.moduleBuilder,
contextProvider.parentDisposable,
contextProvider.settings
) {
protected val moduleBuilder: StarterModuleBuilder = contextProvider.moduleBuilder
protected val starterContext: StarterContext = contextProvider.starterContext
private val starterPackProvider: () -> StarterPack = contextProvider.starterPackProvider
private val contentPanel: DialogPanel by lazy { createComponent() }
protected lateinit var languageRow: Row
@Volatile
private var isDisposed: Boolean = false
override fun getHelpId(): String? = moduleBuilder.getHelpId()
init {
Disposer.register(parentDisposable, Disposable {
isDisposed = true
})
}
override fun updateDataModel() {
starterContext.projectType = projectTypeProperty.get()
starterContext.language = languageProperty.get()
starterContext.group = groupId
starterContext.artifact = artifactId
starterContext.testFramework = testFrameworkProperty.get()
starterContext.includeExamples = exampleCodeProperty.get()
starterContext.gitIntegration = gitProperty.get()
wizardContext.projectName = entityName
wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName))
val sdk = sdkProperty.get()
moduleBuilder.moduleJdk = sdk
if (wizardContext.project == null) {
wizardContext.projectJdk = sdk
}
}
override fun getComponent(): JComponent {
return contentPanel
}
private fun createComponent(): DialogPanel {
entityNameProperty.dependsOn(artifactIdProperty) { artifactId }
artifactIdProperty.dependsOn(entityNameProperty) { entityName }
// query dependencies from builder, called only once
val starterPack = starterPackProvider.invoke()
starterContext.starterPack = starterPack
updateStartersDependencies(starterPack)
return panel {
addProjectLocationUi()
addFieldsBefore(this)
if (starterSettings.applicationTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.app.type.label")) {
val applicationTypesModel = DefaultComboBoxModel<StarterAppType>()
applicationTypesModel.addAll(starterSettings.applicationTypes)
comboBox(applicationTypesModel, SimpleListCellRenderer.create("", StarterAppType::title))
.bindItem(applicationTypeProperty)
.columns(COLUMNS_MEDIUM)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.languages.size > 1) {
row(JavaStartersBundle.message("title.project.language.label")) {
languageRow = this
segmentedButton(starterSettings.languages, StarterLanguage::title)
.bind(languageProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.projectTypes.isNotEmpty()) {
val messages = starterSettings.customizedMessages
row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.build.system.label")) {
segmentedButton(starterSettings.projectTypes, StarterProjectType::title)
.bind(projectTypeProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.testFrameworks.size > 1) {
row(JavaStartersBundle.message("title.project.test.framework.label")) {
segmentedButton(starterSettings.testFrameworks, StarterTestRunner::title)
.bind(testFrameworkProperty)
bottomGap(BottomGap.SMALL)
}
}
addGroupArtifactUi()
addSdkUi()
addSampleCodeUi()
addFieldsAfter(this)
}.withVisualPadding(topField = true)
}
override fun validate(): Boolean {
if (!validateFormFields(component, contentPanel, validatedTextComponents)) {
return false
}
if (!validateJavaVersion(sdkProperty, moduleBuilder.getMinJavaVersionInternal()?.toFeatureString(), moduleBuilder.presentableName)) {
return false
}
return true
}
private fun updateStartersDependencies(starterPack: StarterPack) {
val starters = starterPack.starters
AppExecutorUtil.getAppExecutorService().submit {
checkDependencyUpdates(starters)
}
}
@RequiresBackgroundThread
private fun checkDependencyUpdates(starters: List<Starter>) {
for (starter in starters) {
val localUpdates = loadStarterDependencyUpdatesFromFile(starter.id)
if (localUpdates != null) {
setStarterDependencyUpdates(starter.id, localUpdates)
return
}
val externalUpdates = loadStarterDependencyUpdatesFromNetwork(starter.id) ?: return
val (dependencyUpdates, resourcePath) = externalUpdates
if (isDisposed) return
val dependencyConfig = StarterUtils.parseDependencyConfig(dependencyUpdates, resourcePath)
if (isDisposed) return
saveStarterDependencyUpdatesToFile(starter.id, dependencyUpdates)
setStarterDependencyUpdates(starter.id, dependencyConfig)
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromFile(starterId: String): DependencyConfig? {
val configUpdateDir = File(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
val configUpdateFile = File(configUpdateDir, getPatchFileName(starterId))
if (!configUpdateFile.exists()
|| StarterUtils.isDependencyUpdateFileExpired(configUpdateFile)) {
return null
}
val resourcePath = configUpdateFile.absolutePath
return try {
StarterUtils.parseDependencyConfig(JDOMUtil.load(configUpdateFile), resourcePath)
}
catch (e: Exception) {
logger<StarterInitialStep>().warn("Failed to load starter dependency updates from file: $resourcePath. The file will be deleted.")
FileUtil.delete(configUpdateFile)
null
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromNetwork(starterId: String): Pair<Element, String>? {
val url = buildStarterPatchUrl(starterId) ?: return null
return try {
val content = HttpRequests.request(url)
.accept("application/xml")
.readString()
return JDOMUtil.load(content) to url
}
catch (e: Exception) {
if (e is HttpRequests.HttpStatusException
&& (e.statusCode == 403 || e.statusCode == 404)) {
logger<StarterInitialStep>().debug("No updates for $starterId: $url")
}
else if (e is SocketTimeoutException) {
logger<StarterInitialStep>().debug("Socket timeout for $starterId: $url")
}
else {
logger<StarterInitialStep>().warn("Unable to load external starter $starterId dependency updates from: $url", e)
}
null
}
}
@RequiresBackgroundThread
private fun saveStarterDependencyUpdatesToFile(starterId: String, dependencyConfigUpdate: Element) {
val configUpdateDir = Path.of(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
if (!configUpdateDir.exists()) {
Files.createDirectories(configUpdateDir)
}
val configUpdateFile = configUpdateDir.resolve(getPatchFileName(starterId))
JDOMUtil.write(dependencyConfigUpdate, configUpdateFile)
}
private fun setStarterDependencyUpdates(starterId: String, dependencyConfigUpdate: DependencyConfig) {
invokeLaterIfNeeded {
if (isDisposed) return@invokeLaterIfNeeded
starterContext.startersDependencyUpdates[starterId] = dependencyConfigUpdate
}
}
private fun buildStarterPatchUrl(starterId: String): String? {
val host = Registry.stringValue("starters.dependency.update.host").nullize(true) ?: return null
val ideVersion = ApplicationInfoImpl.getShadowInstance().let { "${it.majorVersion}.${it.minorVersion}" }
val patchFileName = getPatchFileName(starterId)
return "$host/starter/$starterId/$ideVersion/$patchFileName"
}
private fun getDependencyConfigUpdatesDirLocation(starterId: String): String = "framework-starters/$starterId/"
private fun getPatchFileName(starterId: String): String = "${starterId}_patch.pom"
} | java/idea-ui/src/com/intellij/ide/starters/local/wizard/StarterInitialStep.kt | 2677225797 |
package pl.elpassion.cloudtimer
import android.app.PendingIntent
import android.app.PendingIntent.*
import android.content.Intent
import android.support.test.espresso.Espresso.closeSoftKeyboard
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import pl.elpassion.cloudtimer.ComponentsTestsUtils.pressButton
import pl.elpassion.cloudtimer.alarm.AlarmReceiver
import pl.elpassion.cloudtimer.alarm.AlarmReceiver.Companion.REQUEST_CODE
import pl.elpassion.cloudtimer.timer.TimerActivity
@RunWith(AndroidJUnit4::class)
class AlarmServiceTest {
@Rule @JvmField
val rule = rule<TimerActivity>{}
private val alarmReceiverClass = AlarmReceiver::class.java
@Test
fun alarmSchedulerNoPendingIntentsAtStart() {
clearIntent()
val alarmUp = getPendingIntent()
assertNull(alarmUp)
}
@Test
fun alarmSchedulerCreatesPendingIntent() {
clearIntent()
closeSoftKeyboard()
pressButton(R.id.start_timer_button)
val alarmUp = getPendingIntent()
assertNotNull(alarmUp)
}
@Test
fun alarmSchedulerNoRandomIntentType() {
clearIntent()
val requestCodeToTry = 123
closeSoftKeyboard()
pressButton(R.id.start_timer_button)
val alarmUp = getPendingIntent(requestCodeToTry)
assertNull(alarmUp)
}
private fun clearIntent() {
val intent = Intent(rule.activity, alarmReceiverClass)
getBroadcast(rule.activity, REQUEST_CODE, intent, FLAG_CANCEL_CURRENT).cancel()
}
private fun getPendingIntent() = getPendingIntent(REQUEST_CODE)
private fun getPendingIntent(reqCode: Int): PendingIntent? {
val intent = Intent(rule.activity, alarmReceiverClass)
return getBroadcast(rule.activity, reqCode, intent, FLAG_NO_CREATE)
}
}
| app/src/androidTest/java/pl/elpassion/cloudtimer/AlarmServiceTest.kt | 3268058725 |
/*
* LeapTransitData.kt
*
* Copyright 2018-2019 Google
*
* 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 au.id.micolous.metrodroid.transit.tfi_leap
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.TimestampFull
internal fun<T> valuesCompatible(a: T?, b: T?): Boolean =
(a == null || b == null || a == b)
@Parcelize
internal class LeapTripPoint (val mTimestamp: TimestampFull?,
val mAmount: Int?,
private val mEventCode: Int?,
val mStation: Int?): Parcelable {
fun isMergeable(other: LeapTripPoint?): Boolean =
other == null || (
valuesCompatible(mAmount, other.mAmount) &&
valuesCompatible(mTimestamp, other.mTimestamp) &&
valuesCompatible(mEventCode, other.mEventCode) &&
valuesCompatible(mStation, other.mStation)
)
companion object {
fun merge(a: LeapTripPoint?, b: LeapTripPoint?) = LeapTripPoint(
mAmount = a?.mAmount ?: b?.mAmount,
mTimestamp = a?.mTimestamp ?: b?.mTimestamp,
mEventCode = a?.mEventCode ?: b?.mEventCode,
mStation = a?.mStation ?: b?.mStation
)
}
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/transit/tfi_leap/LeapTripPoint.kt | 636958580 |
/*
* ClassicStaticKeys.kt
*
* Copyright 2018-2019 Google
*
* 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 au.id.micolous.metrodroid.key
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.R
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.json
/**
* Helper for access to static MIFARE Classic keys. This can be used for keys that should be
* attempted on multiple cards.
*
* This is only really useful when a transit agency doesn't implement key diversification.
*
* See https://github.com/micolous/metrodroid/wiki/Importing-MIFARE-Classic-keys#static-json for
* a file format description.
*/
class ClassicStaticKeys private constructor(override val description: String?,
override val keys: Map<Int, List<ClassicSectorAlgoKey>>,
override val sourceDataLength: Int)
: ClassicKeysImpl() {
internal operator fun plus(other: ClassicStaticKeys): ClassicStaticKeys {
return ClassicStaticKeys(description = description,
keys = flattenKeys(listOf(this, other)),
sourceDataLength = sourceDataLength + other.sourceDataLength)
}
override fun toJSON(): JsonObject {
if (description == null)
return baseJson
return JsonObject(baseJson + json {
JSON_TAG_ID_DESC to description
})
}
val allBundles get() = keys.values.flatten().map { it.bundle }.toSet()
override val type = CardKeys.TYPE_MFC_STATIC
override val uid = CardKeys.CLASSIC_STATIC_TAG_ID
override val fileType: String
get() = Localizer.localizePlural(R.plurals.keytype_mfc_static, keyCount, keyCount)
companion object {
private const val JSON_TAG_ID_DESC = "Description"
fun fallback() = ClassicStaticKeys(description = "fallback",
keys = mapOf(), sourceDataLength = 0)
fun flattenKeys(lst: List<ClassicStaticKeys>): Map<Int, List<ClassicSectorAlgoKey>> {
val keys = mutableMapOf<Int, MutableList<ClassicSectorAlgoKey>>()
for (who in lst)
for ((key, value) in who.keys) {
if (!keys.containsKey(key))
keys[key] = mutableListOf()
keys[key]?.addAll(value)
}
return keys
}
fun fromJSON(jsonRoot: JsonObject, defaultBundle: String) = try {
ClassicStaticKeys(
description = jsonRoot.getPrimitiveOrNull(JSON_TAG_ID_DESC)?.contentOrNull,
keys = ClassicKeysImpl.keysFromJSON(jsonRoot, false, defaultBundle),
sourceDataLength = jsonRoot.toString().length)
} catch (e: Exception) {
Log.e("ClassicStaticKeys", "parsing failed", e)
null
}
}
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/key/ClassicStaticKeys.kt | 4175879561 |
/*
* Copyright 2010 Kevin Gaudin
*
* 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.acra.collector
import android.content.Context
import android.os.Build
import android.os.Environment
import com.google.auto.service.AutoService
import org.acra.ReportField
import org.acra.builder.ReportBuilder
import org.acra.config.CoreConfiguration
import org.acra.data.CrashReportData
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.lang.reflect.InvocationTargetException
/**
* Collector retrieving key/value pairs from static fields and getters.
* Reflection API usage allows to retrieve data without having to implement a class for each android version of each interesting class.
* It can also help find hidden properties.
*
* @author Kevin Gaudin & F43nd1r
*/
@AutoService(Collector::class)
class ReflectionCollector : BaseReportFieldCollector(ReportField.BUILD, ReportField.BUILD_CONFIG, ReportField.ENVIRONMENT) {
@Throws(JSONException::class, ClassNotFoundException::class)
override fun collect(reportField: ReportField, context: Context, config: CoreConfiguration, reportBuilder: ReportBuilder, target: CrashReportData) {
val result = JSONObject()
when (reportField) {
ReportField.BUILD -> {
collectConstants(Build::class.java, result, exclude = listOf("SERIAL"))
val version = JSONObject()
collectConstants(Build.VERSION::class.java, version)
result.put("VERSION", version)
}
ReportField.BUILD_CONFIG -> collectConstants(getBuildConfigClass(context, config), result)
ReportField.ENVIRONMENT -> collectStaticGettersResults(Environment::class.java, result)
else -> throw IllegalArgumentException()
}
target.put(reportField, result)
}
/**
* Retrieves key/value pairs from static getters of a class (get*() or is*()).
*
* @param someClass the class to be inspected.
*/
@Throws(JSONException::class)
private fun collectStaticGettersResults(someClass: Class<*>, container: JSONObject) {
val methods = someClass.methods
for (method in methods) {
if (method.parameterTypes.isEmpty() && (method.name.startsWith("get") || method.name.startsWith("is"))
&& "getClass" != method.name) {
try {
container.put(method.name, method.invoke(null))
} catch (ignored: IllegalArgumentException) {
// NOOP
} catch (ignored: InvocationTargetException) {
// NOOP
} catch (ignored: IllegalAccessException) {
// NOOP
}
}
}
}
/**
* get the configured BuildConfigClass or guess it if not configured
*
* @return the BuildConfigClass
* @throws ClassNotFoundException if the class cannot be found
*/
@Throws(ClassNotFoundException::class)
private fun getBuildConfigClass(context: Context, config: CoreConfiguration): Class<*> {
return config.buildConfigClass ?: Class.forName(context.packageName + ".BuildConfig")
}
companion object {
/**
* Retrieves key/value pairs from static fields of a class.
*
* @param someClass the class to be inspected.
*/
@Throws(JSONException::class)
private fun collectConstants(someClass: Class<*>, container: JSONObject, exclude: Collection<String> = emptyList()) {
val fields = someClass.fields
for (field in fields) {
if(field.name in exclude) continue
try {
val value = field[null]
if (value != null) {
if (field.type.isArray) {
@Suppress("UNCHECKED_CAST")
container.put(field.name, JSONArray(listOf(*value as Array<Any?>)))
} else {
container.put(field.name, value)
}
}
} catch (ignored: IllegalArgumentException) {
// NOOP
} catch (ignored: IllegalAccessException) {
// NOOP
}
}
}
}
} | acra-core/src/main/java/org/acra/collector/ReflectionCollector.kt | 2431300441 |
package com.github.florent37.assets_audio_player.playerimplem
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Log
import com.github.florent37.assets_audio_player.AssetAudioPlayerThrowable
import com.github.florent37.assets_audio_player.AssetsAudioPlayerPlugin
import com.github.florent37.assets_audio_player.Player
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.C.AUDIO_SESSION_ID_UNSET
import com.google.android.exoplayer2.Player.REPEAT_MODE_ALL
import com.google.android.exoplayer2.Player.REPEAT_MODE_OFF
import com.google.android.exoplayer2.drm.*
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.extractor.ts.AdtsExtractor
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.upstream.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
import java.io.File
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class IncompatibleException(val audioType: String, val type: PlayerImplemTesterExoPlayer.Type) : Throwable()
class PlayerImplemTesterExoPlayer(private val type: Type) : PlayerImplemTester {
enum class Type {
Default,
HLS,
DASH,
SmoothStreaming
}
override suspend fun open(configuration: PlayerFinderConfiguration): PlayerFinder.PlayerWithDuration {
if (AssetsAudioPlayerPlugin.displayLogs) {
Log.d("PlayerImplem", "trying to open with exoplayer($type)")
}
//some type are only for web
if (configuration.audioType != Player.AUDIO_TYPE_LIVESTREAM && configuration.audioType != Player.AUDIO_TYPE_LIVESTREAM) {
if (type == Type.HLS || type == Type.DASH || type == Type.SmoothStreaming) {
throw IncompatibleException(configuration.audioType, type)
}
}
val mediaPlayer = PlayerImplemExoPlayer(
onFinished = {
configuration.onFinished?.invoke()
//stop(pingListener = false)
},
onBuffering = {
configuration.onBuffering?.invoke(it)
},
onError = { t ->
configuration.onError?.invoke(t)
},
type = this.type
)
try {
val durationMS = mediaPlayer.open(
context = configuration.context,
assetAudioPath = configuration.assetAudioPath,
audioType = configuration.audioType,
assetAudioPackage = configuration.assetAudioPackage,
networkHeaders = configuration.networkHeaders,
flutterAssets = configuration.flutterAssets,
drmConfiguration = configuration.drmConfiguration
)
return PlayerFinder.PlayerWithDuration(
player = mediaPlayer,
duration = durationMS
)
} catch (t: Throwable) {
if (AssetsAudioPlayerPlugin.displayLogs) {
Log.d("PlayerImplem", "failed to open with exoplayer($type)")
}
mediaPlayer.release()
throw t
}
}
}
class PlayerImplemExoPlayer(
onFinished: (() -> Unit),
onBuffering: ((Boolean) -> Unit),
onError: ((AssetAudioPlayerThrowable) -> Unit),
val type: PlayerImplemTesterExoPlayer.Type
) : PlayerImplem(
onFinished = onFinished,
onBuffering = onBuffering,
onError = onError
) {
private var mediaPlayer: ExoPlayer? = null
override var loopSingleAudio: Boolean
get() = mediaPlayer?.repeatMode == REPEAT_MODE_ALL
set(value) {
mediaPlayer?.repeatMode = if (value) REPEAT_MODE_ALL else REPEAT_MODE_OFF
}
override val isPlaying: Boolean
get() = mediaPlayer?.isPlaying ?: false
override val currentPositionMs: Long
get() = mediaPlayer?.currentPosition ?: 0
override fun stop() {
mediaPlayer?.stop()
}
override fun play() {
mediaPlayer?.playWhenReady = true
}
override fun pause() {
mediaPlayer?.playWhenReady = false
}
private fun getDataSource(context: Context,
flutterAssets: FlutterPlugin.FlutterAssets,
assetAudioPath: String?,
audioType: String,
networkHeaders: Map<*, *>?,
assetAudioPackage: String?,
drmConfiguration: Map<*, *>?
): MediaSource {
try {
mediaPlayer?.stop()
when (audioType) {
Player.AUDIO_TYPE_NETWORK, Player.AUDIO_TYPE_LIVESTREAM -> {
val uri = Uri.parse(assetAudioPath)
val mediaItem: MediaItem = MediaItem.fromUri(uri)
val userAgent = "assets_audio_player"
val factory = DataSource.Factory {
val allowCrossProtocol = true
val dataSource = DefaultHttpDataSource.Factory().setUserAgent(userAgent).setAllowCrossProtocolRedirects(allowCrossProtocol).createDataSource()
networkHeaders?.forEach {
it.key?.let { key ->
it.value?.let { value ->
dataSource.setRequestProperty(key.toString(), value.toString())
}
}
}
dataSource
}
return when (type) {
PlayerImplemTesterExoPlayer.Type.HLS -> HlsMediaSource.Factory(factory).setAllowChunklessPreparation(true)
PlayerImplemTesterExoPlayer.Type.DASH -> DashMediaSource.Factory(factory)
PlayerImplemTesterExoPlayer.Type.SmoothStreaming -> SsMediaSource.Factory(factory)
else -> ProgressiveMediaSource.Factory(factory, DefaultExtractorsFactory().setAdtsExtractorFlags(AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING))
}.createMediaSource(mediaItem)
}
Player.AUDIO_TYPE_FILE -> {
val uri = Uri.parse(assetAudioPath)
var mediaItem: MediaItem = MediaItem.fromUri(uri)
val factory = ProgressiveMediaSource
.Factory(DefaultDataSource.Factory(context), DefaultExtractorsFactory())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
val key = drmConfiguration?.get("clearKey")?.toString()
if (key != null) {
val mediaItemDrmConfiguration: MediaItem.DrmConfiguration = MediaItem.DrmConfiguration.Builder(C.CLEARKEY_UUID).setKeySetId(key.toByteArray()).build()
mediaItem = mediaItem.buildUpon().setDrmConfiguration(mediaItemDrmConfiguration).build()
factory.setDrmSessionManagerProvider(DefaultDrmSessionManagerProvider())
}
}
return factory.createMediaSource(mediaItem)
}
else -> { //asset$
val p = assetAudioPath!!.replace(" ", "%20")
val path = if (assetAudioPackage.isNullOrBlank()) {
flutterAssets.getAssetFilePathByName(p)
} else {
flutterAssets.getAssetFilePathByName(p, assetAudioPackage)
}
val assetDataSource = AssetDataSource(context)
assetDataSource.open(DataSpec(Uri.fromFile(File(path))))
val factory = DataSource.Factory { assetDataSource }
return ProgressiveMediaSource
.Factory(factory, DefaultExtractorsFactory())
.createMediaSource(MediaItem.fromUri(assetDataSource.uri!!))
}
}
} catch (e: Exception) {
throw e
}
}
private fun ExoPlayer.Builder.incrementBufferSize(audioType: String): ExoPlayer.Builder {
if (audioType == Player.AUDIO_TYPE_NETWORK || audioType == Player.AUDIO_TYPE_LIVESTREAM) {
/* Instantiate a DefaultLoadControl.Builder. */
val loadControlBuilder = DefaultLoadControl.Builder()
/*How many milliseconds of media data to buffer at any time. */
val loadControlBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS /* This is 50000 milliseconds in ExoPlayer 2.9.6 */
/* Configure the DefaultLoadControl to use the same value for */
loadControlBuilder.setBufferDurationsMs(
loadControlBufferMs,
loadControlBufferMs,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
return this.setLoadControl(loadControlBuilder.build())
}
return this
}
fun mapError(t: Throwable): AssetAudioPlayerThrowable {
return when {
t is ExoPlaybackException -> {
(t.cause as? HttpDataSource.InvalidResponseCodeException)?.takeIf { it.responseCode >= 400 }?.let {
AssetAudioPlayerThrowable.UnreachableException(t)
} ?: let {
AssetAudioPlayerThrowable.NetworkError(t)
}
}
t.message?.contains("unable to connect", true) == true -> {
AssetAudioPlayerThrowable.NetworkError(t)
}
else -> {
AssetAudioPlayerThrowable.PlayerError(t)
}
}
}
override suspend fun open(
context: Context,
flutterAssets: FlutterPlugin.FlutterAssets,
assetAudioPath: String?,
audioType: String,
networkHeaders: Map<*, *>?,
assetAudioPackage: String?,
drmConfiguration: Map<*, *>?
) = suspendCoroutine<DurationMS> { continuation ->
var onThisMediaReady = false
try {
mediaPlayer = ExoPlayer.Builder(context)
.incrementBufferSize(audioType)
.build()
val mediaSource = getDataSource(
context = context,
flutterAssets = flutterAssets,
assetAudioPath = assetAudioPath,
audioType = audioType,
networkHeaders = networkHeaders,
assetAudioPackage = assetAudioPackage,
drmConfiguration = drmConfiguration
)
var lastState: Int? = null
this.mediaPlayer?.addListener(object : com.google.android.exoplayer2.Player.Listener {
override fun onPlayerError(error: PlaybackException) {
val errorMapped = mapError(error)
if (!onThisMediaReady) {
continuation.resumeWithException(errorMapped)
} else {
onError(errorMapped)
}
}
override fun onPlaybackStateChanged(playbackState: Int) {
if (lastState != playbackState) {
when (playbackState) {
ExoPlayer.STATE_ENDED -> {
pause()
onFinished.invoke()
onBuffering.invoke(false)
}
ExoPlayer.STATE_BUFFERING -> {
onBuffering.invoke(true)
}
ExoPlayer.STATE_READY -> {
onBuffering.invoke(false)
if (!onThisMediaReady) {
onThisMediaReady = true
//retrieve duration in seconds
if (audioType == Player.AUDIO_TYPE_LIVESTREAM) {
continuation.resume(0) //no duration for livestream
} else {
val duration = mediaPlayer?.duration ?: 0
continuation.resume(duration)
}
}
}
else -> {
}
}
}
lastState = playbackState
}
})
mediaPlayer?.setMediaSource(mediaSource)
mediaPlayer?.prepare()
} catch (error: Throwable) {
if (!onThisMediaReady) {
continuation.resumeWithException(error)
} else {
onBuffering.invoke(false)
onError(mapError(error))
}
}
}
override fun release() {
mediaPlayer?.release()
}
override fun seekTo(to: Long) {
mediaPlayer?.seekTo(to)
}
override fun setVolume(volume: Float) {
mediaPlayer?.volume = volume
}
override fun setPlaySpeed(playSpeed: Float) {
val params: PlaybackParameters? = mediaPlayer?.playbackParameters
if (params != null) {
mediaPlayer?.playbackParameters = PlaybackParameters(playSpeed, params.pitch)
}
}
override fun setPitch(pitch: Float) {
val params: PlaybackParameters? = mediaPlayer?.playbackParameters
if (params != null) {
mediaPlayer?.playbackParameters = PlaybackParameters(params.speed, pitch)
}
}
override fun getSessionId(listener: (Int) -> Unit) {
val id = mediaPlayer?.audioSessionId?.takeIf { it != AUDIO_SESSION_ID_UNSET }
if (id != null) {
listener(id)
} else {
val listener = object : com.google.android.exoplayer2.Player.Listener {
override fun onAudioSessionIdChanged(audioSessionId: Int) {
listener(audioSessionId)
mediaPlayer?.removeListener(this)
}
}
mediaPlayer?.addListener(listener)
}
//return
}
} | android/src/main/kotlin/com/github/florent37/assets_audio_player/playerimplem/PlayerImplemExoPlayer.kt | 2739714745 |
package io.github.fvasco.pinpoi.importer
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.github.fvasco.pinpoi.util.Coordinates
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author Francesco Vasco
*/
@RunWith(AndroidJUnit4::class)
class TextImporterTest : AbstractImporterTestCase() {
@Test
fun testImportImplAsc() {
val list = importPlacemark(TextImporter(), "asc.txt")
assertEquals(4, list.size)
}
@Test
fun testImportImplCsv() {
val list = importPlacemark(TextImporter(), "csv.txt")
assertEquals(3, list.size)
assertEquals(Coordinates(1.0F, 2.5F), list[0].coordinates)
assertEquals("location1 to import", list[0].name)
}
@Test
fun testImportImplCsvLatLon() {
val list = importPlacemark(TextImporter(), "csv.txt", FileFormatFilter.CSV_LAT_LON)
assertEquals(Coordinates(1.0F, 2.5F), list[0].coordinates)
assertEquals("location1 to import", list[0].name)
}
@Test
fun testImportImplCsvLonLat() {
val list = importPlacemark(TextImporter(), "csv.txt", FileFormatFilter.CSV_LON_LAT)
assertEquals(Coordinates(2.5F, 1.0F), list[0].coordinates)
assertEquals("location1 to import", list[0].name)
}
}
| app/src/androidTest/java/io/github/fvasco/pinpoi/importer/TextImporterTest.kt | 2638183860 |
// WITH_STDLIB
class Foo {
companion object {
fun bar(str: String) = str.toInt() + str.toInt()
}
}
fun test() {
"foo".let(Foo::bar<caret>)
}
| plugins/kotlin/idea/tests/testData/intentions/convertReferenceToLambda/companionNoImport2.kt | 2616282396 |
object ConvertMe6 {
@JvmStatic
fun foo(a: SimpleClass?) {}
fun foo(a: SimpleClass?, b: SimpleClass?) {}
}
| plugins/kotlin/j2k/new/tests/testData/multiFile/StaticAnnotation/6.kt | 2269664056 |
fun check() {
""
<caret>.length
}
// SET_FALSE: CONTINUATION_INDENT_FOR_CHAINED_CALLS | plugins/kotlin/idea/tests/testData/editor/enterHandler/beforeDot/StringLiteralInFirstPosition.after.kt | 3716545100 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.config
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
import com.intellij.util.application
import com.intellij.util.ui.VcsExecutablePathSelector
import git4idea.GitVcs
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.CalledInAny
internal class GitExecutableSelectorPanel(val project: Project, val disposable: Disposable) {
companion object {
fun Panel.createGitExecutableSelectorRow(project: Project, disposable: Disposable) {
val panel = GitExecutableSelectorPanel(project, disposable)
with(panel) {
createRow()
}
}
}
private val applicationSettings get() = GitVcsApplicationSettings.getInstance()
private val projectSettings get() = GitVcsSettings.getInstance(project)
private val pathSelector = VcsExecutablePathSelector(GitVcs.DISPLAY_NAME.get(), disposable, GitExecutableHandler())
@Volatile
private var versionCheckRequested = false
init {
application.messageBus.connect(disposable).subscribe(GitExecutableManager.TOPIC,
GitExecutableListener { runInEdt(getModalityState()) { resetPathSelector() } })
BackgroundTaskUtil.executeOnPooledThread(disposable) {
GitExecutableManager.getInstance().getDetectedExecutable(project, true) // detect executable if needed
}
}
private fun Panel.createRow() = row {
cell(pathSelector.mainPanel)
.align(AlignX.FILL)
.onReset {
resetPathSelector()
}
.onIsModified {
pathSelector.isModified(
applicationSettings.savedPathToGit,
projectSettings.pathToGit != null,
projectSettings.pathToGit)
}
.onApply {
val currentPath = pathSelector.currentPath
if (pathSelector.isOverridden) {
projectSettings.pathToGit = currentPath
}
else {
applicationSettings.setPathToGit(currentPath)
projectSettings.pathToGit = null
}
validateExecutableOnceAfterClose()
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
}
}
private fun resetPathSelector() {
pathSelector.setAutoDetectedPath(GitExecutableManager.getInstance().getDetectedExecutable(project, false))
pathSelector.reset(
applicationSettings.savedPathToGit,
projectSettings.pathToGit != null,
projectSettings.pathToGit)
}
private fun testGitExecutable(pathToGit: String) {
val modalityState = getModalityState()
val errorNotifier = InlineErrorNotifierFromSettings(
GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null),
modalityState, disposable
)
if (!project.isDefault && !project.isTrusted()) {
errorNotifier.showError(GitBundle.message("git.executable.validation.cant.run.in.safe.mode"), null)
return
}
object : Task.Modal(project, GitBundle.message("git.executable.version.progress.title"), true) {
private lateinit var gitVersion: GitVersion
override fun run(indicator: ProgressIndicator) {
val executableManager = GitExecutableManager.getInstance()
val executable = executableManager.getExecutable(pathToGit)
executableManager.dropVersionCache(executable)
gitVersion = executableManager.identifyVersion(executable)
}
override fun onThrowable(error: Throwable) {
val problemHandler = findGitExecutableProblemHandler(project)
problemHandler.showError(error, errorNotifier)
}
override fun onSuccess() {
if (gitVersion.isSupported) {
errorNotifier.showMessage(GitBundle.message("git.executable.version.is", gitVersion.presentation))
}
else {
showUnsupportedVersionError(project, gitVersion, errorNotifier)
}
}
}.queue()
}
/**
* Special method to check executable after it has been changed through settings
*/
private fun validateExecutableOnceAfterClose() {
if (versionCheckRequested) return
versionCheckRequested = true
runInEdt(ModalityState.NON_MODAL) {
versionCheckRequested = false
runBackgroundableTask(GitBundle.message("git.executable.version.progress.title"), project, true) {
GitExecutableManager.getInstance().testGitExecutableVersionValid(project)
}
}
}
private fun getModalityState() = ModalityState.stateForComponent(pathSelector.mainPanel)
private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent,
private val modalityState: ModalityState,
disposable: Disposable)
: InlineErrorNotifier(inlineComponent, modalityState, disposable) {
@CalledInAny
override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) {
if (fixOption is ErrorNotifier.FixOption.Configure) {
super.showError(text, description, null)
}
else {
super.showError(text, description, fixOption)
}
}
override fun resetGitExecutable() {
super.resetGitExecutable()
GitExecutableManager.getInstance().getDetectedExecutable(project, true) // populate cache
invokeAndWaitIfNeeded(modalityState) {
resetPathSelector()
}
}
}
private inner class GitExecutableHandler : VcsExecutablePathSelector.ExecutableHandler {
override fun patchExecutable(executable: String): String? {
return GitExecutableDetector.patchExecutablePath(executable)
}
override fun testExecutable(executable: String) {
testGitExecutable(executable)
}
}
} | plugins/git4idea/src/git4idea/config/GitExecutableSelectorPanel.kt | 3512392088 |
package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.util.EventDispatcher
import java.util.*
val NOTEBOOK_CELL_LINES_INTERVAL_DATA_KEY = DataKey.create<NotebookCellLines.Interval>("NOTEBOOK_CELL_LINES_INTERVAL")
/**
* Incrementally iterates over Notebook document, calculates line ranges of cells using lexer.
* Fast enough for running in EDT, but could be used in any other thread.
*
* Note: there's a difference between this model and the PSI model.
* If a document starts not with a cell marker, this class treat the text before the first cell marker as a raw cell.
* PSI model treats such cell as a special "stem" cell which is not a Jupyter cell at all.
* We haven't decided which model is correct and which should be fixed. So, for now avoid using stem cells in tests,
* while UI of PyCharm DS doesn't allow to create a stem cell at all.
*/
interface NotebookCellLines {
enum class CellType {
CODE, MARKDOWN, RAW
}
data class Marker(
val ordinal: Int,
val type: CellType,
val offset: Int,
val length: Int
) : Comparable<Marker> {
override fun compareTo(other: Marker): Int = offset - other.offset
}
enum class MarkersAtLines(val hasTopLine: Boolean, val hasBottomLine: Boolean) {
NO(false, false),
TOP(true, false),
BOTTOM(false, true),
TOP_AND_BOTTOM(true, true)
}
data class Interval(
val ordinal: Int,
val type: CellType,
val lines: IntRange,
val markers: MarkersAtLines,
) : Comparable<Interval> {
override fun compareTo(other: Interval): Int = lines.first - other.lines.first
}
interface IntervalListener : EventListener {
/**
* Called each time when document is changed, even if intervals are the same.
* Contains DocumentEvent and additional information about intervals.
* Components which work with intervals can simply listen for NotebookCellLinesEvent and don't subscribe for DocumentEvent.
*/
fun documentChanged(event: NotebookCellLinesEvent)
fun beforeDocumentChange(event: NotebookCellLinesEventBeforeChange) {}
}
fun intervalsIterator(startLine: Int = 0): ListIterator<Interval>
val intervals: List<Interval>
val intervalListeners: EventDispatcher<IntervalListener>
val modificationStamp: Long
companion object {
fun get(document: Document): NotebookCellLines =
NotebookCellLinesProvider.get(document)?.create(document)
?: error("Can't get NotebookCellLinesProvider for document ${document}")
fun hasSupport(document: Document): Boolean =
NotebookCellLinesProvider.get(document) != null
fun get(editor: Editor): NotebookCellLines =
get(editor.document)
fun hasSupport(editor: Editor): Boolean =
hasSupport(editor.document)
}
} | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLines.kt | 2816921962 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.GeneratedIdentificator
import org.jetbrains.kotlin.tools.projectWizard.Identificator
import org.jetbrains.kotlin.tools.projectWizard.IdentificatorOwner
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ModuleConfiguratorSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingType
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.*
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.templates.Template
@Suppress("EnumEntryName")
enum class ModuleKind(val isSinglePlatform: Boolean) : DisplayableSettingItem {
multiplatform(isSinglePlatform = false),
target(isSinglePlatform = false),
singlePlatformJvm(isSinglePlatform = true),
singlePlatformAndroid(isSinglePlatform = true),
singlePlatformJsBrowser(isSinglePlatform = true),
singlePlatformJsNode(isSinglePlatform = true),
;
override val text: String
@Suppress("HardCodedStringLiteral")
get() = name
}
/**
* @param template selected by default if any, should be present in [permittedTemplateIds].
* @param permittedTemplateIds when specified the set restricts templates available for the module. Final decision (on whether a template
* is included) is made on a template level, see [Template.isSupportedByModuleType].
*/
class Module(
@NonNls var name: String,
val configurator: ModuleConfigurator,
var template: Template? = null,
val permittedTemplateIds: Set<String>? = null,
val sourceSets: List<Sourceset> = createDefaultSourceSets(),
subModules: List<Module> = emptyList(),
val dependencies: MutableList<ModuleReference> = mutableListOf(),
var parent: Module? = null,
override val identificator: Identificator = GeneratedIdentificator(name)
) : DisplayableSettingItem, Validatable<Module>, IdentificatorOwner {
val kind: ModuleKind
get() = configurator.moduleKind
override val validator = (moduleNameValidator and
moduleConfiguratorValidator and
moduleTemplateValidator).withTarget(this) and
subModulesValidator
var subModules = subModules
set(value) {
field = value
value.forEach { it.parent = this }
}
init {
subModules.forEach { it.parent = this }
sourceSets.forEach { it.parent = this }
}
@Suppress("HardCodedStringLiteral")
override val text: String get() = name
override val greyText: String
get() = when {
kind == ModuleKind.target -> configurator.text + " " + KotlinNewProjectWizardBundle.message("module.kind.target")
configurator == MppModuleConfigurator -> KotlinNewProjectWizardBundle.message("module.kind.mpp.module")
configurator == AndroidSinglePlatformModuleConfigurator -> KotlinNewProjectWizardBundle.message("module.kind.android.module")
configurator == IOSSinglePlatformModuleConfigurator -> KotlinNewProjectWizardBundle.message("module.kind.ios.module")
configurator == BrowserJsSinglePlatformModuleConfigurator -> KotlinNewProjectWizardBundle.message("module.kind.js.browser.module")
configurator == NodeJsSinglePlatformModuleConfigurator -> KotlinNewProjectWizardBundle.message("module.kind.js.node.module")
else -> KotlinNewProjectWizardBundle.message("module.kind.module")
}
fun SettingsWriter.initDefaultValuesForSettings() {
configurator.safeAs<ModuleConfiguratorWithSettings>()?.apply { initDefaultValuesFor(this@Module) }
configurator.safeAs<ModuleConfiguratorWithProperties>()?.apply { initDefaultValuesForProperties(this@Module) }
template?.apply { initDefaultValuesFor(this@Module) }
}
companion object {
val ALLOWED_SPECIAL_CHARS_IN_MODULE_NAMES = setOf('-', '_')
val parser: Parser<Module> = mapParser { map, path ->
val (name) = map.parseValue<String>(path, "name")
val identifier = GeneratedIdentificator(name)
val (configurator) = map.parseValue(this, path, "type", ModuleConfigurator.getParser(identifier))
val template = map["template"]?.let {
Template.parser(identifier).parse(this, it, "$path.template")
}.nullableValue()
val sourceSets = listOf(Sourceset(SourcesetType.main), Sourceset(SourcesetType.test))
val (submodules) = map.parseValue(this, path, "subModules", listParser(Module.parser)) { emptyList() }
val (dependencies) = map.parseValue(this, path, "dependencies", listParser(ModuleReference.ByPath.parser)) { emptyList() }
Module(
name, configurator, template = template, sourceSets = sourceSets, subModules = submodules,
dependencies = dependencies.toMutableList(), identificator = identifier
)
}
private val moduleNameValidator = settingValidator<Module> { module ->
StringValidators.shouldNotBeBlank(KotlinNewProjectWizardBundle.message("module.name")).validate(this, module.name)
} and settingValidator { module ->
StringValidators.shouldBeValidIdentifier(
KotlinNewProjectWizardBundle.message("module.name", module.name),
ALLOWED_SPECIAL_CHARS_IN_MODULE_NAMES
).validate(this, module.name)
}
val moduleConfiguratorValidator = settingValidator<Module> { module ->
inContextOfModuleConfigurator(module) {
allSettingsOfModuleConfigurator(module.configurator).map { setting ->
val reference = when (setting) {
is PluginSetting<Any, SettingType<Any>> -> setting.reference
is ModuleConfiguratorSetting<Any, SettingType<Any>> -> setting.reference
else -> null
}
val value = reference?.notRequiredSettingValue
?: reference?.savedOrDefaultValue
?: return@map ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"validation.should.not.be.blank",
setting.title.capitalize()
)
)
setting.validator.validate(this@settingValidator, value)
}.fold()
}
}
val moduleTemplateValidator = settingValidator<Module> { module ->
val template = module.template ?: return@settingValidator ValidationResult.OK
org.jetbrains.kotlin.tools.projectWizard.templates.withSettingsOf(module) {
template.settings.map { setting ->
val value = setting.reference.notRequiredSettingValue
?: setting.reference.savedOrDefaultValue
?: return@map ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"validation.should.not.be.blank",
setting.title.capitalize()
)
)
(setting.validator as SettingValidator<Any>).validate(this@settingValidator, value)
}.fold()
}
}
val subModulesValidator = inValidatorContext<Module> { module ->
validateList(module.subModules)
}
private fun createDefaultSourceSets() =
SourcesetType.values().map { sourceSetType -> Sourceset(sourceSetType, dependencies = emptyList()) }
}
}
val Module.path
get() = generateSequence(this, Module::parent)
.map { it.name }
.toList()
.asReversed()
.let(::ModulePath)
val Sourceset.path
get() = ModulePath(parent?.path?.parts.orEmpty() + sourcesetType.name)
val Module.isRootModule
get() = parent == null
@Suppress("FunctionName")
fun MultiplatformTargetModule(
@NonNls name: String,
configurator: ModuleConfigurator,
sourceSets: List<Sourceset>,
permittedTemplateIds: Set<String>? = null
) =
Module(name, configurator, sourceSets = sourceSets, permittedTemplateIds = permittedTemplateIds)
@Suppress("FunctionName")
fun MultiplatformModule(
@NonNls name: String,
template: Template? = null,
targets: List<Module> = emptyList(),
permittedTemplateIds: Set<String>? = null
) =
Module(name, MppModuleConfigurator, template = template, permittedTemplateIds = permittedTemplateIds, subModules = targets)
@Suppress("FunctionName")
fun SinglePlatformModule(@NonNls name: String, sourceSets: List<Sourceset>, permittedTemplateIds: Set<String>? = null) =
Module(name, JvmSinglePlatformModuleConfigurator, sourceSets = sourceSets, permittedTemplateIds = permittedTemplateIds)
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/settings/buildsystem/Module.kt | 2343486668 |
fun foo() {
1 <caret>is Int
}
// DISALLOW_METHOD_CALLS
// EXPECTED: 1 is Int
// EXPECTED_LEGACY: null | plugins/kotlin/jvm-debugger/test/testData/selectExpression/disallowMethodCalls/isExpression.kt | 2460925350 |
package com.intellij.tools.launch
import com.intellij.tools.launch.impl.ClassPathBuilder
import com.intellij.util.JavaModuleOptions
import com.intellij.util.system.OS
import org.jetbrains.intellij.build.dependencies.TeamCityHelper
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
import java.nio.file.Files
import java.util.logging.Logger
object Launcher {
private const val defaultDebugPort = 5050
private val logger = Logger.getLogger(Launcher::class.java.name)
fun launch(paths: PathsProvider,
modules: ModulesProvider,
options: LauncherOptions,
logClasspath: Boolean): Process {
val classPathBuilder = ClassPathBuilder(paths, modules)
logger.info("Building classpath")
val classPathArgFile = classPathBuilder.build(logClasspath)
logger.info("Done building classpath")
return launch(paths, classPathArgFile, options)
}
fun launch(paths: PathsProvider,
classPathArgFile: File,
options: LauncherOptions): Process {
// We should create config folder to avoid import settings dialog.
Files.createDirectories(paths.configFolder.toPath())
val cmd = mutableListOf(
paths.javaExecutable.canonicalPath,
"-ea",
"-Dapple.laf.useScreenMenuBar=true",
"-Dfus.internal.test.mode=true",
"-Djb.privacy.policy.text=\"<!--999.999-->\"",
"-Djb.consents.confirmation.enabled=false",
"-Didea.suppress.statistics.report=true",
"-Drsch.send.usage.stat=false",
"-Duse.linux.keychain=false",
"-Didea.initially.ask.config=never",
"-Dide.show.tips.on.startup.default.value=false",
"-Didea.config.path=${paths.configFolder.canonicalPath}",
"-Didea.system.path=${paths.systemFolder.canonicalPath}",
"-Didea.log.path=${paths.logFolder.canonicalPath}",
"-Didea.is.internal=true",
"-Didea.debug.mode=true",
"-Didea.jre.check=true",
"-Didea.fix.mac.env=true",
"-Djdk.attach.allowAttachSelf",
"-Djdk.module.illegalAccess.silent=true",
"-Djava.system.class.loader=com.intellij.util.lang.PathClassLoader",
"-Dkotlinx.coroutines.debug=off",
"-Dsun.awt.disablegrab=true",
"-Dsun.io.useCanonCaches=false",
"-Dteamcity.build.tempDir=${paths.tempFolder.canonicalPath}",
"-Xmx${options.xmx}m",
"-XX:+UseG1GC",
"-XX:-OmitStackTraceInFastThrow",
"-XX:CICompilerCount=2",
"-XX:HeapDumpPath=${paths.tempFolder.canonicalPath}",
"-XX:MaxJavaStackTraceDepth=10000",
"-XX:ReservedCodeCacheSize=240m",
"-XX:SoftRefLRUPolicyMSPerMB=50",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+BytecodeVerificationLocal",
"-Dshared.indexes.download.auto.consent=true"
)
val optionsOpenedFile = paths.communityRootFolder.resolve("plugins/devkit/devkit-core/src/run/OpenedPackages.txt")
val optionsOpenedPackages = JavaModuleOptions.readOptions(optionsOpenedFile.toPath(), OS.CURRENT)
cmd.addAll(optionsOpenedPackages)
if (options.platformPrefix != null) {
cmd.add("-Didea.platform.prefix=${options.platformPrefix}")
}
if (!TeamCityHelper.isUnderTeamCity) {
val suspendOnStart = if (options.debugSuspendOnStart) "y" else "n"
val port = if (options.debugPort > 0) options.debugPort else findFreeDebugPort()
// changed in Java 9, now we have to use *: to listen on all interfaces
val host = if (options.runInDocker) "*:" else ""
cmd.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=$suspendOnStart,address=$host$port")
}
for (arg in options.javaArguments) {
cmd.add(arg.trim('"'))
}
cmd.add("@${classPathArgFile.canonicalPath}")
cmd.add("com.intellij.idea.Main")
for (arg in options.ideaArguments) {
cmd.add(arg.trim('"'))
}
/*
println("Starting cmd:")
for (arg in cmd) {
println(" $arg")
}
println("-- END")
*/
return if (options.runInDocker) {
val docker = DockerLauncher(paths, options as DockerLauncherOptions)
docker.assertCanRun()
docker.runInContainer(cmd)
}
else {
val processBuilder = ProcessBuilder(cmd)
processBuilder.affixIO(options.redirectOutputIntoParentProcess, paths.logFolder)
processBuilder.environment().putAll(options.environment)
options.beforeProcessStart.invoke(processBuilder)
processBuilder.start()
}
}
fun ProcessBuilder.affixIO(redirectOutputIntoParentProcess: Boolean, logFolder: File) {
if (redirectOutputIntoParentProcess) {
this.inheritIO()
}
else {
logFolder.mkdirs()
// TODO: test logs overwrite launcher logs
this.redirectOutput(logFolder.resolve("out.log"))
this.redirectError(logFolder.resolve("err.log"))
}
}
fun findFreeDebugPort(): Int {
if (isDefaultPortFree()) {
return defaultDebugPort
}
val socket = ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"))
val result = socket.localPort
socket.reuseAddress = true
socket.close()
return result
}
private fun isDefaultPortFree(): Boolean {
var socket: ServerSocket? = null
try {
socket = ServerSocket(defaultDebugPort, 0, InetAddress.getByName("127.0.0.1"))
socket.reuseAddress = true
return true
}
catch (e: Exception) {
return false
}
finally {
socket?.close()
}
}
} | build/launch/src/com/intellij/tools/launch/Launcher.kt | 2221942514 |
fun test(value: Any?) {
value<caret>
} | plugins/kotlin/code-insight/postfix-templates/testData/expansion/with/simple.kt | 3451844367 |
package org.thoughtcrime.securesms.database.model
data class LocalMetricsSplit(
val name: String,
val duration: Long
) {
override fun toString(): String {
return "$name: $duration"
}
}
| app/src/main/java/org/thoughtcrime/securesms/database/model/LocalMetricsSplit.kt | 3447505527 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.navigation.animation
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.navigation.NavHostController
import androidx.navigation.NoOpNavigator
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.get
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalAnimationApi::class)
@LargeTest
@RunWith(AndroidJUnit4::class)
class NavHostControllerTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun testRememberAnimatedNavController() {
lateinit var navController: NavHostController
composeTestRule.setContent {
navController = rememberAnimatedNavController()
// get state to trigger recompose on navigate
navController.currentBackStackEntryAsState().value
AnimatedNavHost(navController, startDestination = first) {
composable(first) { BasicText(first) }
composable(second) { BasicText(second) }
}
}
val navigator = composeTestRule.runOnIdle {
navController.navigatorProvider[AnimatedComposeNavigator::class]
}
// trigger recompose
composeTestRule.runOnIdle {
navController.navigate(second)
}
composeTestRule.runOnIdle {
assertThat(navController.navigatorProvider[AnimatedComposeNavigator::class])
.isEqualTo(navigator)
}
}
@Test
fun testRememberAnimatedNavControllerAddsCustomNavigator() {
lateinit var navController: NavHostController
composeTestRule.setContent {
val customNavigator = remember { NoOpNavigator() }
navController = rememberAnimatedNavController(customNavigator)
// get state to trigger recompose on navigate
navController.currentBackStackEntryAsState().value
AnimatedNavHost(navController, startDestination = first) {
composable(first) { BasicText(first) }
composable(second) { BasicText(second) }
}
}
val navigator = composeTestRule.runOnIdle {
navController.navigatorProvider[NoOpNavigator::class]
}
// trigger recompose
composeTestRule.runOnIdle {
navController.navigate(second)
}
composeTestRule.runOnIdle {
assertThat(navController.navigatorProvider[NoOpNavigator::class])
.isEqualTo(navigator)
}
}
}
private const val first = "first"
private const val second = "second"
| navigation-animation/src/androidTest/java/com/google/accompanist/navigation/animation/NavHostControllerTest.kt | 342794710 |
package com.example.santaev.domain.repository
import com.example.santaev.domain.api.IApiService
import com.example.santaev.domain.api.LanguagesResponseDto
import com.example.santaev.domain.database.ILanguageDao
import com.example.santaev.domain.dto.LanguageDto
import com.example.santaev.domain.repository.ILanguageRepository.LanguagesState
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
internal class LanguageRepository(
private val languageDao: ILanguageDao,
private val apiService: IApiService
) : ILanguageRepository {
private var languagesLoadingStatus: LanguagesState? = null
set(value) {
field = value
if (value != null) languagesStatusSubject.onNext(value)
}
private val languagesStatusSubject = PublishSubject.create<LanguagesState>()
override fun requestLanguages(): Observable<LanguagesState> {
loadLanguages()
return languagesStatusSubject
}
override fun getLanguages(): Flowable<List<LanguageDto>> {
loadLanguages()
return languageDao.getLanguages()
}
private fun loadLanguages() {
if (languagesLoadingStatus == LanguagesState.LOADING) return
languagesLoadingStatus = LanguagesState.LOADING
apiService.getLanguages()
.subscribeOn(Schedulers.io())
.subscribe(
this::onLoadLanguages,
{ error ->
error.printStackTrace()
languagesLoadingStatus = LanguagesState.ERROR
}
)
}
private fun onLoadLanguages(languagesResponse: LanguagesResponseDto) {
languagesLoadingStatus = LanguagesState.SUCCESS
languageDao.insertAll(languagesResponse.languages)
}
}
| domain/src/main/java/com/example/santaev/domain/repository/LanguageRepository.kt | 2424646708 |
package lt.markmerkk.worklogs
import lt.markmerkk.Mocks
import lt.markmerkk.TimeProviderTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WorklogUploadValidatorKtTest {
private val timeProvider = TimeProviderTest()
@Test
fun localLog() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(1),
code = "WT-66",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogValid::class.java)
}
@Test
fun noComment() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "WT-66",
comment = "",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidNoComment::class.java)
}
@Test
fun notValidTicket() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "invalid_ticket",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidNoTicketCode::class.java)
}
@Test
fun durationLessThanOneMinute() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusSeconds(59),
code = "WT-66",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidDurationTooLittle::class.java)
}
@Test
fun remoteLog() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "WT-66",
comment = "valid_comment",
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidAlreadyRemote::class.java)
}
} | remote/src/test/java/lt/markmerkk/worklogs/WorklogUploadValidatorKtTest.kt | 1274128027 |
package glm
data class DoubleVec3(val x: Double, val y: Double, val z: Double) {
// Initializes each element by evaluating init from 0 until 2
constructor(init: (Int) -> Double) : this(init(0), init(1), init(2))
operator fun get(idx: Int): Double = when (idx) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): DoubleVec3 = DoubleVec3(x.inc(), y.inc(), z.inc())
operator fun dec(): DoubleVec3 = DoubleVec3(x.dec(), y.dec(), z.dec())
operator fun unaryPlus(): DoubleVec3 = DoubleVec3(+x, +y, +z)
operator fun unaryMinus(): DoubleVec3 = DoubleVec3(-x, -y, -z)
operator fun plus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x + rhs.x, y + rhs.y, z + rhs.z)
operator fun minus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x - rhs.x, y - rhs.y, z - rhs.z)
operator fun times(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x * rhs.x, y * rhs.y, z * rhs.z)
operator fun div(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x / rhs.x, y / rhs.y, z / rhs.z)
operator fun rem(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x % rhs.x, y % rhs.y, z % rhs.z)
operator fun plus(rhs: Double): DoubleVec3 = DoubleVec3(x + rhs, y + rhs, z + rhs)
operator fun minus(rhs: Double): DoubleVec3 = DoubleVec3(x - rhs, y - rhs, z - rhs)
operator fun times(rhs: Double): DoubleVec3 = DoubleVec3(x * rhs, y * rhs, z * rhs)
operator fun div(rhs: Double): DoubleVec3 = DoubleVec3(x / rhs, y / rhs, z / rhs)
operator fun rem(rhs: Double): DoubleVec3 = DoubleVec3(x % rhs, y % rhs, z % rhs)
inline fun map(func: (Double) -> Double): DoubleVec3 = DoubleVec3(func(x), func(y), func(z))
fun toList(): List<Double> = listOf(x, y, z)
// Predefined vector constants
companion object Constants {
val zero: DoubleVec3 = DoubleVec3(0.0, 0.0, 0.0)
val ones: DoubleVec3 = DoubleVec3(1.0, 1.0, 1.0)
val unitX: DoubleVec3 = DoubleVec3(1.0, 0.0, 0.0)
val unitY: DoubleVec3 = DoubleVec3(0.0, 1.0, 0.0)
val unitZ: DoubleVec3 = DoubleVec3(0.0, 0.0, 1.0)
}
// Conversions to Float
fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toVec4(w: Float = 0f, conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w)
// Conversions to Float
fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toMutableVec4(w: Float = 0f, conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toDoubleVec(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y)
inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec3(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x, y, z, w)
inline fun toDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y)
inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec3(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w)
inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toIntVec4(w: Int = 0, conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toMutableIntVec4(w: Int = 0, conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toLongVec4(w: Long = 0L, conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toMutableLongVec4(w: Long = 0L, conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec3(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec3(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toByteVec(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec3(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec3(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toCharVec4(w: Char, conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toMutableCharVec4(w: Char, conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0)
inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec3(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0)
inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec3(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toMutableBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toStringVec4(w: String = "", conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toMutableStringVec4(w: String = "", conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(w: T2, conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(w: T2, conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: DoubleVec2 get() = DoubleVec2(x, x)
val xy: DoubleVec2 get() = DoubleVec2(x, y)
val xz: DoubleVec2 get() = DoubleVec2(x, z)
val yx: DoubleVec2 get() = DoubleVec2(y, x)
val yy: DoubleVec2 get() = DoubleVec2(y, y)
val yz: DoubleVec2 get() = DoubleVec2(y, z)
val zx: DoubleVec2 get() = DoubleVec2(z, x)
val zy: DoubleVec2 get() = DoubleVec2(z, y)
val zz: DoubleVec2 get() = DoubleVec2(z, z)
val xxx: DoubleVec3 get() = DoubleVec3(x, x, x)
val xxy: DoubleVec3 get() = DoubleVec3(x, x, y)
val xxz: DoubleVec3 get() = DoubleVec3(x, x, z)
val xyx: DoubleVec3 get() = DoubleVec3(x, y, x)
val xyy: DoubleVec3 get() = DoubleVec3(x, y, y)
val xyz: DoubleVec3 get() = DoubleVec3(x, y, z)
val xzx: DoubleVec3 get() = DoubleVec3(x, z, x)
val xzy: DoubleVec3 get() = DoubleVec3(x, z, y)
val xzz: DoubleVec3 get() = DoubleVec3(x, z, z)
val yxx: DoubleVec3 get() = DoubleVec3(y, x, x)
val yxy: DoubleVec3 get() = DoubleVec3(y, x, y)
val yxz: DoubleVec3 get() = DoubleVec3(y, x, z)
val yyx: DoubleVec3 get() = DoubleVec3(y, y, x)
val yyy: DoubleVec3 get() = DoubleVec3(y, y, y)
val yyz: DoubleVec3 get() = DoubleVec3(y, y, z)
val yzx: DoubleVec3 get() = DoubleVec3(y, z, x)
val yzy: DoubleVec3 get() = DoubleVec3(y, z, y)
val yzz: DoubleVec3 get() = DoubleVec3(y, z, z)
val zxx: DoubleVec3 get() = DoubleVec3(z, x, x)
val zxy: DoubleVec3 get() = DoubleVec3(z, x, y)
val zxz: DoubleVec3 get() = DoubleVec3(z, x, z)
val zyx: DoubleVec3 get() = DoubleVec3(z, y, x)
val zyy: DoubleVec3 get() = DoubleVec3(z, y, y)
val zyz: DoubleVec3 get() = DoubleVec3(z, y, z)
val zzx: DoubleVec3 get() = DoubleVec3(z, z, x)
val zzy: DoubleVec3 get() = DoubleVec3(z, z, y)
val zzz: DoubleVec3 get() = DoubleVec3(z, z, z)
val xxxx: DoubleVec4 get() = DoubleVec4(x, x, x, x)
val xxxy: DoubleVec4 get() = DoubleVec4(x, x, x, y)
val xxxz: DoubleVec4 get() = DoubleVec4(x, x, x, z)
val xxyx: DoubleVec4 get() = DoubleVec4(x, x, y, x)
val xxyy: DoubleVec4 get() = DoubleVec4(x, x, y, y)
val xxyz: DoubleVec4 get() = DoubleVec4(x, x, y, z)
val xxzx: DoubleVec4 get() = DoubleVec4(x, x, z, x)
val xxzy: DoubleVec4 get() = DoubleVec4(x, x, z, y)
val xxzz: DoubleVec4 get() = DoubleVec4(x, x, z, z)
val xyxx: DoubleVec4 get() = DoubleVec4(x, y, x, x)
val xyxy: DoubleVec4 get() = DoubleVec4(x, y, x, y)
val xyxz: DoubleVec4 get() = DoubleVec4(x, y, x, z)
val xyyx: DoubleVec4 get() = DoubleVec4(x, y, y, x)
val xyyy: DoubleVec4 get() = DoubleVec4(x, y, y, y)
val xyyz: DoubleVec4 get() = DoubleVec4(x, y, y, z)
val xyzx: DoubleVec4 get() = DoubleVec4(x, y, z, x)
val xyzy: DoubleVec4 get() = DoubleVec4(x, y, z, y)
val xyzz: DoubleVec4 get() = DoubleVec4(x, y, z, z)
val xzxx: DoubleVec4 get() = DoubleVec4(x, z, x, x)
val xzxy: DoubleVec4 get() = DoubleVec4(x, z, x, y)
val xzxz: DoubleVec4 get() = DoubleVec4(x, z, x, z)
val xzyx: DoubleVec4 get() = DoubleVec4(x, z, y, x)
val xzyy: DoubleVec4 get() = DoubleVec4(x, z, y, y)
val xzyz: DoubleVec4 get() = DoubleVec4(x, z, y, z)
val xzzx: DoubleVec4 get() = DoubleVec4(x, z, z, x)
val xzzy: DoubleVec4 get() = DoubleVec4(x, z, z, y)
val xzzz: DoubleVec4 get() = DoubleVec4(x, z, z, z)
val yxxx: DoubleVec4 get() = DoubleVec4(y, x, x, x)
val yxxy: DoubleVec4 get() = DoubleVec4(y, x, x, y)
val yxxz: DoubleVec4 get() = DoubleVec4(y, x, x, z)
val yxyx: DoubleVec4 get() = DoubleVec4(y, x, y, x)
val yxyy: DoubleVec4 get() = DoubleVec4(y, x, y, y)
val yxyz: DoubleVec4 get() = DoubleVec4(y, x, y, z)
val yxzx: DoubleVec4 get() = DoubleVec4(y, x, z, x)
val yxzy: DoubleVec4 get() = DoubleVec4(y, x, z, y)
val yxzz: DoubleVec4 get() = DoubleVec4(y, x, z, z)
val yyxx: DoubleVec4 get() = DoubleVec4(y, y, x, x)
val yyxy: DoubleVec4 get() = DoubleVec4(y, y, x, y)
val yyxz: DoubleVec4 get() = DoubleVec4(y, y, x, z)
val yyyx: DoubleVec4 get() = DoubleVec4(y, y, y, x)
val yyyy: DoubleVec4 get() = DoubleVec4(y, y, y, y)
val yyyz: DoubleVec4 get() = DoubleVec4(y, y, y, z)
val yyzx: DoubleVec4 get() = DoubleVec4(y, y, z, x)
val yyzy: DoubleVec4 get() = DoubleVec4(y, y, z, y)
val yyzz: DoubleVec4 get() = DoubleVec4(y, y, z, z)
val yzxx: DoubleVec4 get() = DoubleVec4(y, z, x, x)
val yzxy: DoubleVec4 get() = DoubleVec4(y, z, x, y)
val yzxz: DoubleVec4 get() = DoubleVec4(y, z, x, z)
val yzyx: DoubleVec4 get() = DoubleVec4(y, z, y, x)
val yzyy: DoubleVec4 get() = DoubleVec4(y, z, y, y)
val yzyz: DoubleVec4 get() = DoubleVec4(y, z, y, z)
val yzzx: DoubleVec4 get() = DoubleVec4(y, z, z, x)
val yzzy: DoubleVec4 get() = DoubleVec4(y, z, z, y)
val yzzz: DoubleVec4 get() = DoubleVec4(y, z, z, z)
val zxxx: DoubleVec4 get() = DoubleVec4(z, x, x, x)
val zxxy: DoubleVec4 get() = DoubleVec4(z, x, x, y)
val zxxz: DoubleVec4 get() = DoubleVec4(z, x, x, z)
val zxyx: DoubleVec4 get() = DoubleVec4(z, x, y, x)
val zxyy: DoubleVec4 get() = DoubleVec4(z, x, y, y)
val zxyz: DoubleVec4 get() = DoubleVec4(z, x, y, z)
val zxzx: DoubleVec4 get() = DoubleVec4(z, x, z, x)
val zxzy: DoubleVec4 get() = DoubleVec4(z, x, z, y)
val zxzz: DoubleVec4 get() = DoubleVec4(z, x, z, z)
val zyxx: DoubleVec4 get() = DoubleVec4(z, y, x, x)
val zyxy: DoubleVec4 get() = DoubleVec4(z, y, x, y)
val zyxz: DoubleVec4 get() = DoubleVec4(z, y, x, z)
val zyyx: DoubleVec4 get() = DoubleVec4(z, y, y, x)
val zyyy: DoubleVec4 get() = DoubleVec4(z, y, y, y)
val zyyz: DoubleVec4 get() = DoubleVec4(z, y, y, z)
val zyzx: DoubleVec4 get() = DoubleVec4(z, y, z, x)
val zyzy: DoubleVec4 get() = DoubleVec4(z, y, z, y)
val zyzz: DoubleVec4 get() = DoubleVec4(z, y, z, z)
val zzxx: DoubleVec4 get() = DoubleVec4(z, z, x, x)
val zzxy: DoubleVec4 get() = DoubleVec4(z, z, x, y)
val zzxz: DoubleVec4 get() = DoubleVec4(z, z, x, z)
val zzyx: DoubleVec4 get() = DoubleVec4(z, z, y, x)
val zzyy: DoubleVec4 get() = DoubleVec4(z, z, y, y)
val zzyz: DoubleVec4 get() = DoubleVec4(z, z, y, z)
val zzzx: DoubleVec4 get() = DoubleVec4(z, z, z, x)
val zzzy: DoubleVec4 get() = DoubleVec4(z, z, z, y)
val zzzz: DoubleVec4 get() = DoubleVec4(z, z, z, z)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Double, y: Double, z: Double): DoubleVec3 = DoubleVec3(x, y, z)
operator fun Double.plus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this + rhs.x, this + rhs.y, this + rhs.z)
operator fun Double.minus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this - rhs.x, this - rhs.y, this - rhs.z)
operator fun Double.times(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this * rhs.x, this * rhs.y, this * rhs.z)
operator fun Double.div(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this / rhs.x, this / rhs.y, this / rhs.z)
operator fun Double.rem(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this % rhs.x, this % rhs.y, this % rhs.z)
| GlmKt/src/glm/vec/Double/DoubleVec3.kt | 794709217 |
package io.armcha.ribble.presentation.screen.auth
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import io.armcha.ribble.R
import io.armcha.ribble.presentation.base_mvp.base.BaseActivity
import io.armcha.ribble.presentation.screen.home.HomeActivity
import io.armcha.ribble.presentation.utils.extensions.onClick
import io.armcha.ribble.presentation.utils.extensions.showToast
import io.armcha.ribble.presentation.utils.extensions.start
import io.armcha.ribble.presentation.utils.extensions.takeColor
import kotlinx.android.synthetic.main.activity_auth.*
import kotlinx.android.synthetic.main.progress_bar.*
import javax.inject.Inject
class AuthActivity : BaseActivity<AuthContract.View, AuthContract.Presenter>(), AuthContract.View {
@Inject
protected lateinit var authPresenter: AuthPresenter
override fun initPresenter(): AuthContract.Presenter = authPresenter
override fun injectDependencies() {
activityComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
progressBar.backgroundCircleColor = takeColor(io.armcha.ribble.R.color.colorPrimary)
login.onClick {
presenter.makeLogin()
}
}
override fun showLoading() {
progressBar.start()
login.isClickable = false
}
override fun hideLoading() {
progressBar.stop()
login.isClickable = true
}
override fun onDestroy() {
progressBar.dismiss()
super.onDestroy()
}
override fun showError(message: String?) {
showErrorDialog(message)
}
override fun startOAuthIntent(uri: Uri) {
startActivity(Intent(Intent.ACTION_VIEW, uri))
}
override fun openHomeActivity() {
start<HomeActivity>()
finish()
showToast(getString(io.armcha.ribble.R.string.logged_in_message))
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
presenter.checkLogin(intent)
}
}
| app/src/main/kotlin/io/armcha/ribble/presentation/screen/auth/AuthActivity.kt | 2379232746 |
package github.jk1.smtpidea.store
import javax.mail.internet.MimeMessage
import javax.swing.SwingUtilities
import java.util.ArrayList
import javax.mail.Flags.Flag
/**
*
*/
public object InboxFolder : MessageFolder<MimeMessage>(){
private val columns = array("Index", "Subject", "Seen", "Deleted")
private val mails: MutableList<MimeMessage> = ArrayList();
override fun getMessages(): List<MimeMessage> {
return mails;
}
override fun messageCount(): Int {
return mails.size;
}
override fun get(i: Int): MimeMessage {
return mails[i]
}
public override fun add(message: MimeMessage) {
SwingUtilities.invokeAndWait({
InboxFolder.mails.add(message)
InboxFolder.fireTableDataChanged()
})
}
public override fun clear() {
SwingUtilities.invokeAndWait({
InboxFolder.mails.clear()
InboxFolder.fireTableDataChanged()
})
}
/**
* @return - sum of octet size of all messages in this folder
*/
fun totalSize(): Int {
return mails.fold(0, {(sum, item) -> sum + item.getSize()})
}
override fun getColumnCount(): Int = 4
public override fun getRowCount() : Int = messageCount();
override fun getColumnName(column: Int): String = columns[column]
override fun getColumnClass(columnIndex: Int) = if (columnIndex > 1) javaClass<Boolean>() else javaClass<String>()
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
when(columnIndex) {
0 -> return rowIndex
1 -> return this[rowIndex].getSubject();
2 -> return this[rowIndex].isSet(Flag.SEEN)
3 -> return this[rowIndex].isSet(Flag.DELETED)
}
throw IllegalArgumentException("No data available for column index $columnIndex")
}
}
| src/main/kotlin/github/jk1/smtpidea/store/InboxFolder.kt | 2820564564 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package openxr.templates
import org.lwjgl.generator.*
import openxr.*
val MSFT_composition_layer_reprojection = "MSFTCompositionLayerReprojection".nativeClassXR("MSFT_composition_layer_reprojection", type = "instance", postfix = "MSFT") {
documentation =
"""
The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_MSFT_composition_layer_reprojection">XR_MSFT_composition_layer_reprojection</a> extension.
This extension enables an application to provide additional reprojection information for a projection composition layer to help the runtime produce better hologram stability and visual quality.
"""
IntConstant(
"The extension specification version.",
"MSFT_composition_layer_reprojection_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"MSFT_COMPOSITION_LAYER_REPROJECTION_EXTENSION_NAME".."XR_MSFT_composition_layer_reprojection"
)
EnumConstant(
"Extends {@code XrStructureType}.",
"TYPE_COMPOSITION_LAYER_REPROJECTION_INFO_MSFT".."1000066000",
"TYPE_COMPOSITION_LAYER_REPROJECTION_PLANE_OVERRIDE_MSFT".."1000066001"
)
EnumConstant(
"Extends {@code XrResult}.",
"ERROR_REPROJECTION_MODE_UNSUPPORTED_MSFT".."-1000066000"
)
EnumConstant(
"""
XrReprojectionModeMSFT - Describes the reprojection mode of a composition layer
<h5>Description</h5>
<ul>
<li>#REPROJECTION_MODE_DEPTH_MSFT indicates the corresponding layer <b>may</b> benefit from per-pixel depth reprojection provided by ##XrCompositionLayerDepthInfoKHR to the projection layer. This mode is typically used for world-locked content that should remain physically stationary as the user walks around.</li>
<li>#REPROJECTION_MODE_PLANAR_FROM_DEPTH_MSFT indicates the corresponding layer <b>may</b> benefit from planar reprojection and the plane <b>can</b> be calculated from the corresponding depth information provided by ##XrCompositionLayerDepthInfoKHR to the projection layer. This mode works better when the application knows the content is mostly placed on a plane.</li>
<li>#REPROJECTION_MODE_PLANAR_MANUAL_MSFT indicates that the corresponding layer <b>may</b> benefit from planar reprojection. The application <b>can</b> customize the plane by chaining an ##XrCompositionLayerReprojectionPlaneOverrideMSFT structure to the same layer. The app <b>can</b> also omit the plane override, indicating the runtime should use the default reprojection plane settings. This mode works better when the application knows the content is mostly placed on a plane, or when it cannot afford to submit depth information.</li>
<li>#REPROJECTION_MODE_ORIENTATION_ONLY_MSFT indicates the layer should be stabilized only for changes to orientation, ignoring positional changes. This mode works better for body-locked content that should follow the user as they walk around, such as 360-degree video.</li>
</ul>
When the application passes #REPROJECTION_MODE_DEPTH_MSFT or #REPROJECTION_MODE_PLANAR_FROM_DEPTH_MSFT mode, it <b>should</b> also provide the depth buffer for the corresponding layer using ##XrCompositionLayerDepthInfoKHR in <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#XR_KHR_composition_layer_depth">XR_KHR_composition_layer_depth</a> extension. However, if the application does not submit this depth buffer, the runtime <b>must</b> apply a runtime defined fallback reprojection mode, and <b>must</b> not fail the #EndFrame() function because of this missing depth.
When the application passes #REPROJECTION_MODE_PLANAR_MANUAL_MSFT or #REPROJECTION_MODE_ORIENTATION_ONLY_MSFT mode, it <b>should</b> avoid providing a depth buffer for the corresponding layer using ##XrCompositionLayerDepthInfoKHR in <a target="_blank" href="https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html\#XR_KHR_composition_layer_depth">XR_KHR_composition_layer_depth</a> extension. However, if the application does submit this depth buffer, the runtime <b>must</b> not fail the #EndFrame() function because of this unused depth data.
<h5>See Also</h5>
##XrCompositionLayerReprojectionInfoMSFT, #EnumerateReprojectionModesMSFT()
""",
"REPROJECTION_MODE_DEPTH_MSFT".."1",
"REPROJECTION_MODE_PLANAR_FROM_DEPTH_MSFT".."2",
"REPROJECTION_MODE_PLANAR_MANUAL_MSFT".."3",
"REPROJECTION_MODE_ORIENTATION_ONLY_MSFT".."4"
)
XrResult(
"EnumerateReprojectionModesMSFT",
"""
Queries the supported reprojection modes.
<h5>C Specification</h5>
First, the application uses #EnumerateReprojectionModesMSFT() to inspect what reprojection mode the view configuration supports.
The #EnumerateReprojectionModesMSFT() function returns the supported reprojection modes of the view configuration.
<pre><code>
XrResult xrEnumerateReprojectionModesMSFT(
XrInstance instance,
XrSystemId systemId,
XrViewConfigurationType viewConfigurationType,
uint32_t modeCapacityInput,
uint32_t* modeCountOutput,
XrReprojectionModeMSFT* modes);</code></pre>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>The {@link MSFTCompositionLayerReprojection XR_MSFT_composition_layer_reprojection} extension <b>must</b> be enabled prior to calling #EnumerateReprojectionModesMSFT()</li>
<li>{@code instance} <b>must</b> be a valid {@code XrInstance} handle</li>
<li>{@code viewConfigurationType} <b>must</b> be a valid {@code XrViewConfigurationType} value</li>
<li>{@code modeCountOutput} <b>must</b> be a pointer to a {@code uint32_t} value</li>
<li>If {@code modeCapacityInput} is not 0, {@code modes} <b>must</b> be a pointer to an array of {@code modeCapacityInput} {@code XrReprojectionModeMSFT} values</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_FUNCTION_UNSUPPORTED</li>
<li>#ERROR_VALIDATION_FAILURE</li>
<li>#ERROR_RUNTIME_FAILURE</li>
<li>#ERROR_HANDLE_INVALID</li>
<li>#ERROR_INSTANCE_LOST</li>
<li>#ERROR_SIZE_INSUFFICIENT</li>
<li>#ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED</li>
<li>#ERROR_SYSTEM_INVALID</li>
</ul></dd>
</dl>
A system <b>may</b> support different sets of reprojection modes for different view configuration types.
""",
XrInstance("instance", "the instance from which {@code systemId} was retrieved."),
XrSystemId("systemId", "the {@code XrSystemId} whose reprojection modes will be enumerated."),
XrViewConfigurationType("viewConfigurationType", "the {@code XrViewConfigurationType} to enumerate."),
AutoSize("modes")..uint32_t("modeCapacityInput", "the capacity of the array, or 0 to indicate a request to retrieve the required capacity."),
Check(1)..uint32_t.p("modeCountOutput", "a pointer to the count of the array, or a pointer to the required capacity in the case that {@code modeCapacityInput} is insufficient."),
nullable..XrReprojectionModeMSFT.p("modes", "a pointer to an application-allocated array that will be filled with the {@code XrReprojectionModeMSFT} values that are supported by the runtime. It <b>can</b> be {@code NULL} if {@code modeCapacityInput} is 0.")
)
} | modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/MSFT_composition_layer_reprojection.kt | 372896006 |
package net.pureal.traits.interaction
import net.pureal.traits.*
import net.pureal.traits.graphics.*
import net.pureal.traits.math.*
trait Button : Clickable<Trigger<Unit>>, ColoredElement<Trigger<Unit>> {
override fun onClick(pointerKey: PointerKey) = content()
}
fun button(
trigger: Trigger<Unit> = trigger<Unit>(),
shape: Shape,
fill: Fill,
changed: Observable<Unit> = observable(),
onClick: () -> Unit = {}) = object : Button {
override val content = trigger
override val shape = shape
override val fill = fill
override val changed = changed
init {
content addObserver { onClick() }
}
} | traits/src/net/pureal/traits/interaction/Button.kt | 4273546748 |
/*
* Copyright (C) 2019 Square, 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 okhttp3.internal.platform.android
import android.annotation.SuppressLint
import android.net.ssl.SSLSockets
import android.os.Build
import java.io.IOException
import java.lang.IllegalArgumentException
import javax.net.ssl.SSLSocket
import okhttp3.Protocol
import okhttp3.internal.SuppressSignatureCheck
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.Companion.isAndroid
/**
* Simple non-reflection SocketAdapter for Android Q+.
*
* These API assumptions make it unsuitable for use on earlier Android versions.
*/
@SuppressLint("NewApi")
@SuppressSignatureCheck
class Android10SocketAdapter : SocketAdapter {
override fun matchesSocket(sslSocket: SSLSocket): Boolean = SSLSockets.isSupportedSocket(sslSocket)
override fun isSupported(): Boolean = Companion.isSupported()
@SuppressLint("NewApi")
override fun getSelectedProtocol(sslSocket: SSLSocket): String? {
return try {
// SSLSocket.getApplicationProtocol returns "" if application protocols values will not
// be used. Observed if you didn't specify SSLParameters.setApplicationProtocols
when (val protocol = sslSocket.applicationProtocol) {
null, "" -> null
else -> protocol
}
} catch (e: UnsupportedOperationException) {
// https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--
null
}
}
@SuppressLint("NewApi")
override fun configureTlsExtensions(
sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) {
try {
SSLSockets.setUseSessionTickets(sslSocket, true)
val sslParameters = sslSocket.sslParameters
// Enable ALPN.
sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()
sslSocket.sslParameters = sslParameters
} catch (iae: IllegalArgumentException) {
// probably java.lang.IllegalArgumentException: Invalid input to toASCII from IDN.toASCII
throw IOException("Android internal error", iae)
}
}
@SuppressSignatureCheck
companion object {
fun buildIfSupported(): SocketAdapter? =
if (isSupported()) Android10SocketAdapter() else null
fun isSupported() = isAndroid && Build.VERSION.SDK_INT >= 29
}
}
| okhttp/src/main/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt | 3851333915 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.wrapper
import com.mcmoonlake.api.Valuable
/**
* Only applies to Minecraft 1.9+
*/
enum class EnumMainHand(
val value: Int
) : Valuable<Int> {
/**
* Enum Main Hand: Left (枚举主手: 左)
*/
LEFT(0),
/**
* Enum Main Hand: Right (枚举主手: 右)
*/
RIGHT(1),
;
override fun value(): Int
= value
}
| API/src/main/kotlin/com/mcmoonlake/api/wrapper/EnumMainHand.kt | 49664417 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
import com.mcmoonlake.api.block.BlockPosition
data class PacketOutSpawnPosition(
var blockPosition: BlockPosition
) : PacketOutBukkitAbstract("PacketPlayOutSpawnPosition") {
@Deprecated("")
constructor() : this(BlockPosition.ZERO)
override fun read(data: PacketBuffer) {
blockPosition = data.readBlockPosition()
}
override fun write(data: PacketBuffer) {
data.writeBlockPosition(blockPosition)
}
}
| API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutSpawnPosition.kt | 240687333 |
package org.wikipedia.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
class SwipeRefreshLayoutWithScroll constructor(context: Context, attrs: AttributeSet?) : SwipeRefreshLayout(context, attrs) {
var scrollableChild: View? = null
override fun canChildScrollUp(): Boolean {
return if (scrollableChild == null) {
false
} else scrollableChild!!.scrollY > 0
}
}
| app/src/main/java/org/wikipedia/views/SwipeRefreshLayoutWithScroll.kt | 2759436590 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.data.visualization
import org.hisp.dhis.android.core.common.AggregationType
import org.hisp.dhis.android.core.common.ObjectWithUid
import org.hisp.dhis.android.core.common.RelativePeriod
import org.hisp.dhis.android.core.data.utils.FillPropertiesTestUtils
import org.hisp.dhis.android.core.visualization.*
internal object VisualizationSamples {
private const val DATE_STR = "2021-06-16T14:26:50.195"
private val DATE = FillPropertiesTestUtils.parseDate(DATE_STR)
@JvmStatic
fun visualization(): Visualization = Visualization.builder()
.id(1L)
.uid("PYBH8ZaAQnC")
.name("Android SDK Visualization sample")
.displayName("Android SDK Visualization sample")
.created(DATE)
.lastUpdated(DATE)
.description("Sample visualization for the Android SDK")
.displayDescription("Sample visualization for the Android SDK")
.displayFormName("Android SDK Visualization sample")
.title("Sample title")
.displayTitle("Sample display title")
.subtitle("Sample subtitle")
.displaySubtitle("Sample display subtitle")
.type(VisualizationType.PIVOT_TABLE)
.hideTitle(false)
.hideSubtitle(false)
.hideEmptyColumns(false)
.hideEmptyRows(false)
.hideEmptyRowItems(HideEmptyItemStrategy.NONE)
.hideLegend(false)
.showHierarchy(false)
.rowTotals(true)
.rowSubTotals(false)
.colTotals(false)
.colSubTotals(false)
.showDimensionLabels(false)
.percentStackedValues(false)
.noSpaceBetweenColumns(false)
.skipRounding(false)
.legend(
VisualizationLegend.builder()
.set(ObjectWithUid.create("Yf6UHoPkd57"))
.showKey(false)
.strategy(LegendStrategy.FIXED)
.style(LegendStyle.FILL)
.build()
)
.displayDensity(DisplayDensity.NORMAL)
.digitGroupSeparator(DigitGroupSeparator.COMMA)
.relativePeriods(hashMapOf(RelativePeriod.THIS_YEAR to false, RelativePeriod.LAST_12_MONTHS to true))
.categoryDimensions(
listOf(
CategoryDimension.builder()
.category(ObjectWithUid.create("fMZEcRHuamy"))
.categoryOptions(listOf(ObjectWithUid.create("qkPbeWaFsnU"), ObjectWithUid.create("wbrDrL2aYEc")))
.build()
)
)
.filterDimensions(listOf("ou"))
.rowDimensions(listOf("pe"))
.columnDimensions(listOf("dx", "fMZEcRHuamy", "fkAkrdC7eJF"))
.dataDimensionItems(
listOf(
DataDimensionItem.builder()
.dataDimensionItemType(DataDimensionItemType.INDICATOR)
.indicator(ObjectWithUid.create("Uvn6LCg7dVU"))
.build(),
DataDimensionItem.builder()
.dataDimensionItemType(DataDimensionItemType.DATA_ELEMENT)
.dataElement(ObjectWithUid.create("cYeuwXTCPkU"))
.build()
)
)
.organisationUnitLevels(listOf(3))
.userOrganisationUnit(false)
.userOrganisationUnitChildren(false)
.userOrganisationUnitGrandChildren(false)
.organisationUnits(listOf(ObjectWithUid.create("YuQRtpLP10I"), ObjectWithUid.create("vWbkYPRmKyS")))
.periods(listOf(ObjectWithUid.create("202102"), ObjectWithUid.create("202103"), ObjectWithUid.create("2021S2")))
.aggregationType(AggregationType.SUM)
.build()
}
| core/src/sharedTest/java/org/hisp/dhis/android/core/data/visualization/VisualizationSamples.kt | 816458858 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
data class PacketOutStatistic(
var statistics: MutableMap<String, Int>
) : PacketOutBukkitAbstract("PacketPlayOutStatistic") {
@Deprecated("")
constructor() : this(HashMap())
override fun read(data: PacketBuffer) {
statistics = (0 until data.readVarInt()).associate {
val name = data.readString()
val value = data.readVarInt()
name.to(value)
}.toMutableMap()
}
override fun write(data: PacketBuffer) {
data.writeVarInt(statistics.size)
statistics.forEach {
data.writeString(it.key)
data.writeVarInt(it.value)
}
}
}
| API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutStatistic.kt | 2515895998 |
package katas.kotlin.leetcode.merge_k_sorted_lists
import katas.kotlin.leetcode.ListNode
import katas.kotlin.leetcode.listNodes
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/merge-k-sorted-lists
*/
class MergeSortedListsTests {
@Test fun `merge k sorted linked lists`() {
merge(arrayOf(listNodes(1))) shouldEqual listNodes(1)
merge(arrayOf(listNodes(1, 2))) shouldEqual listNodes(1, 2)
merge(arrayOf(listNodes(1), listNodes(2))) shouldEqual listNodes(1, 2)
merge(arrayOf(listNodes(1, 2), listNodes(3))) shouldEqual listNodes(1, 2, 3)
merge(arrayOf(listNodes(1, 3), listNodes(2))) shouldEqual listNodes(1, 2, 3)
merge(arrayOf(listNodes(1, 4, 5), listNodes(1, 3, 4), listNodes(2, 6))) shouldEqual listNodes(1, 1, 2, 3, 4, 4, 5, 6)
}
}
private fun merge(listNodes: Array<ListNode?>): ListNode? {
fun Array<ListNode?>.removeMin(): ListNode {
var result: ListNode? = null
var index = 0
forEachIndexed { i, node ->
if (node != null) {
if (result == null || node.value < result!!.value) {
result = node
index = i
}
}
}
listNodes[index] = result!!.next
return result!!
}
fun Array<ListNode?>.hasNodes() = any { it != null }
if (!listNodes.hasNodes()) return null
var result = listNodes.removeMin()
result.next = null
while (listNodes.hasNodes()) {
val node = listNodes.removeMin()
node.next = result
result = node
}
return result.reverse()
} | kotlin/src/katas/kotlin/leetcode/merge_k_sorted_lists/MergeSortedLists.kt | 3706103937 |
package io.clearnote.infrastructure.mongo
import com.mongodb.rx.client.MongoClients
import org.junit.After
abstract class BaseMongoTests {
@After fun tearDown(): Unit {
mongoDatabase.drop().toBlocking().first()
}
companion object {
val mongoClient = MongoClients.create("mongodb://mongo.service")
val mongoDatabase = mongoClient.getDatabase("clearnote_tests")
val noteCollection = mongoDatabase.getCollection("notes")
val userCollection = mongoDatabase.getCollection("users")
}
}
| src/test/kotlin/io/clearnote/infrastructure/mongo/BaseMongoTests.kt | 3512583642 |
package org.moire.ultrasonic.api.subsonic
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should equal`
import org.junit.Test
import org.moire.ultrasonic.api.subsonic.models.MusicDirectoryChild
/**
* Integration test for [SubsonicAPIDefinition.getBookmarks] call.
*/
class SubsonicApiGetBookmarksTest : SubsonicAPIClientTest() {
@Test
fun `Should handle error response`() {
val response = checkErrorCallParsed(mockWebServerRule) {
client.api.getBookmarks().execute()
}
response.bookmarkList `should equal` emptyList()
}
@Test
fun `Should handle ok response`() {
mockWebServerRule.enqueueResponse("get_bookmarks_ok.json")
val response = client.api.getBookmarks().execute()
assertResponseSuccessful(response)
response.body()!!.bookmarkList.size `should be equal to` 1
with(response.body()!!.bookmarkList[0]) {
position `should be equal to` 107914
username `should be equal to` "CaptainEurope"
comment `should be equal to` "Look at this"
created `should equal` parseDate("2017-11-18T15:22:22.144Z")
changed `should equal` parseDate("2017-11-18T15:22:22.144Z")
entry `should equal` MusicDirectoryChild(
id = "10349", parent = "10342",
isDir = false, title = "Amerika", album = "Home of the Strange",
artist = "Young the Giant", track = 1, year = 2016, genre = "Indie Rock",
coverArt = "10342", size = 9628673, contentType = "audio/mpeg",
suffix = "mp3", duration = 240, bitRate = 320,
path = "Young the Giant/Home of the Strange/01 Amerika.mp3",
isVideo = false, playCount = 2, discNumber = 1,
created = parseDate("2017-11-01T17:46:52.000Z"),
albumId = "984", artistId = "571", type = "music"
)
}
}
}
| core/subsonic-api/src/integrationTest/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicApiGetBookmarksTest.kt | 3125429319 |
// "Make 'B' 'open'" "true"
class A {
class B
}
class C : <caret>A.B() | plugins/kotlin/idea/tests/testData/quickfix/modifiers/addOpenToClassDeclaration/nestedFinalClass.kt | 1337428805 |
fun fun1(<caret>x : Int) : Int = x * 2 + fun1(x)
| plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ExpressionFunctionBefore.kt | 3149370369 |
// AFTER-WARNING: Parameter 'args' is never used
// AFTER-WARNING: Variable 'x' is never used
fun main(args: Array<String>){
val x = "abc" +<caret> 1 + 2 + 'a' + 3.2
}
| plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/combinesNonStringsAsStrings.kt | 2332465451 |
interface Some {
fun <caret>some()
} | plugins/kotlin/idea/tests/testData/javaFacade/WrapFunWithoutImplInTrait.kt | 2420367541 |
package org.javacs.kt
import org.hamcrest.Matchers.*
import org.javacs.kt.classpath.*
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.BeforeClass
import java.nio.file.Files
class ClassPathTest {
companion object {
@JvmStatic @BeforeClass fun setupLogger() {
LOG.connectStdioBackend()
}
}
@Test fun `find gradle classpath`() {
val workspaceRoot = testResourcesRoot().resolve("additionalWorkspace")
val buildFile = workspaceRoot.resolve("build.gradle")
assertTrue(Files.exists(buildFile))
val resolvers = defaultClassPathResolver(listOf(workspaceRoot))
print(resolvers)
val classPath = resolvers.classpathOrEmpty.map { it.toString() }
assertThat(classPath, hasItem(containsString("junit")))
}
@Test fun `find maven classpath`() {
val workspaceRoot = testResourcesRoot().resolve("mavenWorkspace")
val buildFile = workspaceRoot.resolve("pom.xml")
assertTrue(Files.exists(buildFile))
val resolvers = defaultClassPathResolver(listOf(workspaceRoot))
print(resolvers)
val classPath = resolvers.classpathOrEmpty.map { it.toString() }
assertThat(classPath, hasItem(containsString("junit")))
}
@Test fun `find kotlin stdlib`() {
assertThat(findKotlinStdlib(), notNullValue())
}
}
| server/src/test/kotlin/org/javacs/kt/ClassPathTest.kt | 805028936 |
package me.serce.solidity.ide
import com.intellij.lang.HelpID
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import me.serce.solidity.lang.core.SolidityLexer
import me.serce.solidity.lang.core.SolidityParserDefinition
import me.serce.solidity.lang.core.SolidityTokenTypes.IDENTIFIER
import me.serce.solidity.lang.core.SolidityTokenTypes.STRINGLITERAL
import me.serce.solidity.lang.psi.SolNamedElement
class SolFindUsagesProvider : FindUsagesProvider {
override fun getWordsScanner(): WordsScanner = SolWordScanner()
override fun canFindUsagesFor(element: PsiElement) = element is SolNamedElement
override fun getHelpId(element: PsiElement) = HelpID.FIND_OTHER_USAGES
override fun getType(element: PsiElement) = ""
override fun getDescriptiveName(element: PsiElement) = ""
override fun getNodeText(element: PsiElement, useFullName: Boolean) = ""
}
class SolWordScanner : DefaultWordsScanner(
SolidityLexer(),
TokenSet.create(IDENTIFIER),
SolidityParserDefinition.COMMENTS,
TokenSet.create(STRINGLITERAL)
)
| src/main/kotlin/me/serce/solidity/ide/search.kt | 3955707235 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.ui.scroll
import javax.swing.BoundedRangeModel
import javax.swing.JScrollBar
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
abstract class BoundedRangeModelThresholdListener(
private val model: BoundedRangeModel,
private val thresholdPercent: Float
) : ChangeListener {
init {
require(thresholdPercent > 0 && thresholdPercent < 1) { "Threshold should be a value greater than 0 and lesser than 1" }
}
override fun stateChanged(e: ChangeEvent) {
if (model.valueIsAdjusting) return
if (isAtThreshold()) {
onThresholdReached()
}
}
abstract fun onThresholdReached()
private fun isAtThreshold(): Boolean {
val visibleAmount = model.extent
val value = model.value
val maximum = model.maximum
if (maximum == 0) return false
val scrollFraction = (visibleAmount + value) / maximum.toFloat()
if (scrollFraction < thresholdPercent) return false
return true
}
companion object {
@JvmStatic
@JvmOverloads
fun install(scrollBar: JScrollBar, threshold: Float = 0.5f, listener: () -> Unit) {
scrollBar.model.addChangeListener(object : BoundedRangeModelThresholdListener(scrollBar.model, threshold) {
override fun onThresholdReached() = listener()
})
}
}
} | platform/platform-api/src/com/intellij/util/ui/scroll/BoundedRangeModelThresholdListener.kt | 2763044509 |
fun <T> foo(f: () -> T) {}
fun test() {
foo {
return@foo Unit<caret>
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantUnitExpression/labeledReturnGenericType.kt | 1042335050 |
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Diameter
import de.dreier.mytargets.shared.models.ETargetType
import de.dreier.mytargets.shared.targets.scoringstyle.ArrowAwareScoringStyle
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.targets.zone.EllipseZone
import de.dreier.mytargets.shared.utils.Color.BLACK
import de.dreier.mytargets.shared.utils.Color.GRAY
import de.dreier.mytargets.shared.utils.Color.LIGHTER_GRAY
import de.dreier.mytargets.shared.utils.Color.ORANGE
import de.dreier.mytargets.shared.utils.Color.TURBO_YELLOW
class NFAAAnimal : TargetModelBase(
id = ID,
nameRes = R.string.nfaa_animal,
diameters = listOf(Diameter.SMALL, Diameter.MEDIUM, Diameter.LARGE, Diameter.XLARGE),
zones = listOf(
CircularZone(0.162f, TURBO_YELLOW, BLACK, 5),
EllipseZone(1.0f, 0.0f, 0.0f, ORANGE, BLACK, 4),
CircularZone(1.0f, LIGHTER_GRAY, GRAY, 3)
),
scoringStyles = listOf(
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(21, 20, 18), intArrayOf(17, 16, 14), intArrayOf(13, 12, 10))),
ScoringStyle(false, 20, 16, 10),
ScoringStyle(false, 15, 12, 7),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(20, 18, 16), intArrayOf(14, 12, 10), intArrayOf(8, 6, 4))),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(20, 18, 16), intArrayOf(12, 10, 8), intArrayOf(6, 4, 2))),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(15, 10, 5), intArrayOf(12, 7, 2)))
),
type = ETargetType.THREE_D
) {
companion object {
const val ID = 21L
}
}
| shared/src/main/java/de/dreier/mytargets/shared/targets/models/NFAAAnimal.kt | 976543132 |
package com.alexzh.medicationreminder.settings
import android.content.pm.PackageManager
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.rule.ActivityTestRule
import com.alexzh.medicationreminder.R
import com.alexzh.medicationreminder.data.AppInfoRepository
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.subjects.SingleSubject
import org.hamcrest.CoreMatchers.not
import org.hamcrest.CoreMatchers.startsWith
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class SettingsActivityMockUITest {
companion object {
private val NAVIGATE_UP_DESCRIPTION = "Navigate up"
val APP_VERSION = "0.0.1-dev"
}
private val mRepository = mock<AppInfoRepository>()
private val mAppInfoSubject = SingleSubject.create<String>()
@Rule @JvmField
var thrown = ExpectedException.none()
@Rule @JvmField
val mActivityRule = object: ActivityTestRule<SettingsActivity>(SettingsActivity::class.java) {
override fun beforeActivityLaunched() {
SettingsFragment.mRepository = mRepository
whenever(mRepository.getAppVersion()).thenReturn(mAppInfoSubject)
}
}
@Test
fun shouldDisplayAboutCategoryWithVersionPreference() {
onView(withText(R.string.pref_title_category_about))
.check(matches(isDisplayed()))
onView(withText(R.string.pref_title_app_version))
.check(matches(isDisplayed()))
mAppInfoSubject.onSuccess(APP_VERSION)
onView(withText(APP_VERSION))
.check(matches(isDisplayed()))
}
@Test
fun shouldDisplayAboutCategoryWithUnknownAppVersionPreference() {
onView(withText(R.string.pref_title_category_about))
.check(matches(isDisplayed()))
onView(withText(R.string.pref_title_app_version))
.check(matches(isDisplayed()))
mAppInfoSubject.onError(PackageManager.NameNotFoundException())
onView(withText(R.string.pref_summary_app_version_unknown))
.check(matches(isDisplayed()))
}
/**
* Test wait for exception, because Activity should be finished.
*/
@Test
fun shouldCheckNavigationUpButton() {
// Preparing expected exception.
thrown.expect(RuntimeException::class.java)
thrown.expectMessage(startsWith("No activities found."))
onView(withText(R.string.pref_title_category_about))
.check(matches(isDisplayed()))
onView(ViewMatchers.withContentDescription(NAVIGATE_UP_DESCRIPTION))
.check(matches(isDisplayed()))
.perform(ViewActions.click())
onView(withText(R.string.pref_title_category_about))
.check(matches(not(isDisplayed())))
}
} | app/src/androidTest/java/com/alexzh/medicationreminder/settings/SettingsActivityMockUITest.kt | 1985620961 |
package com.seancheey.game
import com.seancheey.game.battlefield.Battlefield
/**
* Created by Seancheey on 10/07/2017.
* GitHub: https://github.com/Seancheey
*/
open class Game(var initialMoney: Int = 2000, playerWithSide: MutableMap<Player, Int> = mutableMapOf(), val field: Battlefield) {
val gamePlayers: List<PlayerInGame> = playerWithSide.map { PlayerInGame(it.key, it.value, initialMoney) }
val playerMap: Map<Player, PlayerInGame> = mutableMapOf(*gamePlayers.map { it.player to it }.toTypedArray())
open fun testWin(): Player? = null
} | src/com/seancheey/game/Game.kt | 2211454238 |
package watch.gnag.website.routes
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.function.server.router
import watch.gnag.website.handlers.SiteHandler
@Configuration
class SiteRouter(private val siteHandler: SiteHandler) {
@Bean
fun siteRoutes() = router {
GET("/", siteHandler::index)
GET("/configHelper", siteHandler::configHelper)
}
}
| src/main/kotlin/watch/gnag/website/routes/SiteRouter.kt | 210359888 |
package assets.dialog.message
/**
* Created by vicboma on 10/12/16.
*/
enum class EnumDialog constructor(val value : Int){
//
// Message types. Used by the UI to determine what icon to display,
// and possibly what behavior to give based on the type.
//
/** Used for error messages. */
ERROR_MESSAGE(0),
/** Used for information messages. */
INFORMATION_MESSAGE(1),
/** Used for warning messages. */
WARNING_MESSAGE(2),
/** Used for questions. */
QUESTION_MESSAGE(3),
/** No icon is used. */
PLAIN_MESSAGE(-1)
} | src/main/kotlin/assets/dialog/EnumDialog.kt | 3251955168 |
package co.smartreceipts.android.ad
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.WorkerThread
import co.smartreceipts.android.persistence.SharedPreferenceDefinitions
import co.smartreceipts.android.purchases.model.InAppPurchase
import co.smartreceipts.android.purchases.wallet.PurchaseWallet
import co.smartreceipts.core.di.scopes.ApplicationScope
import javax.inject.Inject
/**
* A wrapper class that allows us to quickly determine if we should show this user ads or not
*/
@ApplicationScope
class AdStatusTracker @Inject constructor(private val context: Context,
private val purchaseWallet: PurchaseWallet) {
/**
* Checks if we should show ads. Technically this should only be called from an [WorkerThread],
* but I have relaxed this requirement to suit some of the limitations that we see in our 3p
* ad provider libraries (which require lots of UI Thread interactions).
*
* Internally, everything relies on [SharedPreferences], which caches everything after the first
* load. As a result, it's *mostly* safe to call this off the UI thread. To avoid risking anything,
* however, it is recommended that we pre-fetch this data from a background thread in App.onCreate.
*/
fun shouldShowAds() : Boolean {
val hasProSubscription = purchaseWallet.hasActivePurchase(InAppPurchase.SmartReceiptsPlus)
val areAdsEnabledLocally = context.getSharedPreferences(AD_PREFERENCES, 0).getBoolean(SHOW_AD, true)
return areAdsEnabledLocally && !hasProSubscription
}
companion object {
private val AD_PREFERENCES = SharedPreferenceDefinitions.SubclassAds.toString()
private const val SHOW_AD = "pref1"
}
} | app/src/free/java/co/smartreceipts/android/ad/AdStatusTracker.kt | 172667988 |
package com.user.invoicemanagement.view.interfaces
import com.user.invoicemanagement.model.data.Summary
import com.user.invoicemanagement.model.dto.ProductFactory
interface MainTabLayoutView : BaseView {
fun setupTabs(factories: List<ProductFactory>)
fun showSummaryDialog(summary: Summary)
fun addTab(factory: ProductFactory)
fun removeTab(position: Int)
fun showAddFactoryDialog()
fun showEditFactoryDialog(factory: ProductFactory)
fun setTabTitle(title: String)
} | app/src/main/java/com/user/invoicemanagement/view/interfaces/MainTabLayoutView.kt | 1090310959 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.forage
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.forage.databinding.ActivityMainBinding
/**
* A Main activity that hosts all [Fragment]s for this application and hosts the nav controller.
*/
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
val navController = findNavController(R.id.nav_host_fragment_content_main)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration)
|| super.onSupportNavigateUp()
}
}
| app/src/main/java/com/example/forage/MainActivity.kt | 216404910 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.sponge.framework.SPONGE_LIBRARY_KIND
import com.demonwav.mcdev.util.AbstractProjectComponent
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.runWriteTaskLater
import com.intellij.ProjectTopics
import com.intellij.facet.FacetManager
import com.intellij.facet.impl.ui.libraries.LibrariesValidatorContextImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.libraries.LibraryKind
import com.intellij.openapi.roots.ui.configuration.libraries.LibraryPresentationManager
import com.intellij.openapi.startup.StartupManager
class MinecraftFacetDetector(project: Project) : AbstractProjectComponent(project) {
override fun projectOpened() {
val manager = StartupManager.getInstance(project)
val connection = project.messageBus.connect()
manager.registerStartupActivity {
MinecraftModuleRootListener.doCheck(project)
}
// Register a module root listener to check when things change
manager.registerPostStartupActivity {
connection.subscribe(ProjectTopics.PROJECT_ROOTS, MinecraftModuleRootListener)
}
}
private object MinecraftModuleRootListener : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByFileTypesChange) {
return
}
val project = event.source as? Project ?: return
doCheck(project)
}
fun doCheck(project: Project) {
val moduleManager = ModuleManager.getInstance(project)
for (module in moduleManager.modules) {
val facetManager = FacetManager.getInstance(module)
val minecraftFacet = facetManager.getFacetByType(MinecraftFacet.ID)
if (minecraftFacet == null) {
checkNoFacet(module)
} else {
checkExistingFacet(module, minecraftFacet)
}
}
}
private fun checkNoFacet(module: Module) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val facetManager = FacetManager.getInstance(module)
val configuration = MinecraftFacetConfiguration()
configuration.state.autoDetectTypes.addAll(platforms)
val facet = facetManager.createFacet(MinecraftFacet.facetType, "Minecraft", configuration, null)
runWriteTaskLater {
// Only add the new facet if there isn't a Minecraft facet already - double check here since this
// task may run much later
if (module.isDisposed || facet.isDisposed) {
// Module may be disposed before we run
return@runWriteTaskLater
}
if (facetManager.getFacetByType(MinecraftFacet.ID) == null) {
val model = facetManager.createModifiableModel()
model.addFacet(facet)
model.commit()
}
}
}
private fun checkExistingFacet(module: Module, facet: MinecraftFacet) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val types = facet.configuration.state.autoDetectTypes
types.clear()
types.addAll(platforms)
if (facet.configuration.state.forgePatcher) {
// make sure Forge and MCP are present
types.add(PlatformType.FORGE)
types.add(PlatformType.MCP)
}
facet.refresh()
}
private fun autoDetectTypes(module: Module): Set<PlatformType> {
val presentationManager = LibraryPresentationManager.getInstance()
val context = LibrariesValidatorContextImpl(module)
val platformKinds = mutableSetOf<LibraryKind>()
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.librariesOnly()
.forEachLibrary forEach@{ library ->
MINECRAFT_LIBRARY_KINDS.forEach { kind ->
if (presentationManager.isLibraryOfKind(library, context.librariesContainer, setOf(kind))) {
platformKinds.add(kind)
}
}
return@forEach true
}
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.withoutLibraries()
.withoutSdk()
.forEachModule forEach@{ m ->
if (m.name.startsWith("SpongeAPI")) {
// We don't want want to add parent modules in module groups
val moduleManager = ModuleManager.getInstance(m.project)
val groupPath = moduleManager.getModuleGroupPath(m)
if (groupPath == null) {
platformKinds.add(SPONGE_LIBRARY_KIND)
return@forEach true
}
val name = groupPath.lastOrNull() ?: return@forEach true
if (m.name == name) {
return@forEach true
}
platformKinds.add(SPONGE_LIBRARY_KIND)
}
return@forEach true
}
return platformKinds.mapNotNull { kind -> PlatformType.fromLibraryKind(kind) }.toSet()
}
}
}
| src/main/kotlin/com/demonwav/mcdev/facet/MinecraftFacetDetector.kt | 1223538721 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.update
import com.intellij.dvcs.DvcsUtil.getPushSupport
import com.intellij.dvcs.branch.DvcsSyncSettings
import com.intellij.dvcs.repo.Repository
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.openapi.vcs.Executor.echo
import com.intellij.openapi.vcs.update.UpdatedFiles
import com.intellij.openapi.vfs.VfsUtil
import git4idea.config.UpdateMethod.MERGE
import git4idea.config.UpdateMethod.REBASE
import git4idea.push.GitPushOperation
import git4idea.push.GitPushRepoResult
import git4idea.push.GitPushSupport
import git4idea.push.GitRejectedPushUpdateDialog
import git4idea.push.GitRejectedPushUpdateDialog.REBASE_EXIT_CODE
import git4idea.repo.GitRepository
import git4idea.test.*
import java.io.File
class GitSubmoduleTest : GitSubmoduleTestBase() {
private lateinit var main: GitRepository
private lateinit var sub: GitRepository
private lateinit var main2: RepositoryAndParent
private lateinit var sub2: File
override fun setUp() {
super.setUp()
// prepare second clone & parent.git
main2 = createPlainRepo("main")
val sub3 = createPlainRepo("sub")
sub2 = addSubmodule(main2.local, sub3.remote, "sub")
// clone into the project
cd(testRoot)
git("clone --recurse-submodules ${main2.remote} maintmp")
FileUtil.moveDirWithContent(File(testRoot, "maintmp"), VfsUtil.virtualToIoFile(projectRoot))
cd(projectRoot)
setupDefaultUsername()
val subFile = File(projectPath, "sub")
cd(subFile)
setupDefaultUsername()
refresh()
main = registerRepo(project, projectPath)
sub = registerRepo(project, subFile.path)
}
fun `test submodule in detached HEAD state is updated via 'git submodule update'`() {
// push from second clone
cd(sub2)
echo("a", "content\n")
val submoduleHash = addCommit("in submodule")
git("push")
cd(main2.local)
val mainHash = addCommit("Advance the submodule")
git("push")
insertLogMarker("update process")
val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), false, true).update(MERGE)
assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result)
assertEquals("Last commit in submodule is incorrect", submoduleHash, sub.last())
assertEquals("Last commit in main repository is incorrect", mainHash, main.last())
assertEquals("Submodule should be in detached HEAD", Repository.State.DETACHED, sub.state)
}
fun `test submodule in detached HEAD state doesn't fail in case of sync control`() {
settings.syncSetting = DvcsSyncSettings.Value.SYNC
try {
// push from second clone
cd(sub2)
echo("a", "content\n")
val submoduleHash = addCommit("in submodule")
git("push")
cd(main2.local)
val mainHash = addCommit("Advance the submodule")
git("push")
insertLogMarker("update process")
val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), false, true).update(MERGE)
assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result)
assertEquals("Last commit in submodule is incorrect", submoduleHash, sub.last())
assertEquals("Last commit in main repository is incorrect", mainHash, main.last())
assertEquals("Submodule should be in detached HEAD", Repository.State.DETACHED, sub.state)
}
finally {
settings.syncSetting = DvcsSyncSettings.Value.NOT_DECIDED
}
}
fun `test submodule on branch is updated as a normal repository`() {
// push from second clone
cd(sub2)
echo("a", "content\n")
val submoduleHash = addCommit("in submodule")
git("push")
// prepare commit in first sub clone
cd(sub)
git("checkout master")
echo("b", "content\n")
addCommit("msg")
insertLogMarker("update process")
val result = GitUpdateProcess(project, EmptyProgressIndicator(), listOf(main, sub), UpdatedFiles.create(), false, true).update(REBASE)
assertEquals("Update result is incorrect", GitUpdateResult.SUCCESS, result)
assertEquals("Submodule should be on branch", "master", sub.currentBranchName)
assertEquals("Commit from 2nd clone not found in submodule", submoduleHash, sub.git("rev-parse HEAD^"))
}
fun `test push rejected in submodule updates it and pushes again`() {
// push from second clone
cd(sub2)
echo("a", "content\n")
val submoduleHash = addCommit("in submodule")
git("push")
// prepare commit in first sub clone
cd(sub)
git("checkout master")
echo("b", "content\n")
addCommit("msg")
val updateAllRootsIfPushRejected = settings.shouldUpdateAllRootsIfPushRejected()
try {
settings.setUpdateAllRootsIfPushRejected(false)
dialogManager.registerDialogHandler(GitRejectedPushUpdateDialog::class.java, TestDialogHandler { REBASE_EXIT_CODE })
val pushSpecs = listOf(main, sub).associate {
it to makePushSpec(it, "master", "origin/master")
}
insertLogMarker("push process")
val result = GitPushOperation(project, getPushSupport(vcs) as GitPushSupport, pushSpecs, null, false, false).execute()
val mainResult = result.results[main]!!
val subResult = result.results[sub]!!
assertEquals("Submodule push result is incorrect", GitPushRepoResult.Type.SUCCESS, subResult.type)
assertEquals("Main push result is incorrect", GitPushRepoResult.Type.UP_TO_DATE, mainResult.type)
assertEquals("Submodule should be on branch", "master", sub.currentBranchName)
assertEquals("Commit from 2nd clone not found in submodule", submoduleHash, sub.git("rev-parse HEAD^"))
}
finally {
settings.setUpdateAllRootsIfPushRejected(updateAllRootsIfPushRejected)
}
}
private fun insertLogMarker(title: String) {
LOG.info("");
LOG.info("--------- STARTING ${title.toUpperCase()} -----------")
LOG.info("");
}
} | plugins/git4idea/tests/git4idea/update/GitSubmoduleTest.kt | 3334359037 |
package fr.marcsworld.enums
/**
* Type of agencies dealing with Trust Services.
*
* @author Marc Plouhinec
*/
enum class AgencyType {
/**
* Agency representing the European Commission or a Member State.
*/
TRUST_SERVICE_LIST_OPERATOR,
/**
* Agency of a Member State that provides Trust Services.
*/
TRUST_SERVICE_PROVIDER,
/**
* Agency that provides signing certificates.
*/
TRUST_SERVICE
}
| src/main/kotlin/fr/marcsworld/enums/AgencyType.kt | 2084408337 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.type
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.util.containers.toArray
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.highlighting.HighlightSink
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.createSignature
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
fun HighlightSink.highlightUnknownArgs(highlightElement: PsiElement) {
registerProblem(highlightElement, ProblemHighlightType.WEAK_WARNING, message("cannot.infer.argument.types"))
}
fun HighlightSink.highlightCannotApplyError(invokedText: String, typesString: String, highlightElement: PsiElement) {
registerError(highlightElement, message("cannot.apply.method.or.closure", invokedText, typesString))
}
fun HighlightSink.highlightAmbiguousMethod(highlightElement: PsiElement) {
registerError(highlightElement, message("constructor.call.is.ambiguous"))
}
fun HighlightSink.highlightInapplicableMethod(result: GroovyMethodResult,
arguments: List<Argument>,
argumentList: GrArgumentList?,
highlightElement: PsiElement) {
val method = result.element
val containingClass = if (method is GrGdkMethod) method.staticMethod.containingClass else method.containingClass
val argumentString = argumentsString(arguments)
val methodName = method.name
if (containingClass == null) {
highlightCannotApplyError(methodName, argumentString, highlightElement)
return
}
val message: String
if (method is DefaultConstructor) {
message = message("cannot.apply.default.constructor", methodName)
}
else {
val factory = JavaPsiFacade.getElementFactory(method.project)
val containingType = factory.createType(containingClass, result.substitutor)
val canonicalText = containingType.internalCanonicalText
if (method.isConstructor) {
message = message("cannot.apply.constructor", methodName, canonicalText, argumentString)
}
else {
message = message("cannot.apply.method1", methodName, canonicalText, argumentString)
}
}
val fixes = generateCastFixes(result, arguments, argumentList)
registerProblem(highlightElement, ProblemHighlightType.GENERIC_ERROR, message, *fixes)
}
private fun argumentsString(arguments: List<Argument>): String {
return arguments.joinToString(", ", "(", ")") {
it.type?.internalCanonicalText ?: "?"
}
}
private fun generateCastFixes(result: GroovyMethodResult, arguments: Arguments, argumentList: GrArgumentList?): Array<out LocalQuickFix> {
val signature = createSignature(result.element, result.substitutor)
return GroovyTypeCheckVisitorHelper.genCastFixes(signature, arguments.map(Argument::type).toArray(PsiType.EMPTY_ARRAY), argumentList)
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/highlighting.kt | 3817015687 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("PackagingElementProcessing")
package com.intellij.packaging.impl.artifacts
import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.CompositePackagingElementEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.FileOrDirectoryPackagingElementEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.PackagingElementEntity
fun processFileOrDirectoryCopyElements(artifact: ArtifactEntity, processor: (FileOrDirectoryPackagingElementEntity) -> Boolean) {
val rootElement = artifact.rootElement ?: return
processPackagingElementsRecursively(rootElement) {
if (it is FileOrDirectoryPackagingElementEntity) {
return@processPackagingElementsRecursively processor(it)
}
true
}
}
private fun processPackagingElementsRecursively(element: PackagingElementEntity, processor: (PackagingElementEntity) -> Boolean): Boolean {
if (!processor(element)) return false
if (element is CompositePackagingElementEntity) {
element.children.forEach {
if (!processPackagingElementsRecursively(it, processor)) {
return false
}
}
}
return true
}
| java/compiler/impl/src/com/intellij/packaging/impl/artifacts/PackagingElementProcessing.kt | 1861546159 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.ExecutionListener
import com.intellij.execution.ExecutionManager
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.components.dialog
import com.intellij.ui.dsl.builder.COLUMNS_MEDIUM
import com.intellij.ui.dsl.builder.columns
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.util.xmlb.annotations.Attribute
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import javax.swing.Icon
import javax.swing.JCheckBox
internal class LaunchBrowserBeforeRunTaskProvider : BeforeRunTaskProvider<LaunchBrowserBeforeRunTask>(), DumbAware {
companion object {
val ID = Key.create<LaunchBrowserBeforeRunTask>("LaunchBrowser.Before.Run")
}
override fun getName() = IdeBundle.message("task.browser.launch")
override fun getId() = ID
override fun getIcon(): Icon = AllIcons.Nodes.PpWeb
override fun isConfigurable() = true
override fun createTask(runConfiguration: RunConfiguration) = LaunchBrowserBeforeRunTask()
override fun configureTask(context: DataContext, runConfiguration: RunConfiguration, task: LaunchBrowserBeforeRunTask): Promise<Boolean> {
val state = task.state
val modificationCount = state.modificationCount
val browserSelector = BrowserSelector()
val browserComboBox = browserSelector.mainComponent
state.browser?.let {
browserSelector.selected = it
}
val url = TextFieldWithBrowseButton()
state.url?.let {
url.text = it
}
StartBrowserPanel.setupUrlField(url, runConfiguration.project)
var startJavaScriptDebuggerCheckBox: JCheckBox? = null
val panel = panel {
row(IdeBundle.message("task.browser.label")) {
cell(browserComboBox)
.resizableColumn()
.horizontalAlign(HorizontalAlign.FILL)
if (JavaScriptDebuggerStarter.Util.hasStarters()) {
startJavaScriptDebuggerCheckBox = checkBox(IdeBundle.message("start.browser.with.js.debugger"))
.applyToComponent { isSelected = state.withDebugger }
.component
}
}
row(IdeBundle.message("task.browser.url")) {
cell(url)
.horizontalAlign(HorizontalAlign.FILL)
.columns(COLUMNS_MEDIUM)
}
}
dialog(IdeBundle.message("task.browser.launch"), panel = panel, resizable = true, focusedComponent = url)
.show()
state.browser = browserSelector.selected
state.url = url.text
startJavaScriptDebuggerCheckBox?.let {
state.withDebugger = it.isSelected
}
return resolvedPromise(modificationCount != state.modificationCount)
}
override fun executeTask(context: DataContext, configuration: RunConfiguration, env: ExecutionEnvironment, task: LaunchBrowserBeforeRunTask): Boolean {
val disposable = Disposer.newDisposable()
Disposer.register(env.project, disposable)
val executionId = env.executionId
env.project.messageBus.connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, object: ExecutionListener {
override fun processNotStarted(executorId: String, env: ExecutionEnvironment) {
Disposer.dispose(disposable)
}
override fun processStarted(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
if (env.executionId != executionId) {
return
}
Disposer.dispose(disposable)
val settings = StartBrowserSettings()
settings.browser = task.state.browser
settings.isStartJavaScriptDebugger = task.state.withDebugger
settings.url = task.state.url
settings.isSelected = true
BrowserStarter(configuration, settings, handler).start()
}
})
return true
}
}
internal class LaunchBrowserBeforeRunTaskState : BaseState() {
@get:Attribute(value = "browser", converter = WebBrowserReferenceConverter::class)
var browser by property<WebBrowser?>(null) { it == null }
@get:Attribute()
var url by string()
@get:Attribute()
var withDebugger by property(false)
}
internal class LaunchBrowserBeforeRunTask : BeforeRunTask<LaunchBrowserBeforeRunTask>(LaunchBrowserBeforeRunTaskProvider.ID), PersistentStateComponent<LaunchBrowserBeforeRunTaskState> {
private var state = LaunchBrowserBeforeRunTaskState()
override fun loadState(state: LaunchBrowserBeforeRunTaskState) {
state.resetModificationCount()
this.state = state
}
override fun getState() = state
} | platform/platform-impl/src/com/intellij/ide/browsers/LaunchBrowserBeforeRunTaskProvider.kt | 3029705313 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.ex
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresEdt
import java.util.*
/**
* Tracker state can be updated without taking an Application writeLock.
* So Application readLock does not guarantee that 2 [getRanges] calls will return same results.
* Use [readLock] when consistency is needed.
*
* Pay attention to [isValid] and [isOperational].
*/
interface LineStatusTrackerI<out R : Range> {
val project: Project?
val disposable: Disposable
val document: Document
val vcsDocument: Document
/**
* File associated with [document]
*/
val virtualFile: VirtualFile?
val isReleased: Boolean
/**
* Whether [vcsDocument] content is successfully loaded and tracker is not [isReleased].
*/
fun isOperational(): Boolean
/**
* Whether internal state is synchronized with [document] and [vcsDocument].
* While `false`, most of the methods in this interface return `null` or silently do nothing.
*
* Returns `false` if tracker is not [isOperational] or is frozen [doFrozen].
*/
fun isValid(): Boolean
/**
* Changed line ranges between documents.
*
* Requires an Application readLock.
*/
fun getRanges(): List<R>?
fun getRangesForLines(lines: BitSet): List<R>?
fun getRangeForLine(line: Int): R?
fun getNextRange(line: Int): R?
fun getPrevRange(line: Int): R?
fun findRange(range: Range): R?
fun isLineModified(line: Int): Boolean
fun isRangeModified(startLine: Int, endLine: Int): Boolean
fun transferLineFromVcs(line: Int, approximate: Boolean): Int
fun transferLineToVcs(line: Int, approximate: Boolean): Int
@RequiresEdt
fun rollbackChanges(range: Range)
/**
* Modify [document] to match [vcsDocument] content for the passed line ranges.
*
* @param lines line numbers in [document]
* @see com.intellij.diff.util.DiffUtil.getSelectedLines
*/
@RequiresEdt
fun rollbackChanges(lines: BitSet)
/**
* Prevent internal tracker state from being updated for the time being.
* It will be synchronized once when the [task] is finished.
*
* @see com.intellij.codeInsight.actions.VcsFacade.runHeavyModificationTask
*/
@RequiresEdt
fun doFrozen(task: Runnable)
/**
* Run a task under tracker own lock (not to be confused with Application readLock).
*
* [task] should not take Application readLock inside.
*/
fun <T> readLock(task: () -> T): T
}
| platform/diff-impl/src/com/intellij/openapi/vcs/ex/LineStatusTrackerI.kt | 4230608460 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.application.impl
import com.intellij.openapi.application.EDT
import com.intellij.openapi.progress.timeoutRunBlocking
import com.intellij.testFramework.junit5.TestApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
@TestApplication
abstract class ModalCoroutineTest {
@BeforeEach
@AfterEach
fun checkNotModal() {
timeoutRunBlocking {
withContext(Dispatchers.EDT) {
assertFalse(LaterInvocator.isInModalContext()) {
"Expect no modal entries. Probably some of the previous tests didn't left their entries. " +
"Top entry is: " + LaterInvocator.getCurrentModalEntities().firstOrNull()
}
}
}
}
}
| platform/platform-tests/testSrc/com/intellij/openapi/application/impl/ModalCoroutineTest.kt | 1969175778 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.FrameExtraVariablesProvider
import com.intellij.debugger.engine.evaluation.CodeFragmentKind
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.text.CharArrayUtil
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.getLineEndOffset
import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset
import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import java.util.*
import kotlin.math.max
import kotlin.math.min
class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider {
override fun isAvailable(sourcePosition: SourcePosition, evalContext: EvaluationContext): Boolean {
if (runReadAction { sourcePosition.line } < 0) return false
return sourcePosition.file.fileType == KotlinFileType.INSTANCE && DebuggerSettings.getInstance().AUTO_VARIABLES_MODE
}
override fun collectVariables(
sourcePosition: SourcePosition, evalContext: EvaluationContext, alreadyCollected: MutableSet<String>
): Set<TextWithImports> = runReadAction { findAdditionalExpressions(sourcePosition) }
}
private fun findAdditionalExpressions(position: SourcePosition): Set<TextWithImports> {
val line = position.line
val file = position.file
val vFile = file.virtualFile
val doc = if (vFile != null) FileDocumentManager.getInstance().getDocument(vFile) else null
if (doc == null || doc.lineCount == 0 || line > (doc.lineCount - 1)) {
return emptySet()
}
val offset = file.getLineStartOffset(line)?.takeIf { it > 0 } ?: return emptySet()
val elem = file.findElementAt(offset) ?: return emptySet()
val containingElement = getContainingElement(elem) ?: elem
val limit = getLineRangeForElement(containingElement, doc)
var startLine = max(limit.startOffset, line)
while (startLine - 1 > limit.startOffset && shouldSkipLine(file, doc, startLine - 1)) {
startLine--
}
var endLine = min(limit.endOffset, line)
while (endLine + 1 < limit.endOffset && shouldSkipLine(file, doc, endLine + 1)) {
endLine++
}
val startOffset = file.getLineStartOffset(startLine) ?: return emptySet()
val endOffset = file.getLineEndOffset(endLine) ?: return emptySet()
if (startOffset >= endOffset) return emptySet()
val lineRange = TextRange(startOffset, endOffset)
if (lineRange.isEmpty) return emptySet()
val expressions = LinkedHashSet<TextWithImports>()
val variablesCollector = VariablesCollector(lineRange, expressions)
containingElement.accept(variablesCollector)
return expressions
}
private fun getContainingElement(element: PsiElement): KtElement? {
val contElement =
PsiTreeUtil.getParentOfType(element, KtDeclaration::class.java) ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)
if (contElement is KtProperty && contElement.isLocal) {
val parent = contElement.parent
return getContainingElement(parent)
}
if (contElement is KtDeclarationWithBody) {
return contElement.bodyExpression
}
return contElement
}
private fun getLineRangeForElement(containingElement: PsiElement, doc: Document): TextRange {
val elemRange = containingElement.textRange
return TextRange(doc.getLineNumber(elemRange.startOffset), doc.getLineNumber(elemRange.endOffset))
}
private fun shouldSkipLine(file: PsiFile, doc: Document, line: Int): Boolean {
val start = CharArrayUtil.shiftForward(doc.charsSequence, doc.getLineStartOffset(line), " \n\t")
val end = doc.getLineEndOffset(line)
if (start >= end) {
return true
}
val elemAtOffset = file.findElementAt(start)
val topmostElementAtOffset = getTopmostElementAtOffset(elemAtOffset!!, start)
return topmostElementAtOffset !is KtDeclaration
}
private class VariablesCollector(
private val myLineRange: TextRange,
private val myExpressions: MutableSet<TextWithImports>
) : KtTreeVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (element.isInRange()) {
super.visitKtElement(element)
}
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
if (expression.isInRange()) {
val selector = expression.selectorExpression
if (selector is KtReferenceExpression) {
if (isRefToProperty(selector)) {
myExpressions.add(expression.createText())
return
}
}
}
super.visitQualifiedExpression(expression)
}
private fun isRefToProperty(expression: KtReferenceExpression): Boolean {
// NB: analyze() cannot be called here, because DELEGATED_PROPERTY_RESOLVED_CALL will be always null
// Looks like a bug
@Suppress("DEPRECATION")
val context = expression.analyzeWithAllCompilerChecks().bindingContext
val descriptor = context[BindingContext.REFERENCE_TARGET, expression]
if (descriptor is PropertyDescriptor) {
val getter = descriptor.getter
return (getter == null || context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getter] == null) && descriptor.compileTimeInitializer == null
}
return false
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
if (expression.isInRange()) {
if (isRefToProperty(expression)) {
myExpressions.add(expression.createText())
}
}
super.visitReferenceExpression(expression)
}
private fun KtElement.isInRange(): Boolean = myLineRange.intersects(this.textRange)
private fun KtElement.createText(): TextWithImports = TextWithImportsImpl(CodeFragmentKind.EXPRESSION, this.text)
override fun visitClass(klass: KtClass) {
// Do not show expressions used in local classes
}
override fun visitNamedFunction(function: KtNamedFunction) {
// Do not show expressions used in local functions
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Do not show expressions used in anonymous objects
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
// Do not show expressions used in lambdas
}
} | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt | 3029730741 |
package setlist.shea.setlist.songlist
import android.app.Application
import io.reactivex.Flowable
import io.reactivex.Single
import setlist.shea.domain.csv.Parser
import setlist.shea.domain.csv.Writer
import setlist.shea.domain.db.SetListDao
import setlist.shea.domain.model.SetList
import java.io.File
import javax.inject.Inject
/**
* Created by Adam on 8/28/2017.
*/
open class SongListRepository @Inject constructor(private val setListDao: SetListDao,
parser: Parser, writer: Writer,
var context : Application){
private val parser : Parser = parser
private val writer : Writer = writer
fun getSetList(listName: String): Flowable<SetList> = setListDao.getSetList(listName)
fun shareSetListFile(currentSetList : SetList) : Single<File> {
// return getSongsFromSetList(currentSetList)
// .single(emptyList())
// .flatMap { songs ->
// val file = File(context.filesDir, "filename.csv")
// writer.writeFile(file, songs)
// Single.just(file)
// }
return Single.just(null)
}
} | app/src/main/java/setlist/shea/setlist/songlist/SongListRepository.kt | 226271310 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import icons.FeaturesTrainerIcons
import training.learn.CourseManager
import training.learn.lesson.LessonManager
import training.statistic.StatisticBase
import training.ui.LearningUiManager
class RestartLessonAction : AnAction(FeaturesTrainerIcons.Img.ResetLesson) {
override fun actionPerformed(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow ?: return
val lesson = LessonManager.instance.currentLesson ?: return
StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.RESTART)
CourseManager.instance.openLesson(activeToolWindow.project, lesson)
}
override fun update(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow
e.presentation.isEnabled = activeToolWindow != null && activeToolWindow.project == e.project
}
}
| plugins/ide-features-trainer/src/training/actions/RestartLessonAction.kt | 1598598175 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.util
import com.intellij.ui.ExpandedItemListCellRendererWrapper
import java.awt.Component
import java.awt.event.*
import javax.swing.JList
import javax.swing.ListCellRenderer
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener
import kotlin.properties.Delegates
/**
* Materializes a concrete component in a hovered list cell that matches the ones painted by the renderer
*/
class JListHoveredRowMaterialiser<T> private constructor(private val list: JList<T>,
private val cellRenderer: ListCellRenderer<T>) {
private var hoveredIndex: Int by Delegates.observable(-1) { _, oldValue, newValue ->
if (newValue != oldValue)
materialiseRendererAt(newValue)
}
private var rendererComponent: Component? = null
private val listRowHoverListener = object : MouseMotionAdapter() {
override fun mouseMoved(e: MouseEvent) {
val point = e.point
val idx = list.locationToIndex(point)
if (idx >= 0 && list.getCellBounds(idx, idx).contains(point)) {
hoveredIndex = idx
}
else {
hoveredIndex = -1
}
}
}
private val listDataListener = object : ListDataListener {
override fun contentsChanged(e: ListDataEvent) {
if (hoveredIndex in e.index0..e.index1) materialiseRendererAt(hoveredIndex)
}
override fun intervalRemoved(e: ListDataEvent) {
if (hoveredIndex > e.index0 || hoveredIndex > e.index1) hoveredIndex = -1
}
override fun intervalAdded(e: ListDataEvent) {
if (hoveredIndex > e.index0 || hoveredIndex > e.index1) hoveredIndex = -1
}
}
private val listPresentationListener = object : FocusListener,
ListSelectionListener,
ComponentAdapter() {
override fun focusLost(e: FocusEvent) = materialiseRendererAt(hoveredIndex)
override fun focusGained(e: FocusEvent) = materialiseRendererAt(hoveredIndex)
override fun valueChanged(e: ListSelectionEvent) = materialiseRendererAt(hoveredIndex)
override fun componentResized(e: ComponentEvent) = materialiseRendererAt(hoveredIndex)
}
private fun materialiseRendererAt(index: Int) {
if (index < 0 || index > list.model.size - 1) {
rendererComponent?.let { list.remove(it) }
rendererComponent = null
return
}
val cellValue = list.model.getElementAt(index)
val selected = list.isSelectedIndex(index)
val focused = list.hasFocus() && selected
rendererComponent = cellRenderer.getListCellRendererComponent(list, cellValue, index, selected, focused).apply {
list.add(this)
bounds = list.getCellBounds(index, index)
validate()
repaint()
}
}
companion object {
/**
* [cellRenderer] should be an instance different from one in the list
*/
fun <T> install(list: JList<T>, cellRenderer: ListCellRenderer<T>): JListHoveredRowMaterialiser<T> {
if (list.cellRenderer === cellRenderer
|| (list.cellRenderer as? ExpandedItemListCellRendererWrapper)?.wrappee === cellRenderer)
error("cellRenderer should be an instance different from list cell renderer")
return JListHoveredRowMaterialiser(list, cellRenderer).also {
with(list) {
addMouseMotionListener(it.listRowHoverListener)
addFocusListener(it.listPresentationListener)
addComponentListener(it.listPresentationListener)
addListSelectionListener(it.listPresentationListener)
model.addListDataListener(it.listDataListener)
}
}
}
}
} | plugins/github/src/org/jetbrains/plugins/github/ui/util/JListHoveredRowMaterialiser.kt | 4007593642 |
/*
* Copyright (C) 2019 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.config
/**
* Created by: veli
* Date: 4/28/17 8:29 PM
*/
object Keyword {
const val QR_CODE_TYPE_HOTSPOT = "hs"
const val QR_CODE_TYPE_WIFI = "wf"
} | app/src/main/java/org/monora/uprotocol/client/android/config/Keyword.kt | 1651454165 |
/*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.receiver
import android.content.BroadcastReceiver
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.LifecycleService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.backend.Backend
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.data.TransferRepository
import org.monora.uprotocol.client.android.data.TransferTaskRepository
import org.monora.uprotocol.client.android.database.model.SharedText
import org.monora.uprotocol.client.android.database.model.Transfer
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.util.NotificationBackend
import org.monora.uprotocol.core.TransportSeat
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.ConnectionFactory
import javax.inject.Inject
@AndroidEntryPoint
class BgBroadcastReceiver : BroadcastReceiver() {
@Inject
lateinit var backend: Backend
@Inject
lateinit var clientRepository: ClientRepository
@Inject
lateinit var connectionFactory: ConnectionFactory
@Inject
lateinit var persistenceProvider: PersistenceProvider
@Inject
lateinit var transferRepository: TransferRepository
@Inject
lateinit var transferTaskRepository: TransferTaskRepository
@Inject
lateinit var transportSeat: TransportSeat
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
ACTION_FILE_TRANSFER -> {
val client: UClient? = intent.getParcelableExtra(EXTRA_CLIENT)
val transfer: Transfer? = intent.getParcelableExtra(EXTRA_TRANSFER)
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
val isAccepted = intent.getBooleanExtra(EXTRA_ACCEPTED, false)
backend.services.notifications.backend.cancel(notificationId)
if (client != null && transfer != null) {
if (isAccepted) backend.applicationScope.launch(Dispatchers.IO) {
transferRepository.getTransferDetailDirect(transfer.id)?.let { transferDetail ->
transferTaskRepository.toggleTransferOperation(transfer, client, transferDetail)
}
} else {
transferTaskRepository.rejectTransfer(transfer, client)
}
}
}
ACTION_DEVICE_KEY_CHANGE_APPROVAL -> {
val client: UClient? = intent.getParcelableExtra(EXTRA_CLIENT)
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
backend.services.notifications.backend.cancel(notificationId)
if (client != null && intent.getBooleanExtra(EXTRA_ACCEPTED, false)) {
persistenceProvider.approveInvalidationOfCredentials(client)
}
}
ACTION_CLIPBOARD_COPY -> {
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
val sharedText: SharedText? = intent.getParcelableExtra(EXTRA_SHARED_TEXT)
backend.services.notifications.backend.cancel(notificationId)
if (sharedText != null) {
val cbManager = context.applicationContext.getSystemService(
LifecycleService.CLIPBOARD_SERVICE
) as ClipboardManager
cbManager.setPrimaryClip(ClipData.newPlainText("receivedText", sharedText.text))
Toast.makeText(context, R.string.copy_text_to_clipboard_success, Toast.LENGTH_SHORT).show()
}
}
ACTION_STOP_ALL_TASKS -> backend.cancelAllTasks()
}
}
companion object {
const val ACTION_CLIPBOARD_COPY = "org.monora.uprotocol.client.android.action.CLIPBOARD_COPY"
const val ACTION_DEVICE_KEY_CHANGE_APPROVAL = "org.monora.uprotocol.client.android.action.DEVICE_APPROVAL"
const val ACTION_FILE_TRANSFER = "org.monora.uprotocol.client.android.action.FILE_TRANSFER"
const val ACTION_PIN_USED = "org.monora.uprotocol.client.android.transaction.action.PIN_USED"
const val ACTION_STOP_ALL_TASKS = "org.monora.uprotocol.client.android.transaction.action.STOP_ALL_TASKS"
const val EXTRA_SHARED_TEXT = "extraText"
const val EXTRA_CLIENT = "extraClient"
const val EXTRA_TRANSFER = "extraTransfer"
const val EXTRA_ACCEPTED = "extraAccepted"
}
}
| app/src/main/java/org/monora/uprotocol/client/android/receiver/BgBroadcastReceiver.kt | 1155770759 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.ide
import com.google.common.net.UrlEscapers
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.impl.inWriteAction
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.refreshVfs
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.createHeavyProject
import com.intellij.testFramework.use
import com.intellij.util.io.createDirectories
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.write
import com.intellij.util.io.writeChild
import io.netty.handler.codec.http.HttpResponseStatus
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class BuiltInWebServerTest : BuiltInServerTestCase() {
override val urlPathPrefix: String
get() = "/${projectRule.project.name}"
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get only dir without end slash`() {
testIndex("foo")
}
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get only dir with end slash`() {
testIndex("foo/")
}
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get index file and then dir`() {
testIndex("foo/index.html", "foo")
}
private fun testIndex(vararg paths: String) = runBlocking {
val project = projectRule.project
val newPath = tempDirManager.newPath()
newPath.writeChild(manager.filePath!!, "hello")
newPath.refreshVfs()
createModule(newPath.systemIndependentPath, project)
for (path in paths) {
doTest(path) {
assertThat(it.inputStream.reader().readText()).isEqualTo("hello")
}
}
}
}
private suspend fun createModule(systemIndependentPath: String, project: Project) {
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
val module = ModuleManager.getInstance(project).newModule("$systemIndependentPath/test.iml", EmptyModuleType.EMPTY_MODULE)
ModuleRootModificationUtil.addContentRoot(module, systemIndependentPath)
}
}
internal class HeavyBuiltInWebServerTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
@BeforeClass
@JvmStatic
fun runServer() {
BuiltInServerManager.getInstance().waitForStart()
}
}
@Rule
@JvmField
val tempDirManager = TemporaryDirectory()
@Test
fun `path outside of project`() = runBlocking {
val projectDir = tempDirManager.newPath().resolve("foo/bar")
createHeavyProject(projectDir.resolve("test.ipr")).use { project ->
projectDir.createDirectories()
val projectDirPath = projectDir.systemIndependentPath
LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDirPath)
createModule(projectDirPath, project)
val path = tempDirManager.newPath("doNotExposeMe.txt").write("doNotExposeMe").systemIndependentPath
val relativePath = FileUtil.getRelativePath(project.basePath!!, path, '/')
val webPath = StringUtil.replace(UrlEscapers.urlPathSegmentEscaper().escape("${project.name}/$relativePath"), "%2F", "/")
testUrl("http://localhost:${BuiltInServerManager.getInstance().port}/$webPath", HttpResponseStatus.NOT_FOUND)
}
}
@Test
fun `file in hidden folder`() = runBlocking {
val projectDir = tempDirManager.newPath().resolve("foo/bar")
createHeavyProject(projectDir.resolve("test.ipr")).use { project ->
projectDir.createDirectories()
val projectDirPath = projectDir.systemIndependentPath
LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDirPath)
createModule(projectDirPath, project)
val dir = projectDir.resolve(".coverage")
dir.createDirectories()
val path = dir.resolve("foo").write("exposeMe").systemIndependentPath
val relativePath = FileUtil.getRelativePath(project.basePath!!, path, '/')
val webPath = StringUtil.replace(UrlEscapers.urlPathSegmentEscaper().escape("${project.name}/$relativePath"), "%2F", "/")
testUrl("http://localhost:${BuiltInServerManager.getInstance().port}/$webPath", HttpResponseStatus.OK)
}
}
} | platform/built-in-server/testSrc/org/jetbrains/ide/BuiltInWebServerTest.kt | 3334306507 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.components.panels.Wrapper
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil
import org.jetbrains.plugins.github.ui.util.DialogValidationUtils
import org.jetbrains.plugins.github.ui.util.Validator
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.submitBackgroundTask
import java.awt.event.ActionListener
import java.util.concurrent.CompletableFuture
import javax.swing.JTextField
class GithubLoginPanel(executorFactory: GithubApiRequestExecutor.Factory,
isAccountUnique: (name: String, server: GithubServerPath) -> Boolean,
val project: Project?,
isDialogMode: Boolean = true) : Wrapper() {
private var clientName: String = GHSecurityUtil.DEFAULT_CLIENT_NAME
private val serverTextField = ExtendableTextField(GithubServerPath.DEFAULT_HOST, 0)
private var tokenAcquisitionError: ValidationInfo? = null
private lateinit var currentUi: GithubCredentialsUI
private var passwordUi = GithubCredentialsUI.PasswordUI(serverTextField, clientName, ::switchToTokenUI, executorFactory, isAccountUnique,
isDialogMode)
private var tokenUi = GithubCredentialsUI.TokenUI(executorFactory, isAccountUnique, serverTextField, ::switchToPasswordUI, isDialogMode)
private val progressIcon = AnimatedIcon.Default()
private val progressExtension = ExtendableTextComponent.Extension { progressIcon }
init {
applyUi(passwordUi)
}
private fun switchToPasswordUI() {
applyUi(passwordUi)
}
private fun switchToTokenUI() {
applyUi(tokenUi)
}
private fun applyUi(ui: GithubCredentialsUI) {
currentUi = ui
setContent(currentUi.getPanel())
currentUi.getPreferredFocus().requestFocus()
tokenAcquisitionError = null
}
fun getPreferredFocus() = currentUi.getPreferredFocus()
fun doValidateAll(): List<ValidationInfo> {
return listOf(DialogValidationUtils.chain(
DialogValidationUtils.chain(
{ DialogValidationUtils.notBlank(serverTextField, "Server cannot be empty") },
serverPathValidator(serverTextField)),
currentUi.getValidator()),
{ tokenAcquisitionError })
.mapNotNull { it() }
}
private fun serverPathValidator(textField: JTextField): Validator {
return {
val text = textField.text
try {
GithubServerPath.from(text)
null
}
catch (e: Exception) {
ValidationInfo("$text is not a valid server path:\n${e.message}", textField)
}
}
}
private fun setBusy(busy: Boolean) {
if (busy) {
if (!serverTextField.extensions.contains(progressExtension))
serverTextField.addExtension(progressExtension)
}
else {
serverTextField.removeExtension(progressExtension)
}
serverTextField.isEnabled = !busy
currentUi.setBusy(busy)
}
fun acquireLoginAndToken(progressIndicator: ProgressIndicator): CompletableFuture<Pair<String, String>> {
setBusy(true)
tokenAcquisitionError = null
val server = getServer()
val executor = currentUi.createExecutor()
return service<ProgressManager>()
.submitBackgroundTask(project, "Not Visible", true, progressIndicator) {
currentUi.acquireLoginAndToken(server, executor, it)
}.whenComplete { _, throwable ->
runInEdt {
setBusy(false)
if (throwable != null && !GithubAsyncUtil.isCancellation(throwable)) {
tokenAcquisitionError = currentUi.handleAcquireError(throwable)
}
}
}
}
fun getServer(): GithubServerPath = GithubServerPath.from(
serverTextField.text.trim())
fun setServer(path: String, editable: Boolean = true) {
serverTextField.apply {
text = path
isEditable = editable
}
}
fun setCredentials(login: String? = null, password: String? = null, editableLogin: Boolean = true) {
if (login != null) {
passwordUi.setLogin(login, editableLogin)
tokenUi.setFixedLogin(if (editableLogin) null else login)
}
if (password != null) passwordUi.setPassword(password)
applyUi(passwordUi)
}
fun setToken(token: String? = null) {
if (token != null) tokenUi.setToken(token)
applyUi(tokenUi)
}
fun setError(exception: Throwable) {
tokenAcquisitionError = currentUi.handleAcquireError(exception)
}
fun setLoginListener(listener: ActionListener) {
passwordUi.setLoginAction(listener)
tokenUi.setLoginAction(listener)
}
fun setCancelListener(listener: ActionListener) {
passwordUi.setCancelAction(listener)
tokenUi.setCancelAction(listener)
}
fun setLoginButtonVisible(visible: Boolean) {
passwordUi.setLoginButtonVisible(visible)
tokenUi.setLoginButtonVisible(visible)
}
fun setCancelButtonVisible(visible: Boolean) {
passwordUi.setCancelButtonVisible(visible)
tokenUi.setCancelButtonVisible(visible)
}
} | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubLoginPanel.kt | 1459779020 |
package slatekit.meta
import slatekit.common.*
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import slatekit.common.ids.UPID
import slatekit.common.types.Content
import slatekit.common.types.ContentFile
//import java.time.*
import org.threeten.bp.*
import slatekit.common.ext.toStringNumeric
import slatekit.common.ext.toStringTime
import slatekit.common.ext.toStringYYYYMMDD
import slatekit.common.ids.ULID
import slatekit.utils.smartvalues.SmartValue
import slatekit.utils.smartvalues.SmartValued
import slatekit.common.values.Vars
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.createType
object KTypes {
val KStringClass = String::class
val KBoolClass = Boolean::class
val KShortClass = Short::class
val KIntClass = Int::class
val KLongClass = Long::class
val KFloatClass = Float::class
val KDoubleClass = Double::class
val KDateTimeClass = DateTime::class
val KLocalDateClass = LocalDate::class
val KLocalTimeClass = LocalTime::class
val KLocalDateTimeClass = LocalDateTime::class
val KZonedDateTimeClass = ZonedDateTime::class
val KInstantClass = Instant::class
val KUUIDClass = java.util.UUID::class
val KUPIDClass = UPID::class
val KDocClass = ContentFile::class
val KVarsClass = Vars::class
val KSmartValueClass = SmartValue::class
val KEnumLikeClass = EnumLike::class
val KContentClass = Content::class
val KDecStringClass = EncString::class
val KDecIntClass = EncInt::class
val KDecLongClass = EncLong::class
val KDecDoubleClass = EncDouble::class
val KAnyClass = EncDouble::class
val KStringType = String::class.createType()
val KBoolType = Boolean::class.createType()
val KShortType = Short::class.createType()
val KIntType = Int::class.createType()
val KLongType = Long::class.createType()
val KFloatType = Float::class.createType()
val KDoubleType = Double::class.createType()
val KDateTimeType = DateTime::class.createType()
val KLocalDateType = LocalDate::class.createType()
val KLocalTimeType = LocalTime::class.createType()
val KLocalDateTimeType = LocalDateTime::class.createType()
val KZonedDateTimeType = ZonedDateTime::class.createType()
val KInstantType = Instant::class.createType()
val KUUIDType = java.util.UUID::class.createType()
val KULIDType = ULID::class.createType()
val KUPIDType = UPID::class.createType()
val KDocType = ContentFile::class.createType()
val KVarsType = Vars::class.createType()
val KSmartValueType = SmartValue::class.createType()
val KSmartValuedType = SmartValued::class.createType()
val KEnumLikeType = EnumLike::class.createType()
val KContentType = Content::class.createType()
val KDecStringType = EncString::class.createType()
val KDecIntType = EncInt::class.createType()
val KDecLongType = EncLong::class.createType()
val KDecDoubleType = EncDouble::class.createType()
val KAnyType = Any::class.createType()
fun getClassFromType(tpe: KType): KClass<*> {
return when (tpe) {
// Basic types
KStringType -> KStringClass
KBoolType -> KBoolClass
KShortType -> KShortClass
KIntType -> KIntClass
KLongType -> KLongClass
KFloatType -> KFloatClass
KDoubleType -> KDoubleClass
KDateTimeType -> KDateTimeClass
KLocalDateType -> KLocalDateClass
KLocalTimeType -> KLocalTimeClass
KLocalDateTimeType -> KLocalDateTimeClass
KZonedDateTimeType -> KZonedDateTimeClass
KInstantType -> KInstantClass
KUUIDType -> KUUIDClass
KUPIDType -> KUPIDClass
KDocType -> KDocClass
KVarsType -> KVarsClass
KSmartValueType -> KSmartValueClass
KContentType -> KContentClass
KDecStringType -> KDecStringClass
KDecIntType -> KDecIntClass
KDecLongType -> KDecLongClass
KDecDoubleType -> KDecDoubleClass
else -> tpe.classifier as KClass<*>
}
}
fun getTypeExample(name: String, tpe: KType, textSample: String = "'abc'"): String {
return when (tpe) {
// Basic types
KStringType -> textSample
KBoolType -> "true"
KShortType -> "0"
KIntType -> "10"
KLongType -> "100"
KFloatType -> "10.0"
KDoubleType -> "10.00"
KDateTimeType -> DateTime.now().toStringNumeric("")
KLocalDateType -> DateTime.now().toStringYYYYMMDD("")
KLocalTimeType -> DateTime.now().toStringTime("")
KLocalDateTimeType -> DateTime.now().toStringNumeric()
KZonedDateTimeType -> DateTime.now().toStringNumeric()
KInstantType -> DateTime.now().toStringNumeric()
KUUIDType -> "782d1a4a-9223-4c49-96ee-cecb4c368a61"
KUPIDType -> "prefix:782d1a4a-9223-4c49-96ee-cecb4c368a61"
KDocType -> "user://myapp/conf/abc.conf"
KVarsType -> "a=1,b=2,c=3"
KSmartValueType -> "123-456-7890"
KContentType -> "[email protected]"
KDecStringType -> "ALK342481SFA"
KDecIntType -> "ALK342481SFA"
KDecLongType -> "ALK342481SFA"
KDecDoubleType -> "ALK342481SFA"
else -> name
}
}
fun isBasicType(tpe: KType): Boolean {
return when (tpe) {
// Basic types
KStringType -> true
KBoolType -> true
KShortType -> true
KIntType -> true
KLongType -> true
KFloatType -> true
KDoubleType -> true
KDateTimeType -> true
KLocalDateType -> true
KLocalTimeType -> true
KLocalDateTimeType -> true
KZonedDateTimeType -> true
KInstantType -> true
KUUIDType -> true
KUPIDType -> true
KSmartValueType -> true
KDecStringType -> true
KDecIntType -> true
KDecLongType -> true
KDecDoubleType -> true
else -> false
}
}
fun isBasicType(cls: KClass<*>): Boolean {
return when (cls) {
// Basic types
KStringClass -> true
KBoolClass -> true
KShortClass -> true
KIntClass -> true
KLongClass -> true
KFloatClass -> true
KDoubleClass -> true
KDateTimeClass -> true
KLocalDateClass -> true
KLocalTimeClass -> true
KLocalDateTimeClass -> true
KZonedDateTimeClass -> true
KInstantClass -> true
KUUIDClass -> true
KUPIDClass -> true
KSmartValueClass -> true
KDecStringClass -> true
KDecIntClass -> true
KDecLongClass -> true
KDecDoubleClass -> true
else -> false
}
}
}
| src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/KTypes.kt | 2183305261 |
package slatekit.examples
//<doc:import_required>
import slatekit.cloud.aws.S3
import slatekit.core.files.CloudFiles
import com.amazonaws.auth.profile.ProfileCredentialsProvider
import com.amazonaws.regions.Regions
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Success
import slatekit.results.Try
import slatekit.results.getOrElse
import kotlinx.coroutines.runBlocking
//</doc:import_examples>
class Example_Cloud_Files : Command("s3") {
override fun execute(request: CommandRequest): Try<Any> {
//<doc:setup>
// Setup 1: Use the default aws config file in "{user_dir}/.aws/credentials"
val files1 = S3(credentials = ProfileCredentialsProvider().credentials,
region = Regions.US_EAST_1, bucket = "slatekit-unit-tests", createBucket = false)
// Setup 2: Use the default aws config file in "{user_dir}/.aws/credentials"
val files2 = S3.of(region = "us-west-2", bucket = "slatekit-unit-tests", createBucket = false)
// Setup 3: Use the config "{user_id}/myapp/conf/files.conf"
// Specify the api key section as "files"
/**
* SAMPLE CONFIG:
* files = true
* files.key = AWS_KEY_HERE
* files.pass = AWS_PASSWORD_HERE
* files.env = dev
* files.tag = samples
*/
val files3 = S3.of(region = "us-west-2", bucket = "slatekit-unit-tests", createBucket = false,
confPath = "~/.slatekit/conf/files.conf", confSection = "files")
val files:CloudFiles = files2.getOrElse { files1 }
//</doc:setup>
//<doc:examples>
runBlocking {
// Use case 1: Creates bucket if configured
files.init()
// NOTES:
// 1. All operations use the slate kit Result<T,E> type
// 2. All operations return a slate kit Try<T> = Result<T, Exception>
// Use case 2: create using just name and content
val result1:Try<String> = files.create("file-1", "content 1")
// Use case 3: update using just name and content
files.update("file-1", "content 2")
// Use case 4: create using folder and file name
files.create("folder-1", "file-1", "content 1")
// Use case 5: update using folder and file name
files.update("folder-1", "file-1", "content 2")
// Use case 6: get file as a text using just name
files.getAsText("file-1")
// Use case 7: get file using folder and file name
files.getAsText("folder-1", "file-1")
// Use case 8: download file to local folder
files.download("file-1", "~/dev/temp/")
// Use case 9: download using folder and file name to local folder
files.download("folder-1", "file-1", "~/dev/temp")
// Use case 10: delete file by just the name
files.delete("file-1")
// Use case 11: delete using folder and name
files.delete("folder-1", "file-1")
}
//</doc:examples>
return Success("")
}
}
| src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Cloud_Files.kt | 2046205784 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.tracker
import com.intellij.stats.personalization.session.PeriodTracker
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
class PeriodTrackerTest : UsefulTestCase() {
private val tracker = PeriodTracker()
fun `test consistent when empty`() {
TestCase.assertEquals(0L, tracker.totalTime(null))
TestCase.assertEquals(0, tracker.count(null))
TestCase.assertEquals(0.0, tracker.average(null))
TestCase.assertNull(tracker.minDuration(null))
TestCase.assertNull(tracker.maxDuration(null))
}
fun `test empty with while current period is in process`() {
TestCase.assertEquals(42L, tracker.totalTime(42))
TestCase.assertEquals(1, tracker.count(100))
TestCase.assertEquals(15.0, tracker.average(15))
TestCase.assertEquals(100L, tracker.minDuration(100))
TestCase.assertEquals(200L, tracker.maxDuration(200))
}
fun `test consistent if past observations exist`() {
tracker.addDuration(100)
TestCase.assertEquals(100L, tracker.totalTime(null))
TestCase.assertEquals(142L, tracker.totalTime(42))
TestCase.assertEquals(1, tracker.count(null))
TestCase.assertEquals(2, tracker.count(100))
TestCase.assertEquals(100.0, tracker.average(null))
TestCase.assertEquals(70.0, tracker.average(40))
TestCase.assertEquals(100L, tracker.minDuration(null))
TestCase.assertEquals(100L, tracker.minDuration(150))
TestCase.assertEquals(30L, tracker.minDuration(30))
TestCase.assertEquals(100L, tracker.maxDuration(null))
TestCase.assertEquals(100L, tracker.maxDuration(30))
TestCase.assertEquals(200L, tracker.maxDuration(200))
}
}
| plugins/stats-collector/test/com/intellij/completion/tracker/PeriodTrackerTest.kt | 3385708463 |
package com.stefanosiano.powerful_libraries.imageview.blur.algorithms
import android.graphics.Bitmap
import androidx.renderscript.RenderScript
import com.stefanosiano.powerful_libraries.imageview.blur.BlurOptions
/** Algorithm to blur the image. */
internal interface BlurAlgorithm {
/** Set the renderscript context to this algorithm. Pass it before blurring! */
fun setRenderscript(renderscript: RenderScript?): BlurAlgorithm = this
/**
* Blurs the image.
*
* @param original Bitmap to blur
* @param radius Radius of the algorithm
* @param options Options of the blurring
* @return The blurred bitmap
* @throws RenderscriptException If renderscript is used and something goes wrong with it
*/
@Throws(RenderscriptException::class)
fun blur(original: Bitmap, radius: Int, options: BlurOptions): Bitmap?
}
/** Dummy algorithm that doesn't do anything. */
internal class DummyBlurAlgorithm : BlurAlgorithm {
override fun blur(original: Bitmap, radius: Int, options: BlurOptions) = original
}
internal class RenderscriptException(message: String) : Exception(message)
| powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/blur/algorithms/BlurAlgorithm.kt | 2782342269 |
package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
internal data class ProjectModule(
val name: String,
val nativeModule: Module,
val parent: ProjectModule?,
val buildFile: VirtualFile,
val buildSystemType: BuildSystemType,
val moduleType: ProjectModuleType
) {
var getNavigatableDependency: (groupId: String, artifactId: String, version: PackageVersion) -> Navigatable? =
{ _, _, _ -> null }
@NlsSafe
fun getFullName(): String {
if (parent != null) {
return parent.getFullName() + ":$name"
}
return name
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProjectModule) return false
if (name != other.name) return false
if (nativeModule.moduleFilePath != other.nativeModule.moduleFilePath) return false // This can't be automated
if (parent != other.parent) return false
if (buildFile.path != other.buildFile.path) return false
if (buildSystemType != other.buildSystemType) return false
if (moduleType != other.moduleType) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + nativeModule.moduleFilePath.hashCode()
result = 31 * result + (parent?.hashCode() ?: 0)
result = 31 * result + buildFile.path.hashCode()
result = 31 * result + buildSystemType.hashCode()
result = 31 * result + moduleType.hashCode()
return result
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModule.kt | 3094167860 |
package net.ndrei.teslacorelib.energy.systems
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.energy.CapabilityEnergy
import net.minecraftforge.energy.IEnergyStorage
import net.modcrafters.mclib.energy.IGenericEnergyStorage
import net.ndrei.teslacorelib.energy.IEnergySystem
object ForgeEnergySystem : IEnergySystem {
const val MODID = "minecraft"
override val ModId: String get() = MODID
override fun hasCapability(capability: Capability<*>)
= (capability == CapabilityEnergy.ENERGY)
@Suppress("UNCHECKED_CAST")
override fun <T> wrapCapability(capability: Capability<T>, energy: IGenericEnergyStorage): T?
= if (capability == CapabilityEnergy.ENERGY) (Wrapper(energy) as? T) else null
class Wrapper(val energy: IGenericEnergyStorage) : IEnergyStorage {
override fun canExtract() = this.energy.canTake
override fun getMaxEnergyStored() = this.energy.capacity.toInt()
override fun getEnergyStored() = this.energy.stored.toInt()
override fun canReceive() = this.energy.canGive
override fun extractEnergy(maxExtract: Int, simulate: Boolean)
= this.energy.takePower(maxExtract.toLong(), simulate).toInt()
override fun receiveEnergy(maxReceive: Int, simulate: Boolean)
= this.energy.givePower(maxReceive.toLong(), simulate).toInt()
}
override fun wrapTileEntity(te: TileEntity, side: EnumFacing): IGenericEnergyStorage? {
if (te is IEnergyStorage) {
// maybe someone didn't understand capabilities too well
return ReverseWrapper(te)
}
if (te.hasCapability(CapabilityEnergy.ENERGY, side)) {
val energy = te.getCapability(CapabilityEnergy.ENERGY, side)
if (energy != null) {
return ReverseWrapper(energy)
}
}
return null
}
override fun wrapItemStack(stack: ItemStack): IGenericEnergyStorage? {
if (!stack.isEmpty && stack.hasCapability(CapabilityEnergy.ENERGY, null)) {
val energy = stack.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
return ReverseWrapper(energy)
}
}
return null
}
class ReverseWrapper(val energy: IEnergyStorage) : IGenericEnergyStorage {
override val capacity get() = this.energy.maxEnergyStored.toLong()
override val stored get() = this.energy.energyStored.toLong()
override val canGive get() = this.energy.canReceive()
override fun givePower(power: Long, simulated: Boolean)
= this.energy.receiveEnergy(power.toInt(), simulated).toLong()
override val canTake get() = this.energy.canExtract()
override fun takePower(power: Long, simulated: Boolean)
= this.energy.extractEnergy(power.toInt(), simulated).toLong()
}
}
| src/main/kotlin/net/ndrei/teslacorelib/energy/systems/ForgeEnergySystem.kt | 2921079240 |
package codegen.coroutines.controlFlow_tryCatch1
import kotlin.test.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resume(value: Any?) {}
override fun resumeWithException(exception: Throwable) { throw exception }
}
suspend fun s1(): Int = suspendCoroutineOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
val x = try {
s1()
} catch (t: Throwable) {
f2()
}
result = x
}
println(result)
} | backend.native/tests/codegen/coroutines/controlFlow_tryCatch1.kt | 1299225697 |
package com.antonio.samir.meteoritelandingsspots.features.list
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.View.*
import androidx.annotation.NonNull
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.paging.PagedList
import androidx.recyclerview.widget.GridLayoutManager
import com.antonio.samir.meteoritelandingsspots.R
import com.antonio.samir.meteoritelandingsspots.data.Result
import com.antonio.samir.meteoritelandingsspots.data.Result.InProgress
import com.antonio.samir.meteoritelandingsspots.data.Result.Success
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import com.antonio.samir.meteoritelandingsspots.databinding.FragmentMeteoriteListBinding
import com.antonio.samir.meteoritelandingsspots.features.detail.MeteoriteDetailFragment
import com.antonio.samir.meteoritelandingsspots.features.list.MeteoriteListFragmentDirections.Companion.toDetail
import com.antonio.samir.meteoritelandingsspots.features.list.MeteoriteListViewModel.ContentStatus.*
import com.antonio.samir.meteoritelandingsspots.features.list.recyclerView.MeteoriteAdapter
import com.antonio.samir.meteoritelandingsspots.features.list.recyclerView.SpacesItemDecoration
import com.antonio.samir.meteoritelandingsspots.ui.extension.isLandscape
import com.antonio.samir.meteoritelandingsspots.ui.extension.showActionBar
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.concurrent.atomic.AtomicBoolean
@FlowPreview
@ExperimentalCoroutinesApi
class MeteoriteListFragment : Fragment() {
private var layoutManager: GridLayoutManager? = null
private var meteoriteAdapter = MeteoriteAdapter().apply {
setHasStableIds(false)
}
private var meteoriteDetailFragment: MeteoriteDetailFragment? = null
private val viewModel: MeteoriteListViewModel by viewModel()
private var _binding: FragmentMeteoriteListBinding? = null
private val binding get() = _binding!!
private val shouldOpenMeteorite = AtomicBoolean(true)
private val redirectedToPortrait = AtomicBoolean(false)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentMeteoriteListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
showActionBar(getString(R.string.title))
meteoriteAdapter.clearSelectedMeteorite()
binding.meteoriteRV.adapter = meteoriteAdapter
binding.meteoriteRV.addItemDecoration(SpacesItemDecoration(
context = requireContext(),
verticalMargin = R.dimen.spacing,
horizontalMargin = R.dimen.horizontal_spacing
))
setupGridLayout()
observeLiveData()
setupLocation()
setHasOptionsMenu(true)
if (viewModel.filter.isBlank()) {
viewModel.loadMeteorites()
}
redirectedToPortrait.set(false)
}
private fun observeLiveData() {
observeMeteorites()
observeRecoveryAddressStatus()
observeNetworkLoadingStatus()
meteoriteAdapter.openMeteorite.observe(viewLifecycleOwner) {
shouldOpenMeteorite.set(true)
viewModel.selectMeteorite(it)
}
viewModel.selectedMeteorite.observe(viewLifecycleOwner) { meteorite ->
if (meteorite != null) {
if (isLandscape()) {
showMeteoriteLandscape(meteorite)
meteoriteAdapter.updateListUI(meteorite)
val position = meteoriteAdapter.getPosition(meteorite)
position?.let { binding.meteoriteRV.smoothScrollToPosition(it) }
} else {
if (shouldOpenMeteorite.get()) {
showMeteoritePortrait(meteorite)
} else {
//Should clean the selected meteorite when it is not shown
viewModel.clearSelectedMeteorite()
}
shouldOpenMeteorite.set(false)
}
}
}
}
private fun setupLocation() {
viewModel.isAuthorizationRequested().observe(viewLifecycleOwner, {
if (it) {
requestPermissions(arrayOf(ACCESS_FINE_LOCATION), LOCATION_REQUEST_CODE)
}
})
viewModel.updateLocation()
viewModel.getLocation().observe(viewLifecycleOwner, {
meteoriteAdapter.location = it
})
}
private fun observeMeteorites() {
viewModel.getContentStatus().observe(viewLifecycleOwner) { contentStatus ->
when (contentStatus) {
ShowContent -> showContent()
NoContent -> noResult()
Loading -> showProgressLoader()
}
}
viewModel.getMeteorites().observe(viewLifecycleOwner) { meteorites ->
onSuccess(meteorites)
}
}
private fun onSuccess(meteorites: PagedList<Meteorite>) {
if (meteorites.isEmpty()) {
noResult()
} else {
meteoriteAdapter.submitList(meteorites)
}
}
private fun observeRecoveryAddressStatus() {
viewModel.getRecoverAddressStatus().observe(viewLifecycleOwner, { status ->
when (status) {
is InProgress -> showAddressLoading(status.data)
is Success -> hideAddressLoading()
is Result.Error -> error(getString(R.string.general_error))
}
})
}
private fun observeNetworkLoadingStatus() {
viewModel.getNetworkLoadingStatus().observe(viewLifecycleOwner, {
when (it) {
is InProgress -> networkLoadingStarted()
is Success -> networkLoadingStopped()
else -> unableToFetch()
}
})
}
private fun noResult() {
error(getString(R.string.no_result_found))
hideContent()
}
private fun showAddressLoading(progress: Float?) {
val addressRecoverProgress = binding.addressRecoverProgress
progress?.let {
addressRecoverProgress.progress = it
addressRecoverProgress.secondaryProgress = it + 10
}
addressRecoverProgress.progressText = getString(R.string.loading_addresses)
addressRecoverProgress.visibility = VISIBLE
}
private fun hideAddressLoading() {
binding.addressRecoverProgress.visibility = GONE
}
private fun unableToFetch() {
error(getString(R.string.no_network))
}
private fun error(messageString: String) {
hideContent()
binding.progressLoader.visibility = INVISIBLE
binding.messageTV.visibility = VISIBLE
binding.messageTV.text = messageString
}
private fun showMeteoriteLandscape(meteorite: Meteorite) {
layoutManager?.spanCount = 1
if (meteoriteDetailFragment == null) {
binding.fragment?.visibility = VISIBLE
parentFragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit).apply {
val meteoriteId: String = meteorite.id.toString()
meteoriteDetailFragment = MeteoriteDetailFragment.newInstance(meteoriteId)
replace(R.id.fragment, meteoriteDetailFragment!!)
commit()
}
} else {
meteoriteDetailFragment?.setCurrentMeteorite(meteorite.id.toString())
}
}
private fun showMeteoritePortrait(meteorite: Meteorite) {
redirectedToPortrait.set(true)
findNavController().navigate(toDetail(meteorite.id.toString()))
}
private fun setupGridLayout() {
val columnCount = resources.getInteger(R.integer.list_column_count)
layoutManager = GridLayoutManager(requireContext(), columnCount)
binding.meteoriteRV.layoutManager = layoutManager
}
private fun networkLoadingStarted() {
try {
showContent()
} catch (e: Exception) {
Log.e(TAG, e.message, e)
}
}
private fun networkLoadingStopped() {
try {
binding.networkStatusLoading.visibility = INVISIBLE
showContent()
} catch (e: Exception) {
Log.e(TAG, e.message, e)
}
}
private fun showContent() {
binding.progressLoader.visibility = INVISIBLE
binding.container?.visibility = VISIBLE
binding.meteoriteRV.visibility = VISIBLE
binding.messageTV.visibility = INVISIBLE
}
private fun hideContent() {
binding.container?.visibility = INVISIBLE
binding.meteoriteRV.visibility = INVISIBLE
}
private fun showProgressLoader() {
binding.progressLoader.visibility = VISIBLE
binding.messageTV.visibility = INVISIBLE
hideContent()
}
override fun onRequestPermissionsResult(
requestCode: Int,
@NonNull permissions: Array<String>,
@NonNull grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_REQUEST_CODE) {
for (grantResult in grantResults) {
val isPermitted = grantResult == PackageManager.PERMISSION_GRANTED
if (isPermitted) {
viewModel.updateLocation()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.main, menu)
val searchView = menu.findItem(R.id.action_search).actionView as SearchView
setup(searchView)
super.onCreateOptionsMenu(menu, inflater)
}
private fun setup(searchView: SearchView?) {
if (searchView != null) {
with(searchView) {
isActivated = true
onActionViewExpanded()
isIconified = false
setQuery(viewModel.filter, false)
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(query: String): Boolean {
if (!redirectedToPortrait.get() && query.isBlank()) {
onQueryTextSubmit(query)
}
return false
}
override fun onQueryTextSubmit(query: String): Boolean {
loadMeteorites(query)
return true
}
private fun loadMeteorites(query: String) {
viewModel.loadMeteorites(query)
}
})
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private val TAG = MeteoriteListFragment::class.java.simpleName
const val LOCATION_REQUEST_CODE = 11111
}
}
| app/src/main/java/com/antonio/samir/meteoritelandingsspots/features/list/MeteoriteListFragment.kt | 3456224863 |
fun box(): String {
val plusZero: Any = 0.0
val minusZero: Any = -0.0
if (plusZero is Double && minusZero is Double) {
when {
plusZero < minusZero -> {
return "fail 1"
}
plusZero > minusZero -> {
return "fail 2"
}
else -> {
}
}
when {
plusZero == minusZero -> {
}
else -> return "fail 3"
}
}
return "OK"
} | backend.native/tests/external/codegen/box/ieee754/whenNoSubject.kt | 2798417340 |
package abi42_0_0.expo.modules.imagepicker.exporters
import android.graphics.Bitmap
import android.net.Uri
import abi42_0_0.expo.modules.imagepicker.exporters.ImageExporter.Listener
import abi42_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface
import org.apache.commons.io.FilenameUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class CompressionImageExporter(
private val mImageLoader: ImageLoaderInterface,
private val mQuality: Int,
private val mBase64: Boolean
) : ImageExporter {
override fun export(source: Uri, output: File, exporterListener: Listener) {
val imageLoaderHandler = object : ImageLoaderInterface.ResultListener {
override fun onSuccess(bitmap: Bitmap) {
val width = bitmap.width
val height = bitmap.height
(if (mBase64) ByteArrayOutputStream() else null).use { base64Stream ->
try {
val compressFormat = if (FilenameUtils.getExtension(output.path).contains("png")) {
Bitmap.CompressFormat.PNG
} else {
Bitmap.CompressFormat.JPEG
}
saveBitmap(bitmap, compressFormat, output, base64Stream)
exporterListener.onResult(base64Stream, width, height)
} catch (e: IOException) {
exporterListener.onFailure(e)
}
}
}
override fun onFailure(cause: Throwable?) {
exporterListener.onFailure(cause)
}
}
mImageLoader.loadImageForManipulationFromURL(source.toString(), imageLoaderHandler)
}
/**
* Compress and save the `bitmap` to `file`, optionally saving it in `out` if
* base64 is requested.
*
* @param bitmap bitmap to be saved
* @param compressFormat compression format to save the image in
* @param output file to save the image to
* @param out if not null, the stream to save the image to
*/
@Throws(IOException::class)
private fun saveBitmap(bitmap: Bitmap, compressFormat: Bitmap.CompressFormat, output: File, out: ByteArrayOutputStream?) {
writeImage(bitmap, output, compressFormat)
if (mBase64) {
bitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, out)
}
}
@Throws(IOException::class)
private fun writeImage(image: Bitmap, output: File, compressFormat: Bitmap.CompressFormat) {
FileOutputStream(output).use { out -> image.compress(compressFormat, mQuality, out) }
}
}
| android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/imagepicker/exporters/CompressionImageExporter.kt | 2440583589 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.