repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tmarsteel/kotlin-prolog
async/src/main/kotlin/com/github/prologdb/async/MappedLazySequence.kt
1
2505
package com.github.prologdb.async import java.util.concurrent.LinkedBlockingDeque class MappedLazySequence<T : Any, M : Any>( private val base: LazySequence<T>, private val mapper: (T) -> M ) : LazySequence<M> { private var closed = false private var mapperException: Throwable? = null override val principal = base.principal private val cachedResults = LinkedBlockingDeque<M>() private val stepMutex = Any() override val state: LazySequence.State get() = when { closed -> LazySequence.State.DEPLETED cachedResults.isNotEmpty() -> LazySequence.State.RESULTS_AVAILABLE mapperException != null -> LazySequence.State.FAILED else -> when (base.state) { LazySequence.State.FAILED -> LazySequence.State.FAILED LazySequence.State.DEPLETED -> LazySequence.State.DEPLETED LazySequence.State.PENDING -> LazySequence.State.PENDING LazySequence.State.RESULTS_AVAILABLE -> LazySequence.State.PENDING } } override fun step(): LazySequence.State { synchronized(stepMutex) { var baseState = base.step() while (baseState == LazySequence.State.RESULTS_AVAILABLE) { val baseResult = base.tryAdvance() ?: break baseState = base.state val mappedResult = try { mapper(baseResult) } catch (mapperEx: Throwable) { mapperException = mapperEx break } cachedResults.add(mappedResult) } return state } } override tailrec fun tryAdvance(): M? { while (state == LazySequence.State.RESULTS_AVAILABLE) { cachedResults.poll()?.let { return it } } return when (step()) { LazySequence.State.RESULTS_AVAILABLE -> tryAdvance() LazySequence.State.DEPLETED -> null LazySequence.State.FAILED -> { if (mapperException != null) { throw mapperException!! } else { base.tryAdvance() error("base.tryAdvance() should have thrown") } } LazySequence.State.PENDING -> tryAdvance() } } override fun close() { if (closed) return closed = true cachedResults.clear() base.close() } }
mit
6b10214a767e08a290b6df4e4bd51418
30.708861
82
0.559681
4.99004
false
false
false
false
feer921/BaseProject
src/main/java/common/base/popupwindow/BasePopupWindow.kt
1
2866
package common.base.popupwindow import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.widget.PopupWindow import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat /** * @author fee * <P> DESC: * PopupWindow 的基类 * 注意:使用子类时最好调用一下 [build] 方法 * </P> */ abstract class BasePopupWindow<I : BasePopupWindow<I>>(protected val mContext: Context) : PopupWindow(mContext) { @LayoutRes private var mContentViewResId: Int? = null @LayoutRes protected abstract fun providerContentLayoutRes(): Int? protected open fun providerContentView(): View? = null fun withWidth(popWidth: Int): I { width = popWidth return self() } fun withHeight(popHeight: Int):I { height = popHeight return self() } fun withBackground(backgroundDrawabl1e: Drawable?):I { setBackgroundDrawable(backgroundDrawabl1e) return self() } fun withBackground(@ColorInt bgColor: Int) :I{ return withBackground(ColorDrawable(bgColor)) } fun withBackgroundRes(@DrawableRes bgDrawableResId: Int): I { return withBackground(ContextCompat.getDrawable(mContext, bgDrawableResId)) } fun withContentViewLayoutRes(@LayoutRes contentViewLayoutRes: Int?):I { this.mContentViewResId = contentViewLayoutRes return self() } fun withFocusable(focusable: Boolean):I { isFocusable = focusable return self() } /** * 外部如果仍然调用该方法提供 [contentView]的优先级最高 */ override fun setContentView(contentView: View?) { var finalContentView: View? = contentView if (finalContentView == null) { finalContentView = providerContentView() } if (finalContentView == null) { val contentViewResId = mContentViewResId ?: providerContentLayoutRes() if (0!= contentViewResId) { finalContentView = LayoutInflater.from(mContext).inflate(contentViewResId!!, null) } } super.setContentView(finalContentView) } /** * 需要调用一下这个方法 * 如果外部不调用 [setContentView]的情况下 */ fun build(): I { if (contentView == null) {//先获取当前 PopupWindow的 contentView,如果为null,则表示还没有配置 [contentView] contentView = null//则主动调用一次 [setContentView()] } return self() } final override fun getContentView(): View? { return super.getContentView() } protected fun self(): I = this as I }
apache-2.0
b4acef38f3dcd5d8e7a0d9fcd678674b
26.804124
113
0.669881
4.531092
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/storage/blobstore/persisted/PersistedBlobStoreManagement.kt
1
3172
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.libraries.pcc.chronicle.storage.blobstore.persisted import com.google.android.libraries.pcc.chronicle.storage.blobstore.BlobStoreManagement import com.google.android.libraries.pcc.chronicle.storage.blobstore.ManagementInfo import com.google.android.libraries.pcc.chronicle.storage.blobstore.PersistedManagementInfo import com.google.android.libraries.pcc.chronicle.storage.blobstore.TrimOrder import com.google.android.libraries.pcc.chronicle.storage.blobstore.db.BlobDao /** Implementation of [BlobStoreManagement] for persisted storage using the [BlobDao]. */ class PersistedBlobStoreManagement( private val dao: BlobDao, ) : BlobStoreManagement { override suspend fun clearAll(): Int { return dao.removeAllBlobEntities() } override suspend fun deleteExpiredEntities( currentTimeMillis: Long, managementInfos: Set<ManagementInfo> ) { managementInfos.forEach { info -> if (info is PersistedManagementInfo<*>) { dao.removeExpiredBlobEntitiesByDtdName(info.dtdName, currentTimeMillis - info.ttlMillis) } } } override suspend fun deleteEntitiesCreatedBetween( startTimeMillis: Long, endTimeMillis: Long, ): Int { return dao.removeBlobEntitiesCreatedBetween(startTimeMillis, endTimeMillis) } override suspend fun trim(managementInfos: Set<ManagementInfo>) { managementInfos.forEach { info -> if (info is PersistedManagementInfo<*>) { val rowCount = dao.countBlobsByDtdName(info.dtdName) if (rowCount <= info.quotaInfo.maxRowCount) { return@forEach } val numRowsToDelete = rowCount - info.quotaInfo.minRowsAfterTrim if (info.quotaInfo.trimOrder == TrimOrder.NEWEST) { dao.removeNewestBlobEntitiesByDtdName(info.dtdName, numRowsToDelete) } else { dao.removeOldestBlobEntitiesByDtdName(info.dtdName, numRowsToDelete) } // If for some reason due to race conditions or other circumstances, the trim doesn't bring // the number of entries below the maxRowCount for the specified type, all entries are // cleared. if (dao.countBlobsByDtdName(info.dtdName) > info.quotaInfo.maxRowCount) { dao.removeBlobEntitiesByDtdName(info.dtdName) } } } } override suspend fun deletePackage(packageName: String): Int { return dao.removeBlobAndPackageEntitiesByPackageName(packageName) } override suspend fun reconcilePackages(allowedPackages: Set<String>): Int { return dao.deleteNotAllowedPackages(allowedPackages) } }
apache-2.0
0a4e3694e71c43d77c69ac92c251d47b
38.160494
99
0.741173
4.252011
false
false
false
false
rethumb/rethumb-examples
examples-read-exif-data-in-json/example-kotlin.kt
1
576
import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL object KotlinRethumbExifExample { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val url = URL("http://api.rethumb.com/v1/exif/all/http://images.rethumb.com/image_exif_1.jpg") val reader = BufferedReader(InputStreamReader(url.openStream())) var s = reader.readLine() while (s != null) { println(s) s = reader.readLine() } // Use your favorite json library to parse the response! } }
unlicense
c19fee589751674b4374c7cda7a3f8bc
26.47619
102
0.638889
3.84
false
false
false
false
box/box-android-share-sdk
box-share-sdk/src/test/java/com/box/androidsdk/share/utils/ResponsesCreator.kt
1
3142
package com.box.androidsdk.share.utils import com.box.androidsdk.content.BoxException import com.box.androidsdk.content.models.* import com.box.androidsdk.content.requests.* import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever class ResponsesCreator { companion object { fun createFailedBoxCollaborationResponse(dummyName: String, exception: Exception): BoxResponse<BoxCollaboration> { val boxResponse: BoxResponse<BoxCollaboration> = mock() whenever(boxResponse.exception).thenReturn(exception) val boxUser: BoxUser = mock() whenever(boxUser.login).thenReturn(dummyName) val boxRequestShare: BoxRequestsShare.AddCollaboration = mock() whenever(boxRequestShare.accessibleBy).thenReturn(boxUser) whenever(boxResponse.request).thenReturn(boxRequestShare) whenever(boxResponse.isSuccess).thenReturn(false) return boxResponse } fun createFailedBoxIterCollaborationResponse(exception: Exception): BoxResponse<BoxIteratorCollaborations> { val boxResponse: BoxResponse<BoxIteratorCollaborations> = mock() whenever(boxResponse.exception).thenReturn(exception) whenever(boxResponse.isSuccess).thenReturn(false) return boxResponse } fun createSuccessfulBoxCollaborationResponse(dummyName: String?): BoxResponse<BoxCollaboration> { val boxResponse: BoxResponse<BoxCollaboration> = mock() var boxUser: BoxUser? = null if (dummyName != null) { boxUser = mock() whenever(boxUser.login).thenReturn(dummyName) } val boxRequestShare: BoxCollaboration = mock() whenever(boxRequestShare.accessibleBy).thenReturn(boxUser) whenever(boxResponse.result).thenReturn(boxRequestShare) whenever(boxResponse.isSuccess).thenReturn(true) return boxResponse } fun createSuccessfulBoxItemResponse(): BoxResponse<BoxItem> { val boxResponse: BoxResponse<BoxItem> = mock() whenever(boxResponse.isSuccess).thenReturn(true) whenever(boxResponse.result).thenReturn(mock()) whenever(boxResponse.request).thenReturn(mock()) return boxResponse } fun createFailedBoxItemResponse(e: Exception): BoxResponse<BoxItem> { val boxResponse: BoxResponse<BoxItem> = mock() whenever(boxResponse.isSuccess).thenReturn(false) whenever(boxResponse.exception).thenReturn(e) return boxResponse } fun createBoxCollaborationResponseBatch(vararg respones: BoxResponse<BoxCollaboration>): BoxResponseBatch { val boxResponses: BoxResponseBatch = mock() val boxResponseList = arrayListOf<BoxResponse<BoxObject>>() respones.forEach { boxResponse -> boxResponseList.add(boxResponse as BoxResponse<BoxObject>) } whenever(boxResponses.responses).thenReturn(boxResponseList) return boxResponses } } }
apache-2.0
babfa440eacf5a86119bd01435fe0001
43.885714
122
0.682368
4.894081
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/quiethours/QuietHoursManager.kt
1
7254
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.quiethours import android.content.Context import com.github.quarck.calnotify.Settings import com.github.quarck.calnotify.bluetooth.BTDeviceManager import com.github.quarck.calnotify.logs.DevLog //import com.github.quarck.calnotify.logs.Logger import com.github.quarck.calnotify.utils.DateTimeUtils import com.github.quarck.calnotify.utils.addDays import java.util.* class QuietHoursManager (val ctx: Context) : QuietHoursManagerInterface { private val btDeviceManager: BTDeviceManager by lazy { BTDeviceManager(ctx) } private fun isEnabled(settings: Settings) = settings.quietHoursEnabled && (settings.quietHoursFrom != settings.quietHoursTo) override fun startManualQuietPeriod(settings: Settings, until: Long) { settings.manualQuietPeriodUntil = until } override fun stopManualQuietPeriod(settings: Settings) { settings.manualQuietPeriodUntil = 0L } override fun isInsideQuietPeriod(settings: Settings, time: Long) = getSilentUntil(settings, time) > time override fun isInsideQuietPeriod(settings: Settings, currentTimes: LongArray) = getSilentUntil(settings, currentTimes).map { it -> it > 0L }.toBooleanArray() override fun isCustomQuietHoursActive(settings: Settings): Boolean = (settings.manualQuietPeriodUntil > System.currentTimeMillis()) // returns time in millis, when silent period ends, // or 0 if we are not on silent override fun getSilentUntil(settings: Settings, time: Long): Long { var ret = 0L val currentTime = if (time != 0L) time else System.currentTimeMillis() var manualEnd = Math.max(settings.manualQuietPeriodUntil, btDeviceManager.carModeSilentUntil) if (manualEnd < currentTime) { manualEnd = 0L } if (currentTime < manualEnd) { // we are in the manual quiet hours, but by the end of it we could hit the regular - double // check for that ret = Math.max(manualEnd, getSilentUntilImpl(settings, manualEnd)) } else { ret = getSilentUntilImpl(settings, currentTime) } return ret } private fun getSilentUntilImpl(settings: Settings, currentTime: Long): Long { var ret: Long = 0 if (!isEnabled(settings)) { return 0 } val cal = Calendar.getInstance() cal.timeInMillis = currentTime val from = settings.quietHoursFrom val silentFrom = DateTimeUtils.createCalendarTime(currentTime, from.component1(), from.component2()) val to = settings.quietHoursTo val silentTo = DateTimeUtils.createCalendarTime(currentTime, to.component1(), to.component2()) DevLog.debug(LOG_TAG, "getSilentUntil: ct=$currentTime, $from to $to") // Current silent period could have started yesterday, so account for this by rolling it back to one day silentFrom.addDays(-1) silentTo.addDays(-1) // Check if "from" is before "to", otherwise add an extra day to "to" if (silentTo.before(silentFrom)) silentTo.addDays(1) var cnt = 0 while (silentFrom.before(cal)) { if (cal.after(silentFrom) && cal.before(silentTo)) { // this hits silent period -- so it should be silent until 'silentTo' ret = silentTo.timeInMillis DevLog.debug(LOG_TAG, "Time hits silent period range, would be silent for ${(ret - currentTime) / 1000L} seconds since expected wake up time") break } silentFrom.addDays(1) silentTo.addDays(1) if (++cnt > 1000) break } return ret } override fun getSilentUntil(settings: Settings, currentTimes: LongArray): LongArray { val manualEndValue = Math.max(settings.manualQuietPeriodUntil, btDeviceManager.carModeSilentUntil) val tmp = LongArray(currentTimes.size) for (i in 0 until currentTimes.size) { if (currentTimes[i] < manualEndValue) { tmp[i] = manualEndValue } else { tmp[i] = currentTimes[i] } } val ret = getSilentUntilImpl(settings, tmp) for (i in 0 until currentTimes.size) { val manualEnd = if (currentTimes[i] < manualEndValue) manualEndValue else 0L if (ret[i] < manualEnd) ret[i] = manualEnd } return ret } private fun getSilentUntilImpl(settings: Settings, currentTimes: LongArray): LongArray { val ret = LongArray(currentTimes.size) if (!isEnabled(settings)) return ret if (ret.isEmpty()) return ret val cals = Array<Calendar>(ret.size) { idx -> val cal = Calendar.getInstance() cal.timeInMillis = currentTimes[idx] cal } val from = settings.quietHoursFrom val silentFrom: Calendar = DateTimeUtils.createCalendarTime(currentTimes[0], from.component1(), from.component2()) val to = settings.quietHoursTo val silentTo = DateTimeUtils.createCalendarTime(currentTimes[0], to.component1(), to.component2()) // Current silent period could have started yesterday, so account for this by rolling it back to one day silentFrom.addDays(-1) silentTo.addDays(-1) // Check if "from" is before "to", otherwise add an extra day to "to" if (silentTo.before(silentFrom)) silentTo.addDays(1) var cnt = 0 while (true) { var allPassed = true for ((idx, cal) in cals.withIndex()) { if (silentFrom.before(cal)) { allPassed = false } if (cal.after(silentFrom) && cal.before(silentTo)) // this hits silent period -- so it should be silent until 'silentTo' ret[idx] = silentTo.timeInMillis } if (allPassed) break silentFrom.addDays(1) silentTo.addDays(1) if (++cnt > 1000) break } return ret } companion object { private const val LOG_TAG = "QuietPeriodManager" } }
gpl-3.0
5699ef950c784de32c9485f51fbecaef
32.739535
158
0.628481
4.458513
false
false
false
false
ajordens/clouddriver
clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/util.kt
2
1957
/* * Copyright 2019 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.clouddriver.saga import com.fasterxml.jackson.annotation.JsonTypeName import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaSystemException import com.netflix.spinnaker.clouddriver.saga.flow.SagaAction import org.springframework.core.ResolvableType /** * Get the name of the provided [command] instance. * */ internal fun getStepCommandName(command: SagaCommand): String = getStepCommandName(command.javaClass) /** * Get the name of the provided [commandClass]. * * TODO(rz): Do we want our own annotation instead of relying on [JsonTypeName]? */ internal fun getStepCommandName(commandClass: Class<SagaCommand>): String = commandClass.getAnnotation(JsonTypeName::class.java)?.value ?: commandClass.simpleName /** * Get the [SagaCommand] for a given [SagaAction]. */ internal fun getCommandTypeFromAction(action: Class<out SagaAction<*>>): Class<SagaCommand> { val actionType = ResolvableType.forClass(SagaAction::class.java, action) actionType.resolve() val commandType = actionType.getGeneric(0) commandType.resolve() val rawClass = commandType.rawClass!! if (SagaCommand::class.java.isAssignableFrom(rawClass)) { @Suppress("UNCHECKED_CAST") return rawClass as Class<SagaCommand> } throw SagaSystemException("Resolved next action is not a SagaCommand: ${rawClass.simpleName}") }
apache-2.0
3872fa44cf18c8a6a2ebe768d47d7bea
34.581818
96
0.763924
4.235931
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/model/messages/MessageWaypoint.kt
1
1380
package org.owntracks.android.model.messages import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonTypeInfo import org.owntracks.android.support.Preferences @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "_type") @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_EMPTY) class MessageWaypoint : MessageBase() { @JsonProperty("desc") var description: String? = null @JsonProperty("lon") var longitude = 0.0 @JsonProperty("lat") var latitude = 0.0 @JsonProperty("tst") var timestamp: Long = 0 // Optional types for optional values @JsonProperty("rad") var radius: Int? = null override fun isValidMessage(): Boolean { return super.isValidMessage() && description != null } override fun addMqttPreferences(preferences: Preferences) { topic = preferences.pubTopicWaypoints qos = preferences.pubQosWaypoints retained = preferences.pubRetainWaypoints } override val baseTopicSuffix: String get() = BASETOPIC_SUFFIX companion object { const val TYPE = "waypoint" private const val BASETOPIC_SUFFIX = "/event" } }
epl-1.0
01b98e9f6080c28a63a8135e918b4f18
29
106
0.721739
4.6
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/rendering/PolygonRenderer.kt
1
959
package xyz.jmullin.drifter.rendering import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.PolygonRegion import com.badlogic.gdx.graphics.g2d.PolygonSprite import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.EarClippingTriangulator import com.badlogic.gdx.math.Vector2 import xyz.jmullin.drifter.extensions.list /** * Simple renderer wrapped around a PolygonBatch */ class PolygonRenderer(val batch: PolygonSpriteBatch, var texture: TextureRegion = Draw.fill, var color: Color = Color.WHITE) { val triangulator = EarClippingTriangulator() fun polygon(points: List<Vector2>) { val verts = points.flatMap { it.list() }.toFloatArray() val sprite = PolygonSprite(PolygonRegion(texture, verts, triangulator.computeTriangles(verts).items)) sprite.color = color sprite.draw(batch) batch.flush() } }
mit
2b8707a5ed0965117a4aeb3b2bf81168
32.103448
126
0.763295
3.898374
false
false
false
false
SourceUtils/hl2-utils
src/main/kotlin/com/timepath/hl2/net/Proxy.kt
1
2631
package com.timepath.hl2.net import com.timepath.with import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import kotlin.concurrent.thread fun main(args: Array<String>) { require(args.size() == 3, "Usage: <proxyPort> <serverAddr> <serverPort>") // bind to localhost instead of broadcast, can break TF2 otherwise val proxyAddr = InetAddress.getLocalHost(); val proxyPort = args[0].toInt() val serverAddr = args[1].let { InetAddress.getByName(it) } val serverPort = args[2].toInt() // getHostAddress to remove hostname, easier to read println("Proxy listening on ${proxyAddr.getHostAddress()}:$proxyPort, forwarding to ${serverAddr.getHostAddress()}:$serverPort") setupRoutes(DatagramSocket(proxyPort, proxyAddr), serverAddr, serverPort, {}) } fun setupRoutes(proxy: DatagramSocket, serverAddr: InetAddress, serverPort: Int, handle: (DatagramPacket) -> Unit) { val writerS = "proxyclient" val readerS = "proxyserver" val clientS = "client" val serverS = "server" val server = DatagramSocket() with { connect(serverAddr, serverPort) } var client: DatagramSocket val packet = packet() route(packet, "$writerS <- $clientS", proxy, "$writerS -> $serverS", server) { println("client is ${it.getAddress() to it.getPort()}") client = DatagramSocket() with { connect(it.getSocketAddress()) } handle(it) it.setAddress(null) } routeThread(writerS, packet, clientS, proxy, serverS, server) { handle(it) it.setAddress(null) } routeThread(readerS, packet(), serverS, server, clientS, proxy) { it.setSocketAddress(client.getRemoteSocketAddress()) } } val SOURCE_MAX_BYTES = 1400 fun packet() = ByteArray(SOURCE_MAX_BYTES) let { DatagramPacket(it, it.size()) } inline fun routeThread(name: String, packet: DatagramPacket, fromS: String, from: DatagramSocket, toS: String, to: DatagramSocket, @inlineOptions(InlineOption.ONLY_LOCAL_RETURN) handler: (DatagramPacket) -> Unit) { thread(name = "$fromS -> $name -> $toS") { while (true) { route(packet, "$name <- $fromS", from, "$name -> $toS", to, handler) } } } inline fun route(packet: DatagramPacket, fromS: String, from: DatagramSocket, toS: String, to: DatagramSocket, handler: (DatagramPacket) -> Unit) { from.receive(packet) handler(packet) to.send(packet) } inline fun log(msg: String, f: () -> Unit) = run { println(msg + "..."); f(); println(msg) }
artistic-2.0
f32e082bf32db99cc34775b8f504bb6f
36.585714
132
0.651463
3.915179
false
false
false
false
vsch/SmartData
src/com/vladsch/smart/MarkdownTable.kt
1
12362
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import com.intellij.openapi.editor.LogicalPosition import java.util.* data class TableCell(val charSequence: CharSequence, val untrimmedWidth: Int, val colSpan: Int = 1, val isUnterminated: Boolean = false) { init { assert(colSpan >= 1) } fun withColSpan(colSpan: Int): TableCell { return TableCell(charSequence, untrimmedWidth, colSpan) } } class TableRow(val rowCells: ArrayList<TableCell>, val isSeparator: Boolean) { constructor(rowCells: ArrayList<TableCell>) : this(rowCells, isSeparator(rowCells)) val totalColumns: Int get() { return columnOf(rowCells.size) } val isUnterminated: Boolean get() { return rowCells.size > 0 && rowCells[rowCells.size - 1].isUnterminated } fun columnOf(index: Int): Int { return columnOfOrNull(index)!! } fun columnOfOrNull(index: Int?): Int? { if (index == null) return null var columns = 0 for (i in 0..(index - 1).maxLimit(rowCells.size - 1)) { val cell = rowCells[i] columns += cell.colSpan } return columns } fun indexOf(column: Int): Int { return indexOfOrNull(column)!! } fun indexOfOrNull(column: Int?): Int? { if (column == null) return null var columns = 0 var index = 0 for (cell in rowCells) { if (columns >= column) break columns += cell.colSpan index++ } return index } private fun addColumn(index: Int = rowCells.size) { if (isSeparator) { rowCells.add(index, TableCell(MarkdownTableFormatter.SEPARATOR_COLUMN, MarkdownTableFormatter.SEPARATOR_COLUMN.length, 1)) } else { rowCells.add(index, TableCell(MarkdownTableFormatter.EMPTY_COLUMN, MarkdownTableFormatter.EMPTY_COLUMN.length, 1)) } } fun appendColumns(count: Int) { for (i in 1..count) { // add empty column addColumn() } } fun insertColumns(column: Int, count: Int) { if (count <= 0) return val totalColumns = totalColumns if (column >= totalColumns) { // append to the end appendColumns(count) } else { // insert in the middle var index = indexOf(column) val cellColumn = columnOf(index) if (cellColumn > column) { // spanning column, we expand its span val cell = rowCells[index] rowCells.removeAt(index) rowCells.add(index, cell.withColSpan(cell.colSpan + count)) } else { for (i in 1..count) { // add empty column addColumn(index) } } } } fun deleteColumns(column: Int, count: Int) { var remaining = count var index = indexOf(column) while (index < rowCells.size && remaining > 0) { val cell = rowCells[index] rowCells.removeAt(index); if (cell.colSpan > remaining) { rowCells.add(index, cell.withColSpan(cell.colSpan - remaining)) } remaining -= cell.colSpan } } private fun explicitColumns(): Array<TableCell?> { val explicitColumns = Array<TableCell?>(totalColumns) { null } var explicitIndex = 0 for (cell in rowCells) { explicitColumns[explicitIndex] = cell explicitIndex += cell.colSpan } return explicitColumns } private fun addExplicitColumns(explicitColumns: Array<TableCell?>, isUnterminated: Boolean) { var lastCell: TableCell? = null for (i in 0..explicitColumns.lastIndex) { val cell = explicitColumns[i] lastCell = if (cell == null) { lastCell?.withColSpan(lastCell.colSpan + 1) ?: TableCell(EMPTY_SEQUENCE, 0, 1, i == explicitColumns.lastIndex && isUnterminated) } else { if (lastCell != null) rowCells.add(lastCell) cell.withColSpan(1) } } if (lastCell != null) { rowCells.add(lastCell) } } fun moveColumn(fromColumn: Int, toColumn: Int) { val maxColumn = totalColumns if (fromColumn != toColumn && fromColumn < maxColumn && toColumn < maxColumn) { val isUnterminated = rowCells.last().isUnterminated val explicitColumns = explicitColumns() val fromCell = explicitColumns[fromColumn] if (toColumn < fromColumn) { // shift in between columns right System.arraycopy(explicitColumns, toColumn, explicitColumns, toColumn + 1, fromColumn - toColumn) } else { // shift in between columns left System.arraycopy(explicitColumns, fromColumn + 1, explicitColumns, fromColumn, toColumn - fromColumn) } explicitColumns[toColumn] = fromCell // reconstruct cells rowCells.clear() addExplicitColumns(explicitColumns, isUnterminated) } } fun isEmptyColumn(column: Int): Boolean { val index = indexOf(column) return isSeparator || index >= rowCells.size || rowCells[index].charSequence.isBlank() } fun isEmpty(): Boolean { if (isSeparator) return false for (cell in rowCells) { if (!cell.charSequence.isBlank()) return false } return true } companion object { @JvmStatic fun isSeparator(rowCells: ArrayList<TableCell>): Boolean { if (rowCells.isEmpty()) return false; for (cell in rowCells) { if (!MarkdownTableFormatter.SEPARATOR_COLUMN_PATTERN_REGEX.matches(cell.charSequence)) return false } return true } } fun logicalPosition(tableStartColumn: Int, row: Int, index: Int, inColumnOffset: Int): LogicalPosition? { if (index < rowCells.size) { var col = 0 val endColIndex = if (inColumnOffset < 0) index else index - 1 for (i in 0..endColIndex) { col += rowCells[i].untrimmedWidth } return LogicalPosition(row, tableStartColumn + col + inColumnOffset) } return null } } class MarkdownTable(val rows: ArrayList<TableRow>, val caption: String?, val indentPrefix: CharSequence, val exactColumn: Int?, val offsetRow: Int?, val offsetColumn: Int?) { private var mySeparatorRow: Int = 0 private var mySeparatorRowCount: Int = 0 init { computeSeparatorRow() } val isUnterminated: Boolean get() { return rows.size > 0 && rows[rows.size - 1].isUnterminated } val separatorRow: Int get() = mySeparatorRow val separatorRowCount: Int get() = mySeparatorRowCount val maxColumns: Int get() { return maxColumnsWithout() } val minColumns: Int get() { return minColumnsWithout() } fun fillMissingColumns(column: Int?) { val maxColumns = this.maxColumns for (row in rows) { val rowColumns = row.totalColumns val count = maxColumns - rowColumns if (count > 0) { var done = 0 if (column != null) { row.insertColumns(column, 1) done = 1 } if (count - done > 0) row.appendColumns(count - done) } } } fun insertColumns(column: Int, count: Int) { for (row in rows) { row.insertColumns(column, count) } } fun deleteColumns(column: Int, count: Int) { for (row in rows) { row.deleteColumns(column, count) } } fun insertRows(rowIndex: Int, count: Int) { val maxColumns = this.maxColumns for (i in 1..count) { val emptyRow = TableRow(ArrayList(), false) emptyRow.appendColumns(maxColumns) rows.add(rowIndex, emptyRow) } computeSeparatorRow() } fun moveColumn(fromColumn: Int, toColumn: Int) { for (row in rows) { row.moveColumn(fromColumn, toColumn) } } fun computeSeparatorRow() { var firstSeparator = -1 var secondSeparator = -1 var firstNonSeparator = -1 var separators = 0 var rowIndex = 0 for (row in rows) { if (row.isSeparator) { separators++ if (firstSeparator == -1) firstSeparator = rowIndex else if (secondSeparator == -1) secondSeparator = rowIndex } else if (firstNonSeparator == -1) firstNonSeparator = rowIndex rowIndex++ } if (secondSeparator == -1) mySeparatorRow = firstSeparator else { if (firstNonSeparator >= 0 && firstNonSeparator < firstSeparator) mySeparatorRow = firstSeparator else mySeparatorRow = secondSeparator } mySeparatorRowCount = separators } fun insertSeparatorRow(rowIndex: Int) { val maxColumns = this.maxColumns val emptyRow = TableRow(ArrayList(), true) emptyRow.appendColumns(maxColumns) rows.add(rowIndex, emptyRow) mySeparatorRowCount++ computeSeparatorRow() } fun deleteRows(rowIndex: Int, count: Int) { var remaining = count while (rowIndex < rows.size && remaining > 0) { rows.removeAt(rowIndex) remaining-- } computeSeparatorRow() } fun isEmptyColumn(column: Int): Boolean { for (row in rows) { if (!row.isEmptyColumn(column)) { return false } } return true } fun isEmptyRow(rowIndex: Int): Boolean { return rowIndex < rows.size && rows[rowIndex].isEmpty() } fun isSeparatorRow(rowIndex: Int): Boolean { return rowIndex == mySeparatorRow } fun maxColumnsWithout(vararg skipRows: Int): Int { var columns = 0 var index = 0 for (row in rows) { if (index !in skipRows) columns = columns.max(row.totalColumns) index++ } return columns } fun minColumnsWithout(vararg skipRows: Int): Int { var columns = Integer.MAX_VALUE var index = 0 for (row in rows) { if (index !in skipRows) columns = columns.min(row.totalColumns) index++ } return if (columns == Int.MAX_VALUE) 0 else columns } fun logicalPositionFromColumnOffset(tableStartColumn: Int, row: Int, column: Int, firstRowOffset: Int, inColumnOffset: Int): LogicalPosition? { if (row < rows.size) { return rows[row].logicalPosition(tableStartColumn, row + firstRowOffset, rows[row].indexOf(column), inColumnOffset) } return null } fun logicalPosition(tableStartColumn: Int, row: Int, column: Int, firstRowOffset: Int, inColumnOffset: Int): LogicalPosition? { if (row < rows.size) { return rows[row].logicalPosition(tableStartColumn, row + firstRowOffset, column, inColumnOffset) } return null } }
apache-2.0
5c113396d9fec3e49b2693d6da9ab453
29.448276
174
0.58154
4.531525
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/real/RealState.kt
1
496
package cn.luo.yuan.maze.model.real import java.io.Serializable /** * Copyright @Luo * Created by Gavin Luo on 9/15/2017. */ abstract class RealState: Serializable { var id:String = "" open var priorState:RealState? = null open var nextState:RealState? = null fun newEmptyInstance():RealState{ val ni = this.javaClass.newInstance() ni.priorState = priorState?.newEmptyInstance() ni.nextState = nextState?.newEmptyInstance() return ni } }
bsd-3-clause
d73ced929763a31469d4c7e248032901
23.85
54
0.673387
3.729323
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsListFragment.kt
1
4300
package com.ruuvi.station.settings.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.View import androidx.core.view.isVisible import androidx.lifecycle.Observer import com.ruuvi.station.util.extensions.viewModel import com.ruuvi.station.R import com.ruuvi.station.database.TagRepository import com.ruuvi.station.util.BackgroundScanModes import com.ruuvi.station.util.extensions.setDebouncedOnClickListener import kotlinx.android.synthetic.main.fragment_app_settings_list.* import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.x.closestKodein import org.kodein.di.generic.instance import timber.log.Timber class AppSettingsListFragment : Fragment(R.layout.fragment_app_settings_list), KodeinAware { override val kodein: Kodein by closestKodein() private val viewModel: AppSettingsListViewModel by viewModel() private val repository: TagRepository by instance() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViewModel() setupUI() } private fun setupViewModel() { viewModel.experimentalFeatures.observe(viewLifecycleOwner, Observer { Timber.d("experimentalSettingsContainer $it") experimentalSettingsContainer.isVisible = it }) } private fun setupUI() { scanLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_background_scan) } gatewaySettingsLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.gateway_url) } graphSettingsLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_chart) } temperatureUnitLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_temperature_unit) } humidityUnitLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_humidity_unit) } pressureUnitLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_pressure_unit) } localeSettingsLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_language) } experimentalSettingsLayout.setDebouncedOnClickListener { (activity as? AppSettingsDelegate)?.openFragment(R.string.settings_experimental) } dashboardSwitch.isChecked = viewModel.isDashboardEnabled() dashboardSwitch.setOnCheckedChangeListener { _, isChecked -> viewModel.setIsDashboardEnabled(isChecked) } updateView() } private fun updateView() { var intervalText = "" if (viewModel.getBackgroundScanMode() != BackgroundScanModes.DISABLED) { val bgScanInterval = viewModel.getBackgroundScanInterval() val min = bgScanInterval / 60 val sec = bgScanInterval - min * 60 if (min > 0) intervalText += min.toString() + " " + getString(R.string.min) + " " if (sec > 0) intervalText += sec.toString() + " " + getString(R.string.sec) } if (viewModel.getBackgroundScanMode() == BackgroundScanModes.BACKGROUND) { bgScanDescriptionTextView.text = getString(R.string.settings_background_continuous_description, intervalText) } else { bgScanDescriptionTextView.text = getString(R.string.settings_background_disabled_description) } gatewayUrlSubTextView.text = viewModel.getGatewayUrl() if (gatewayUrlSubTextView.text.isEmpty()) gatewayUrlSubTextView.text = getString(R.string.gateway_disabled) val temperature = viewModel.getTemperatureUnit() temperatureUnitSubTextView.text = getString(temperature.title) val humidity = viewModel.getHumidityUnit() humidityUnitSubTextView.text = getString(humidity.title) val pressure = viewModel.getPressureUnit() pressureUnitSubTextView.text = getString(pressure.title) } }
mit
854983d9683b82140a99aa0d0c8ec4b1
39.186916
121
0.713953
4.772475
false
false
false
false
StefanOltmann/Kaesekaestchen
app/src/main/java/de/stefan_oltmann/kaesekaestchen/controller/SpielerManager.kt
1
2027
/* * Kaesekaestchen * A simple Dots'n'Boxes Game for Android * * Copyright (C) Stefan Oltmann * * Contact : [email protected] * Homepage: https://github.com/StefanOltmann/Kaesekaestchen * * This file is part of Kaesekaestchen. * * Kaesekaestchen 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. * * Kaesekaestchen 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 Kaesekaestchen. If not, see <http://www.gnu.org/licenses/>. */ package de.stefan_oltmann.kaesekaestchen.controller import de.stefan_oltmann.kaesekaestchen.model.Spieler /** * Der SpielerManager bestimmt, welcher Spieler am Zug ist und wählt den * nächsten Spieler aus. Er kennt alle Mitspieler. */ class SpielerManager { /** Liste aller Spieler. */ val spieler = Spieler.values().toList() /** Der Spieler, der gerade am Zug ist. */ private var _aktuellerSpieler: Spieler = Spieler.KAESE val aktuellerSpieler: Spieler get() = _aktuellerSpieler private var computerGegner: Spieler? = null /* * Der Computergegner wird zufällig bestimmt, damit * sowohl das Symbol als auch der beginnende Spieler * durchgewechselt wird. */ fun bestimmeZufaelligComputerGegner() { computerGegner = Spieler.values()[(0..1).random()] } fun isComputerGegner(spieler: Spieler) = spieler == computerGegner fun waehleNaechstenSpielerAus() { _aktuellerSpieler = if (_aktuellerSpieler == Spieler.KAESE) Spieler.MAUS else Spieler.KAESE } }
gpl-3.0
c57c3650989f91ed0419c1f8729f35f2
29.666667
73
0.69664
3.442177
false
false
false
false
EZTEQ/rbtv-firetv
app/src/main/java/de/markhaehnel/rbtv/rocketbeanstv/vo/ChatMessage.kt
1
1843
package de.markhaehnel.rbtv.rocketbeanstv.vo /* * { * "dateFrom": "2019-01-29T13:05:11.970Z", * "message": "FortOne Kreygasm", * "source": 0, * "specialPayload": { * "emotes": "822112:0-6/41:8-15", * "mod": false, * "subscriber": false, * "uuid": "aef98ee5-0980-4fbb-951c-f9516b30a0e5" * }, * "user": "EZTEQ", * "userIdentifier": "ezteq", * "uuid": "aef98ee5-0980-4fbb-951c-f9516b30a0e5" * } */ private const val DELIMITER_EMOTELIST = "/" private const val DELIMITER_EMOTEINFO = ":" private const val DELIMITER_EMOTESPAN = "," private const val DELIMITER_EMOTESPANINFO = "," data class ChatMessage( val dateFrom: String, val message: String, val source: Int, val user: String, val userIdentifier: String, val uuid: String, val specialPayload: SpecialPayload ) { fun getEmotes() : List<Emote> { val emoteList = mutableListOf<Emote>() if (!specialPayload.emotes.isNullOrEmpty()) { val emotes = specialPayload.emotes.split(DELIMITER_EMOTELIST) emotes.forEach { val (emoteId, emoteSpans) = it.split(DELIMITER_EMOTEINFO) val emote = Emote(emoteId.toInt()) emoteSpans.split(DELIMITER_EMOTESPAN).forEach { emoteSpan -> val (spanStart, spanEnd) = emoteSpan.split(DELIMITER_EMOTESPANINFO) emote.spans.add(EmoteSpan(spanStart.toInt(), spanEnd.toInt())) } emoteList.add(emote) } } return emoteList } data class Emote(val id: Int, val spans: MutableList<EmoteSpan> = mutableListOf()) data class EmoteSpan(val start: Int, val end: Int) } data class SpecialPayload( val emotes: String?, val mod: Boolean?, val subscriber: Boolean?, val uuid: String? )
mit
1c926f0ef0d6112321b1267e1353585e
27.369231
87
0.60879
3.400369
false
false
false
false
jilees/Fuel
fuel/src/main/kotlin/com/github/kittinunf/fuel/util/InputStreams.kt
1
495
package com.github.kittinunf.fuel.util import java.io.InputStream import java.io.OutputStream fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE, progress: ((Long) -> Unit)?): Long { var bytesCopied = 0L val buffer = ByteArray(bufferSize) var bytes = read(buffer) while (bytes >= 0) { out.write(buffer, 0, bytes) bytesCopied += bytes progress?.invoke(bytesCopied) bytes = read(buffer) } return bytesCopied }
mit
6f1e30bcf9b054b614630d46b9d5b3fb
28.117647
117
0.668687
3.991935
false
false
false
false
MichaelObi/PaperPlayer
app/src/main/java/xyz/michaelobi/paperplayer/presentation/musiclibrary/fragment/albums/AlbumsFragment.kt
1
4001
/* * MIT License * * Copyright (c) 2017 MIchael Obi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package xyz.michaelobi.paperplayer.presentation.musiclibrary.fragment.albums import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.Toast import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import xyz.michaelobi.paperplayer.R import xyz.michaelobi.paperplayer.data.model.Album import xyz.michaelobi.paperplayer.injection.Injector /** * PaperPlayer * Michael Obi * 23 10 2016 4:00 PM */ class AlbumsFragment : androidx.fragment.app.Fragment(), AlbumsView { lateinit var presenter: AlbumsPresenter private lateinit var albumsAdapter: AlbumsAdapter private lateinit var recyclerViewAlbums: androidx.recyclerview.widget.RecyclerView private lateinit var progressBar: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter = AlbumsPresenter(Injector.provideMusicRepository(activity), Schedulers.io(), AndroidSchedulers.mainThread()) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.fragment_albums, container, false) recyclerViewAlbums = v.findViewById(xyz.michaelobi.paperplayer.R.id.rv_albums_grid) as androidx.recyclerview.widget.RecyclerView progressBar = v.findViewById(xyz.michaelobi.paperplayer.R.id.progressbar_loading) as ProgressBar presenter.attachView(this) albumsAdapter = AlbumsAdapter(null, activity) with(recyclerViewAlbums) { layoutManager = androidx.recyclerview.widget.GridLayoutManager(context, calculateNoOfColumns()) setHasFixedSize(true) adapter = albumsAdapter } presenter.getAll() return v } private fun calculateNoOfColumns(): Int { val displayMetrics = requireActivity().resources.displayMetrics val dpWidth = displayMetrics.widthPixels / displayMetrics.density return (dpWidth / 180).toInt() } override fun onDestroyView() { super.onDestroyView() presenter.detachView() } override fun showList(albums: List<Album>) { recyclerViewAlbums.visibility = View.VISIBLE albumsAdapter.setAlbums(albums) } override fun showLoading() { recyclerViewAlbums.visibility = View.GONE progressBar.visibility = View.VISIBLE } override fun hideLoading() { progressBar.visibility = View.GONE } override fun showError(message: String) { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() } }
mit
955d1b8eca1f64bb5d9a5766733a5ace
37.471154
136
0.742564
4.808894
false
false
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/bookmarks/dialogs/EditBookmarkDialog.kt
1
2552
package de.ph1b.audiobook.features.bookmarks.dialogs import android.app.Dialog import android.os.Bundle import android.text.InputType import android.view.inputmethod.EditorInfo import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.bluelinelabs.conductor.Controller import de.ph1b.audiobook.R import de.ph1b.audiobook.common.conductor.DialogController import de.ph1b.audiobook.data.Bookmark2 import de.ph1b.audiobook.data.getBookmarkId import de.ph1b.audiobook.data.putBookmarkId /** * Dialog for changing the bookmark title. */ class EditBookmarkDialog(args: Bundle) : DialogController(args) { override fun onCreateDialog(savedViewState: Bundle?): Dialog { val bookmarkTitle = args.getString(NI_BOOKMARK_TITLE) val bookmarkId = args.getBookmarkId(NI_BOOKMARK_ID)!! val dialog = MaterialDialog(activity!!).apply { title(R.string.bookmark_edit_title) val inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT @Suppress("CheckResult") input( hintRes = R.string.bookmark_edit_hint, prefill = bookmarkTitle, allowEmpty = false, inputType = inputType ) { _, charSequence -> val callback = targetController as Callback val newTitle = charSequence.toString() callback.onEditBookmark(bookmarkId, newTitle) } positiveButton(R.string.dialog_confirm) } val editText = dialog.getInputField() editText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val callback = targetController as Callback val newTitle = editText.text.toString() callback.onEditBookmark(bookmarkId, newTitle) dismissDialog() true } else false } return dialog } interface Callback { fun onEditBookmark(id: Bookmark2.Id, title: String) } companion object { private const val NI_BOOKMARK_ID = "ni#bookMarkId" private const val NI_BOOKMARK_TITLE = "ni#bookmarkTitle" operator fun <T> invoke( target: T, bookmark: Bookmark2 ): EditBookmarkDialog where T : Controller, T : Callback { val args = Bundle().apply { putBookmarkId(NI_BOOKMARK_ID, bookmark.id) putString(NI_BOOKMARK_TITLE, bookmark.title) } return EditBookmarkDialog(args).apply { targetController = target } } } }
lgpl-3.0
306c8c149589ae2f8793c718f0a2dfd7
31.717949
92
0.709248
4.267559
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/preferenceGraph.kt
1
924
package app.lawnchair.ui.preferences import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.navigation.NavGraphBuilder import com.google.accompanist.navigation.animation.composable @OptIn(ExperimentalAnimationApi::class) inline fun NavGraphBuilder.preferenceGraph( route: String, crossinline root: @Composable () -> Unit, crossinline block: NavGraphBuilder.(subRoute: (String) -> String) -> Unit = { } ) { val subRoute: (String) -> String = { name -> "$route$name/" } composable(route = route) { CompositionLocalProvider(LocalRoute provides route) { root() } } block(subRoute) } val LocalRoute = compositionLocalOf { "" } @Composable fun subRoute(name: String) = "${LocalRoute.current}$name/"
gpl-3.0
c59b84b58e0a90a0d3de8aa943f84e77
32
83
0.743506
4.507317
false
false
false
false
Shashi-Bhushan/General
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/math/primes/StepsInPrime.kt
1
1343
package `in`.shabhushan.cp_trials.math.primes import kotlin.math.sqrt object StepsInPrime { fun isPrime(num: Long): Boolean = if (num != 2L && num % 2 == 0L) { false } else { var prime = true val sqrt = sqrt(num.toDouble()).toLong() + 1 (3L until sqrt step 2).forEach { if (num % it == 0L) prime = false } prime } fun isPrime2(x: Long) = (2L..sqrt(x.toDouble()).toLong()).none { x % it == 0L } // if these g-steps prime numbers don't exist return [] fun step( g: Int, m: Long, n: Long ): LongArray { if (g % 2 != 0) { return longArrayOf() } else { ((if (m % 2 == 0L) m + 1 else m)..n step 2).forEach { if (isPrime(it) && isPrime( it + g.toLong() ) ) { return longArrayOf(it, it + g.toLong()) } } return longArrayOf() } } fun step2( g: Int, m: Long, n: Long ): LongArray = ((if (m % 2 == 0L) m + 1 else m)..n step 2) .find { isPrime(it) && isPrime( it + g.toLong() ) } ?.let { longArrayOf(it, it + g.toLong()) } ?: longArrayOf() }
gpl-2.0
7368381e7f572a783321ad1a34c3af66
22.982143
83
0.419955
3.783099
false
false
false
false
angryziber/picasa-gallery
src/views/oauth.kt
1
288
package views // language=HTML fun oauth(refreshToken: String?) = """ <!DOCTYPE html> <html lang="en"> <body> Paste this to <code>config.properties</code>: <pre> google.oauth.refreshToken=$refreshToken </pre> <a href="/">See your authorized gallery</a> </body> </html> """
gpl-3.0
5b7f283eaac5ad9069db0cf77ce00e88
15.941176
47
0.65625
3.272727
false
true
false
false
clhols/zapr
app/src/main/java/dk/youtec/zapr/backend/BackendApi.kt
1
14629
package dk.youtec.zapr.backend import android.content.Context import android.net.Uri import android.os.Build import android.support.annotation.WorkerThread import android.util.Log import dk.youtec.zapr.backend.exception.BackendException import dk.youtec.zapr.model.* import dk.youtec.zapr.util.SharedPreferences import dk.youtec.zapr.util.SharedPreferences.SMART_CARD_ID import dk.youtec.zapr.util.UIDHelper import dk.youtec.zapr.util.iterator import okhttp3.MediaType import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import org.json.JSONException import org.json.JSONObject import java.util.* /** * API for communication with backend. */ class BackendApi(val context: Context, var uid: String = UIDHelper().getUID(context)) { private val TAG = BackendApi::class.java.simpleName /** * Login to web tv backend */ @WorkerThread fun login(email: String = SharedPreferences.getString(context, SharedPreferences.EMAIL), password: String = SharedPreferences.getString(context, SharedPreferences.PASSWORD)): Boolean { val client = OkHttpClientFactory.getInstance(context) val body = enrichUrl(buildString { append("mitLoginMail=") append(email) append("&mitLoginPassword=") append(password) }) val request = Request.Builder() .url(URL_LOGIN) .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), body)) .build() var response: Response? = null try { response = client.newCall(request).execute() var jsonResponse = response.body()!!.string() Log.d(TAG, "Login response: " + jsonResponse) val loginResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(loginResponse) if (loginResponse.optBoolean("status")) { val loginData = loginResponse.optJSONObject("loginData") if (loginData != null) { val loginStatus = loginData.optBoolean("loginStatus") return loginStatus } } else { return false } } catch (e: Exception) { Log.e(TAG, e.message, e) } finally { closeResponse(response) } return false } /** * Get EPG channel data. */ @WorkerThread fun retrieveEpgData(genreId: Int = 0): EpgResult { val channels = mutableListOf<Channel>() var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_EPG.replace("[FAVOURITE_KEY]", SharedPreferences.getString(context, SharedPreferences.FAVOURITE_LIST_KEY, "0"))) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "EPG response: " + jsonResponse) val epgResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(epgResponse) if (!epgResponse.optBoolean("status")) { throw BackendException(epgResponse.optInt("error"), epgResponse.optString("info")) } val data = epgResponse.getJSONObject("data") val epgData = data.getJSONArray("epgData") for (channel in epgData) { channels.add(Channel.fromJSONObject(channel)) } return EpgResult(data.optLong("updateNextInSec"), channels.filter { (genreId == 0 || it.now?.genreId == genreId) }) } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } /** * Get EPG program data for a single channel. */ @WorkerThread fun retrievePrograms(channelSID: String, startTimeToRetrieveDataFrom: Long = System.currentTimeMillis() - 48 * 60 * 60 * 1000, hoursOfDataToRetrieve: Int = 256): MutableList<Program> { val programs = mutableListOf<Program>() var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_EPG_CHANNEL .replace("[SID]", channelSID) .replace("[HOURS_OF_DATA]", hoursOfDataToRetrieve.toString()) .replace("[TIME_FROM]", (startTimeToRetrieveDataFrom / 1000).toString()) ) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "EPG response: " + jsonResponse) val epgResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(epgResponse) if (!epgResponse.optBoolean("status")) { throw BackendException(epgResponse.optInt("error"), epgResponse.optString("info")) } val data = epgResponse.getJSONObject("data") val epgData = data.getJSONArray("epgData") for (program in epgData) { programs.add(Program.fromJSONObject(program)) } return programs } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } /** * Get id of TV box to control */ @WorkerThread fun retrieveSmartCards(): String { var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_GET_SMART_CARDS) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "SmartCard response: " + jsonResponse) val smartCardResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(smartCardResponse) val smartCards = smartCardResponse.getJSONArray("data") if (smartCards.length() > 0) { val id = smartCards.getJSONObject(0).getString("id") return id } else { return "" } } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } /** * Retrieve channels lists */ @WorkerThread fun retrieveFavouriteLists(): List<FavouriteList> { val list = mutableListOf<FavouriteList>() var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_FAVORITE_LISTS) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "FavouriteLists response: " + jsonResponse) val favouriteListsResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(favouriteListsResponse) val favourites = favouriteListsResponse.getJSONArray("data") if (favourites.length() > 0) { for (i in favourites.length() - 1 downTo 0) { val jsonArray = favourites.getJSONArray(i) val key = jsonArray.getInt(0) val name = jsonArray.getString(1) list.add(FavouriteList(key, name)) } } } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } return list } @WorkerThread fun changeToChannel(sid: String, eventId: Long, restart: Boolean = false): Boolean { var httpResponse: Response? = null try { var urlAddress = enrichUrl(URL_PUSH_SID_TO_TV) urlAddress = buildString { append(urlAddress) append("&smartcardId=") append(SharedPreferences.getString(context.applicationContext, SMART_CARD_ID)) append("&sid=") append(sid) if (restart && eventId > 0) { append("&eventId=") append(eventId) } } httpResponse = getHttpResponse(context.applicationContext, urlAddress) val pushSidResponse = JSONObject(unwrapJson(httpResponse.body()!!.string())) fetchLoginData(pushSidResponse) Log.d(TAG, "Push SID response: " + pushSidResponse) if (!pushSidResponse.optBoolean("data") || !pushSidResponse.optBoolean("status")) { return false } return true } finally { closeResponse(httpResponse) } } @WorkerThread fun getStreamUrl(sid: String, eventId: Long, restart: Boolean = false): String { var httpResponse: Response? = null try { var urlAddress = enrichUrl(URL_GET_STREAM) urlAddress = buildString { append(urlAddress) append("&sid=") append(sid) if (eventId > 0) { append("&eventId=") append(eventId) } } httpResponse = getHttpResponse(context.applicationContext, urlAddress) val streamResponse = JSONObject(unwrapJson(httpResponse.body()!!.string())) fetchLoginData(streamResponse) Log.d(TAG, "Get stream response: " + streamResponse) if (streamResponse.optBoolean("status")) { val streams = streamResponse.optJSONObject("data").optJSONObject("streams") var uri = "" if (!restart) uri = streams.optString("stream") else { uri = streams.optString("startover") if (uri.isNotBlank()) { if (streams.optJSONObject("drm").optString("catchup") == "1") { storeDrmCatchup(sid, streams.optLong("eventId")) // Not sure when this call is needed. } } else { uri = streams.optString("stream") } } Log.d(TAG, "Stream URL is " + uri) return uri } else { throw BackendException(streamResponse.getInt("error"), streamResponse.getString("info")) } } finally { closeResponse(httpResponse) } } @WorkerThread fun forceProvisioning() { var httpResponse: Response? = null try { val urlAddress = buildString { append(URL_FORCE_RETRY) append("&drmKey=") append(uid) } httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "Force provisioning response: " + jsonResponse) } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } @WorkerThread fun keepAlive(sid: String) { var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_KEEP_ALIVE .replace("[SID]", sid) .replace("[CUSTOMER_ID]", LoginData.customerId) .replace("[INSTALL_ID]", LoginData.installId) ) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "Keep alive response: " + jsonResponse) } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } @WorkerThread fun storeDrmCatchup(sid: String, eventId: Long) { var httpResponse: Response? = null try { val urlAddress = URL_STORE_DRM_CATCHUP .replace("[SID]", sid) .replace("[EVENT_ID]", eventId.toString()) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "Store DRM catchup response: " + jsonResponse) } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } } /** * Get genres. */ @WorkerThread fun retrieveEpgGenres(): List<Genre> { val genres: ArrayList<Genre> = ArrayList() var httpResponse: Response? = null try { val urlAddress = enrichUrl(URL_GET_GENRES) httpResponse = getHttpResponse(context, urlAddress) val jsonResponse = httpResponse.body()!!.string() Log.d(TAG, "Genres response: " + jsonResponse) val epgResponse = JSONObject(unwrapJson(jsonResponse)) fetchLoginData(epgResponse) if (!epgResponse.optBoolean("status")) { throw BackendException(epgResponse.optInt("error"), epgResponse.optString("info")) } val data = epgResponse.optJSONObject("data") if (data != null) { for (id in data.keys()) { val genreJson = data.optJSONObject(id) val genre = Genre.fromJSONObject(id.toInt(), genreJson) genres.add(genre) } } } catch (e: JSONException) { Log.e(TAG, e.message, e) throw BackendException(-1, e.message) } finally { closeResponse(httpResponse) } return genres } fun enrichUrl(url: String): String { return buildString { append(url) append("&manufacturer=") append(Uri.encode(Build.MANUFACTURER)) append("&model=") append(Build.MODEL.replace(" ", "+")) append("&uid=") append(uid) append("&token=") append(LoginData.token) append("&ver=") append(VERSION) append("&drmKey=") append(uid) append("&datatype=json") } } }
mit
7f016281746ac5a24ada989d5ee5cab8
32.024831
188
0.552464
4.894279
false
false
false
false
beyama/winter
winter-compiler/src/main/java/io/jentz/winter/compiler/generator/FactoryGenerator.kt
1
3623
package io.jentz.winter.compiler.generator import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview import io.jentz.winter.Component import io.jentz.winter.Graph import io.jentz.winter.TypeKey import io.jentz.winter.compiler.* import io.jentz.winter.compiler.model.FactoryModel import io.jentz.winter.inject.Factory @KotlinPoetMetadataPreview class FactoryGenerator( private val configuration: ProcessorConfiguration, private val model: FactoryModel ) { fun generate(): FileSpec { val typeName = model.typeName val factoryTypeName = model.factoryTypeName val graphName = Graph::class.asClassName() val factoryName = Factory::class.asClassName() val typeKeyName = TypeKey::class.asClassName() val componentBuilderName = Component.Builder::class.asClassName() val superInterfaceName = factoryName.parameterizedBy(factoryTypeName) val builderMethodName = if (model.isEagerSingleton) "eagerSingleton" else model.scope.name val constructorParameters = model.parameters.map { it.typeName.getInstanceCode(it.isNullable, it.qualifier) }.toTypedArray() val constructorSignature = when (constructorParameters.size) { 0 -> "" 1 -> "%L" else -> constructorParameters.joinToString(",\n ", "\n ", "\n") { "%L" } } val newInstanceCode = CodeBlock .of("%T($constructorSignature)", typeName, *constructorParameters) val newMembersInjectorCode = model.injectorModel ?.let { CodeBlock.of("%T()", it.generatedClassName) } val invokeMethod = FunSpec.builder("invoke") .addModifiers(KModifier.PUBLIC, KModifier.OVERRIDE) .returns(factoryTypeName) .addParameter("graph", graphName) .apply { if (newMembersInjectorCode != null) { addStatement("val instance = %L", newInstanceCode) addStatement("%L.inject(graph, instance)", newMembersInjectorCode) addStatement("return instance") } else { addStatement("return %L", newInstanceCode) } } .build() val qualifierArgument = model.qualifier?.let { "qualifier = \"$it\", " } ?: "" val registerMethod = FunSpec.builder("register") .addModifiers(KModifier.PUBLIC, KModifier.OVERRIDE) .returns(typeKeyName.parameterizedBy(factoryTypeName)) .addParameter("builder", componentBuilderName) .addParameter("override", BOOLEAN) .apply { model.scopeAnnotationName?.let { annotation -> addStatement("builder.checkComponentQualifier(%T::class)", annotation) } } .addCode(CodeBlock.of( "return builder.$builderMethodName(${qualifierArgument}override = override, factory = this)\n" )) .build() val factoryClass = TypeSpec.classBuilder(model.generatedClassName) .addSuperinterface(superInterfaceName) .addModifiers(KModifier.PUBLIC) .generatedAnnotation(configuration.generatedAnnotation) .addOriginatingElement(model.originatingElement) .addFunction(invokeMethod) .addFunction(registerMethod) .build() return FileSpec.get(model.generatedClassName.packageName, factoryClass) } }
apache-2.0
d53213512ad322043b6e5908dd9961a5
39.266667
110
0.642009
5.197991
false
false
false
false
toastkidjp/Yobidashi_kt
ui/src/main/java/jp/toastkid/ui/menu/view/OptionMenuItem.kt
1
1837
/* * Copyright (c) 2022 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.ui.menu.view import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material.Checkbox import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import jp.toastkid.lib.model.OptionMenu @Composable fun OptionMenuItem(optionMenu: OptionMenu) { Row( verticalAlignment = Alignment.CenterVertically ) { val title = stringResource(id = optionMenu.titleId) val iconId = optionMenu.iconId if (iconId != null) { Icon( painterResource(id = iconId), contentDescription = title, tint = MaterialTheme.colors.secondary ) } Text( title, fontSize = 16.sp, modifier = Modifier .weight(1f) .padding(start = 4.dp) ) val checkState = optionMenu.checkState if (checkState != null) { Checkbox( checked = checkState.value, onCheckedChange = {}, Modifier.clickable(false) {}) } } }
epl-1.0
d96db0ced9e38ccafa761de1f097f6c0
30.152542
88
0.670659
4.581047
false
false
false
false
uber/RIBs
android/tooling/rib-intellij-plugin/src/main/kotlin/com/uber/intellij/plugin/android/rib/ui/RibHierarchyRootNodeDescriptor.kt
1
3248
/* * Copyright (C) 2018-2019. Uber Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.intellij.plugin.android.rib.ui import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.util.CompositeAppearance import com.intellij.psi.PsiElement import com.uber.intellij.plugin.android.rib.AndroidDeviceRepositoryComponent import com.uber.intellij.plugin.android.rib.RibHierarchyBrowser import com.uber.intellij.plugin.android.rib.RibProjectComponent import com.uber.intellij.plugin.android.rib.io.RibHost import javax.swing.Icon /** Node descriptor used to render tree roots. */ class RibHierarchyRootNodeDescriptor( project: Project, element: PsiElement, val ribHost: RibHost, private val status: RibHierarchyBrowser.Status ) : RibHierarchyDescriptor(project, null, element, true) { companion object { /** Label used when android bridge is not connected */ const val LABEL_NO_BRIDGE: String = "No Android bridge. Make sure Android SDK is configured for this project." /** Label used when no device is connected. */ const val LABEL_NO_DEVICE: String = "No Android device connected..." /** Label used when device list is being refreshed. */ const val LABEL_WAIT: String = "Loading RIB info..." /** Label used when no no Rib info could be fetched from device. */ const val LABEL_ERROR: String = "No RIB info available. Make sure RIB app is running in foreground, then refresh." } override fun updateText(text: CompositeAppearance) { if (!AndroidDeviceRepositoryComponent.getInstance(project).isBridgeConnected()) { text.ending.addText(LABEL_NO_BRIDGE) return } if (!RibProjectComponent.getInstance(project).hasSelectedDevice()) { text.ending.addText(LABEL_NO_DEVICE) return } when (status) { RibHierarchyBrowser.Status.UNINITIALIZED -> { text.ending.addText(LABEL_NO_DEVICE) } RibHierarchyBrowser.Status.INITIALIZING -> { text.ending.addText(LABEL_WAIT) } else -> { val label: String = if (ribHost.name.isNotEmpty()) ribHost.name else LABEL_ERROR text.ending.addText(label, getDefaultTextAttributes()) } } } override fun getIcon(element: PsiElement): Icon? { if (!RibProjectComponent.getInstance(project).hasSelectedDevice()) { return AllIcons.General.BalloonInformation } return when (status) { RibHierarchyBrowser.Status.UNINITIALIZED -> { AllIcons.General.BalloonInformation } RibHierarchyBrowser.Status.INITIALIZING -> { AllIcons.Ide.UpDown } else -> { AllIcons.Actions.Dump } } } }
apache-2.0
ad0f37f7502ecd6f70e16550334c6ebb
33.553191
88
0.714286
4.28496
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/refactoring/extractFunction/RsExtractFunctionDialog.kt
1
1825
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.refactoring.extractFunction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiFile import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.ui.components.dialog import java.awt.Dimension import java.awt.GridLayout import javax.swing.JComboBox import javax.swing.JLabel import javax.swing.JPanel fun extractFunctionDialog( project: Project, file: PsiFile, config: RsExtractFunctionConfig ) { val contentPanel = JPanel(GridLayout(2, 2)) val functionNameLabel = JLabel() val functionNameField = NameSuggestionsField(project) val visibilityLabel = JLabel() val visibilityBox = JComboBox<String>() contentPanel.size = Dimension(522, 396) functionNameLabel.text = "Name:" visibilityLabel.text = "Visibility:" with(visibilityBox) { addItem("Public") addItem("Private") } visibilityBox.selectedItem = "Private" with(contentPanel) { add(visibilityLabel) add(functionNameLabel) add(visibilityBox) add(functionNameField) } dialog( "Extract Function", contentPanel, resizable = false, focusedComponent = functionNameField, okActionEnabled = true, project = project, parent = null, errorText = null, modality = DialogWrapper.IdeModalityType.IDE ) { config.name = functionNameField.enteredName config.visibilityLevelPublic = visibilityBox.selectedItem == "Public" RsExtractFunctionHandlerAction( project, file, config ).execute() true }.show() }
mit
3e304eb02cc3330ec7c7212d283e8625
26.238806
77
0.681644
4.573935
false
true
false
false
JimSeker/ui
Advanced/GuiDemo_kt/app/src/main/java/edu/cs4730/guidemo_kt/Button_Fragment.kt
1
2177
package edu.cs4730.guidemo_kt import android.content.Context import android.widget.TextView import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import android.util.Log import android.view.View import android.widget.Button import androidx.fragment.app.Fragment class Button_Fragment : Fragment(), View.OnClickListener { var TAG = "Button_Fragment" lateinit var myContext: Context lateinit var output: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.button_fragment, container, false) output = myView.findViewById(R.id.output) //setup the listeners. Each one setup a different way. //"standard" way val btn1 = myView.findViewById<Button>(R.id.button01) btn1.setOnClickListener { output.setText("Output:\nButton1") } //using the implements methods, ie this val btn2 = myView.findViewById<Button>(R.id.button02) btn2.setOnClickListener(this) //shortest version, no variable created. myView.findViewById<View>(R.id.button03).setOnClickListener(this) //note setting the listener in the xml android:onclick= will call the MainActivity, not the fragment! return myView } /* * This on is the for the implements View.OnClickListener * * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ override fun onClick(v: View) { if (v.id == R.id.button02) { //it's button 2 Toast.makeText(myContext, "Button 2 was clicked", Toast.LENGTH_SHORT).show() } else if (v.id == R.id.button03) { //it's button 3 output!!.text = "Output:\nButton3" } } override fun onAttach(context: Context) { super.onAttach(context) myContext = context Log.d(TAG, "onAttach") } }
apache-2.0
bb8044b79cc94e278f4a092f867937db
32.507692
109
0.673404
4.218992
false
false
false
false
Fitbit/MvRx
mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksExtensions.kt
1
11500
package com.airbnb.mvrx import android.os.Bundle import android.os.Parcelable import androidx.annotation.RestrictTo import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import java.io.Serializable import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty /** * For internal use only. Public for inline. * * Looks for [Mavericks.KEY_ARG] on the arguments of the fragments. */ @Suppress("FunctionName") @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @InternalMavericksApi fun <T : Fragment> T._fragmentArgsProvider(): Any? = arguments?.get(Mavericks.KEY_ARG) /** * Gets or creates a ViewModel scoped to this Fragment. You will get the same instance every time for this Fragment, even * through rotation, or other configuration changes. * * If the ViewModel has additional dependencies, implement [MavericksViewModelFactory] in its companion object. * You will be given the initial state as well as a FragmentActivity with which you can access other dependencies to * pass to the ViewModel's constructor. * * Mavericks will also handle persistence across process restarts. Refer to [PersistState] for more info. * * Use [keyFactory] if you have multiple ViewModels of the same class in the same scope. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.fragmentViewModel( viewModelClass: KClass<VM> = VM::class, crossinline keyFactory: () -> String = { viewModelClass.java.name } ): MavericksDelegateProvider<T, VM> where T : Fragment, T : MavericksView = viewModelDelegateProvider( viewModelClass, keyFactory, existingViewModel = false ) { stateFactory -> MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = FragmentViewModelContext( activity = requireActivity(), args = _fragmentArgsProvider(), fragment = this ), key = keyFactory(), initialStateFactory = stateFactory ) } /** * Gets or creates a ViewModel scoped to a parent fragment. This delegate will walk up the parentFragment hierarchy * until it finds a Fragment that can provide the correct ViewModel. If no parent fragments can provide the ViewModel, * a new one will be created in top-most parent Fragment. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.parentFragmentViewModel( viewModelClass: KClass<VM> = VM::class, crossinline keyFactory: () -> String = { viewModelClass.java.name } ): MavericksDelegateProvider<T, VM> where T : Fragment, T : MavericksView = viewModelDelegateProvider( viewModelClass, keyFactory, existingViewModel = true ) { stateFactory -> // 'existingViewModel' is set to true. Although this function works in both cases of // either existing or new viewmodel it would be more difficult to support both cases, // so we just test the common case of "existing". We can't be sure that the fragment // was designed for it to be used in the non-existing case (ie it may require arguments) if (parentFragment == null) { // Using ViewModelDoesNotExistException so mocking framework can intercept and mock the viewmodel in this case. throw ViewModelDoesNotExistException( "There is no parent fragment for ${this::class.java.simpleName} so view model ${viewModelClass.simpleName} could not be found." ) } var parent: Fragment? = parentFragment val key = keyFactory() while (parent != null) { try { return@viewModelDelegateProvider MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = FragmentViewModelContext( activity = this.requireActivity(), args = _fragmentArgsProvider(), fragment = parent ), key = key, forExistingViewModel = true ) } catch (e: ViewModelDoesNotExistException) { parent = parent.parentFragment } } // ViewModel was not found. Create a new one in the top-most parent. var topParentFragment = parentFragment while (topParentFragment?.parentFragment != null) { topParentFragment = topParentFragment.parentFragment } val viewModelContext = FragmentViewModelContext( requireActivity(), _fragmentArgsProvider(), topParentFragment!! ) MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = viewModelContext, key = keyFactory(), initialStateFactory = stateFactory ) } /** * Gets or creates a ViewModel scoped to a target fragment. Throws [IllegalStateException] if there is no target fragment. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.targetFragmentViewModel( viewModelClass: KClass<VM> = VM::class, crossinline keyFactory: () -> String = { viewModelClass.java.name } ): MavericksDelegateProvider<T, VM> where T : Fragment, T : MavericksView = viewModelDelegateProvider( viewModelClass, keyFactory, existingViewModel = true ) { stateFactory -> // 'existingViewModel' is set to true. Although this function works in both cases of // either existing or new viewmodel it would be more difficult to support both cases, // so we just test the common case of "existing". We can't be sure that the fragment // was designed for it to be used in the non-existing case (ie it may require arguments) val targetFragment = requireNotNull(targetFragment) { "There is no target fragment for ${this::class.java.simpleName}!" } MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = FragmentViewModelContext( activity = requireActivity(), args = targetFragment._fragmentArgsProvider(), fragment = targetFragment ), key = keyFactory(), initialStateFactory = stateFactory ) } /** * [activityViewModel] except it will throw [IllegalStateException] if the ViewModel doesn't already exist. * Use this for screens in the middle of a flow that cannot reasonably be an entry point to the flow. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.existingViewModel( viewModelClass: KClass<VM> = VM::class, crossinline keyFactory: () -> String = { viewModelClass.java.name } ): MavericksDelegateProvider<T, VM> where T : Fragment, T : MavericksView = viewModelDelegateProvider( viewModelClass, keyFactory, existingViewModel = true ) { stateFactory -> MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = ActivityViewModelContext( requireActivity(), _fragmentArgsProvider() ), key = keyFactory(), initialStateFactory = stateFactory, forExistingViewModel = true ) } /** * [fragmentViewModel] except scoped to the current Activity. Use this to share state between different Fragments. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.activityViewModel( viewModelClass: KClass<VM> = VM::class, noinline keyFactory: () -> String = { viewModelClass.java.name } ): MavericksDelegateProvider<T, VM> where T : Fragment, T : MavericksView = viewModelDelegateProvider( viewModelClass, keyFactory, existingViewModel = false ) { stateFactory -> MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = ActivityViewModelContext( activity = requireActivity(), args = _fragmentArgsProvider() ), key = keyFactory(), initialStateFactory = stateFactory ) } /** * [fragmentViewModel] except scoped to the current Activity. Use this to share state between different Fragments. */ inline fun <T, reified VM : MavericksViewModel<S>, reified S : MavericksState> T.viewModel( viewModelClass: KClass<VM> = VM::class, crossinline keyFactory: () -> String = { viewModelClass.java.name } ) where T : FragmentActivity = lifecycleAwareLazy(this) { MavericksViewModelProvider.get( viewModelClass = viewModelClass.java, stateClass = S::class.java, viewModelContext = ActivityViewModelContext(this, intent.extras?.get(Mavericks.KEY_ARG)), key = keyFactory() ) } /** * Fragment argument delegate that makes it possible to set fragment args without * creating a key for each one. * * To create arguments, define a property in your fragment like: * `private val listingId by arg<MyArgs>()` * * Each fragment can only have a single argument with the key [Mavericks.KEY_ARG] */ fun <V : Any> args() = object : ReadOnlyProperty<Fragment, V> { var value: V? = null override fun getValue(thisRef: Fragment, property: KProperty<*>): V { if (value == null) { val args = thisRef.arguments ?: throw IllegalArgumentException("There are no fragment arguments!") val argUntyped = args.get(Mavericks.KEY_ARG) argUntyped ?: throw IllegalArgumentException("MvRx arguments not found at key _root_ide_package_.com.airbnb.mvrx.Mavericks.KEY_ARG!") @Suppress("UNCHECKED_CAST") value = argUntyped as V } return value ?: throw IllegalArgumentException("") } } /** * Takes anything that is serializable and creates a Mavericks Fragment argument [Bundle]. * * Set this as your Fragment's arguments and you can use the [args] property delegate in your Fragment * to easily retrieve it. */ fun Serializable.asMavericksArgs() = Bundle().apply { putSerializable(Mavericks.KEY_ARG, this@asMavericksArgs) } /** * Takes anything that is [Parcelable] and creates a Mavericks Fragment argument [Bundle]. * * Set this as your Fragment's arguments and you can use the [args] property delegate in your Fragment * to easily retrieve it. */ fun Parcelable.asMavericksArgs() = Bundle().apply { putParcelable(Mavericks.KEY_ARG, this@asMavericksArgs) } /** * Helper to handle pagination. Use this when you want to append a list of results at a given offset. * This is safer than just appending blindly to a list because it guarantees that the data gets added * at the offset it was requested at. * * This will replace *all contents* starting at the offset with the new list. * For example: [1,2,3].appendAt([4], 1) == [1,4]] */ fun <T : Any> List<T>.appendAt(other: List<T>?, offset: Int) = subList(0, offset.coerceIn(0, size)) + (other ?: emptyList())
apache-2.0
6b6e933dea010d892edd89eaaaf11493
41.124542
143
0.663826
4.856419
false
false
false
false
http4k/http4k
http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/server/AuthenticationComplete.kt
1
2411
package org.http4k.security.oauth.server import dev.forkhandles.result4k.get import dev.forkhandles.result4k.map import dev.forkhandles.result4k.mapFailure import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.Response import org.http4k.security.ResponseType.Code import org.http4k.security.ResponseType.CodeIdToken class AuthenticationComplete( private val authorizationCodes: AuthorizationCodes, private val requestTracking: AuthRequestTracking, private val idTokens: IdTokens, private val documentationUri: String? = null ) : HttpHandler { override fun invoke(request: Request): Response { val authorizationRequest = requestTracking.resolveAuthRequest(request) ?: error("Authorization request could not be found.") return ResponseRender .forAuthRequest(authorizationRequest).addResponseTypeValues(authorizationRequest, request) .withState(authorizationRequest.state) .complete() } private fun ResponseRender.addResponseTypeValues( authorizationRequest: AuthRequest, request: Request, response: Response = this.complete() ): ResponseRender = with(authorizationCodes.create(request, authorizationRequest, response)) { map { when (authorizationRequest.responseType) { Code -> addParameter("code", it.value) CodeIdToken -> addParameter("code", it.value) .addParameter( "id_token", idTokens.createForAuthorization( request, authorizationRequest, response, authorizationRequest.nonce, it ).value ) } } .mapFailure { val responseRender = addParameter("error", it.rfcError.rfcValue) .addParameter("error_description", it.description) documentationUri?.addTo(responseRender) ?: responseRender } .get() } private fun String.addTo(responseRender: ResponseRender): ResponseRender = responseRender.addParameter("error_uri", this) }
apache-2.0
cb107c4c593007a8ca2f7af271f3f936
38.52459
102
0.599751
5.492027
false
false
false
false
johnnywey/kotlin-koans
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
1
960
package i_introduction._9_Extension_Functions import util.TODO import util.doc9 fun String.lastChar() = this[this.length - 1] // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber = RationalNumber(this, 1) fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(this.first, this.second)
mit
fb0426784471059ff51f7bcee782a4a8
28.090909
109
0.675
3.664122
false
false
false
false
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/download/view/outofspace/OutOfSpaceDialogPresenter.kt
1
3100
package cm.aptoide.pt.download.view.outofspace import cm.aptoide.pt.crashreports.CrashReport import cm.aptoide.pt.presenter.Presenter import cm.aptoide.pt.presenter.View import rx.Scheduler class OutOfSpaceDialogPresenter(private val view: OutOfSpaceDialogView, private val crashReporter: CrashReport, private val viewScheduler: Scheduler, private val ioScheduler: Scheduler, private val outOfSpaceManager: OutOfSpaceManager, private val outOfSpaceNavigator: OutOfSpaceNavigator) : Presenter { override fun present() { loadAppsToUninstall() loadRequiredStorageSize() uninstallApp() handleDismissDialogButtonClick() handleUninstalledEnoughApps() } private fun loadRequiredStorageSize() { view.lifecycleEvent .filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE } .flatMapSingle { outOfSpaceManager.getRequiredStorageSize() } .doOnNext { view.requiredSpaceToInstall(it) }.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY)) .subscribe({}, { e -> crashReporter.log(e) }) } private fun handleUninstalledEnoughApps() { view.lifecycleEvent .filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE } .flatMap { outOfSpaceManager.uninstalledEnoughApps() } .doOnNext { outOfSpaceNavigator.clearedEnoughSpace() view.dismiss() }.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY)) .subscribe({}, { e -> crashReporter.log(e) }) } private fun handleDismissDialogButtonClick() { view.lifecycleEvent .filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE } .flatMap { view.dismissDialogClick() } .doOnNext { view.dismiss() } .compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY)) .subscribe({}, { e -> crashReporter.log(e) }) } private fun uninstallApp() { view.lifecycleEvent .filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE } .flatMap { view.uninstallClick() } .flatMapSingle { outOfSpaceManager.uninstallApp(it) } .doOnNext { removedAppSize -> view.requiredSpaceToInstall(removedAppSize) } .compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY)) .subscribe({}, { e -> crashReporter.log(e) }) } private fun loadAppsToUninstall() { view.lifecycleEvent .filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE } .observeOn(ioScheduler) .flatMap { outOfSpaceManager.getInstalledApps() } .observeOn(viewScheduler) .doOnNext { appsList -> if (appsList.isNotEmpty()) { view.showInstalledApps(appsList) } else { view.showGeneralOutOfSpaceError() } } .compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY)) .subscribe({}, { e -> crashReporter.log(e) }) } }
gpl-3.0
6158920f94eb304a62cfdba645d865a5
37.7625
99
0.653871
4.806202
false
false
false
false
ShevaBrothers/easylib
src/core/cryptography/main/RSA.kt
1
2017
import java.math.BigInteger import java.security.SecureRandom /** * Generate an N-bit public and private RSA key and use to encrypt * and decrypt a message. * * @author Vasyl Antoniuk (@toniukan). * @since 0.2 */ class RSA: AbstractCryptoAlgorithm { private var modulo: BigInteger = BigInteger("1") private var privateKey: BigInteger = BigInteger("1") private var publicKey: BigInteger = BigInteger("1") private var bitlen = 1024 /** * Create an instance that can encrypt using someone elses public key. */ constructor(newModulo: BigInteger, newPublicKey: BigInteger) { modulo = newModulo publicKey = newPublicKey privateKey = publicKey.modInverse(modulo) } /** * Create an instance that can both encrypt and decrypt. */ constructor(bits: Int) { bitlen = bits generateKeys() } /** * Encrypt the given plaintext message. */ override fun encrypt(message: String): String { return BigInteger(message.toByteArray()).modPow(publicKey, modulo).toString() } /** * Decrypt the given ciphertext message. */ override fun decrypt(message: String): String { return String(BigInteger(message).modPow(privateKey, modulo).toByteArray()) } /** * Generate a new public and private key set. */ fun generateKeys() { val random = SecureRandom() val p = BigInteger(bitlen / 2, 100, random) val q = BigInteger(bitlen / 2, 100, random) modulo = p.multiply(q) val m = p.subtract(BigInteger.ONE) .multiply(q.subtract(BigInteger.ONE)) publicKey = BigInteger("3") while (m.gcd(publicKey).toInt() > 1) { publicKey = publicKey.add(BigInteger("2")) } privateKey = publicKey.modInverse(m) } /** * Return the modulus. */ fun getModulo() = modulo /** * Return the public key. */ fun getPublicKey() = publicKey }
mit
483cb9ddb95278029736bf9d725b08e8
25.552632
85
0.612295
4.309829
false
false
false
false
mixitconf/mixit
src/main/kotlin/mixit/config/GmailApiConfig.kt
1
1891
package mixit.config import com.google.api.client.auth.oauth2.Credential import com.google.api.client.googleapis.auth.oauth2.GoogleCredential import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.jackson2.JacksonFactory import com.google.api.client.util.store.MemoryDataStoreFactory import com.google.api.services.gmail.Gmail import com.google.api.services.gmail.GmailScopes import mixit.MixitProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.core.io.ClassPathResource @Configuration @Profile("service-mail") class GmailApiConfig { @Bean fun jacksonFactory(): JacksonFactory = JacksonFactory.getDefaultInstance() @Bean fun dataStoreFactory(): MemoryDataStoreFactory = MemoryDataStoreFactory.getDefaultInstance() @Bean fun httpTransport(): NetHttpTransport = GoogleNetHttpTransport.newTrustedTransport() @Bean fun authorize(properties: MixitProperties): Credential = GoogleCredential.Builder() .setTransport(httpTransport()) .setJsonFactory(jacksonFactory()) .setServiceAccountId(properties.googleapi.clientid) .setServiceAccountPrivateKeyFromP12File(ClassPathResource(properties.googleapi.p12path).file) .setServiceAccountScopes(listOf(GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_INSERT, GmailScopes.MAIL_GOOGLE_COM)) .setServiceAccountUser(properties.googleapi.user) .build() .apply { this.refreshToken } @Bean fun gmailService(properties: MixitProperties): Gmail = Gmail .Builder(httpTransport(), jacksonFactory(), authorize(properties)) .setApplicationName(properties.googleapi.appname).build() }
apache-2.0
4d4fe436f77f783f2dd80d0180bf1172
41.022222
122
0.793231
4.211581
false
true
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooUpdateVariationFragment.kt
2
14612
package org.wordpress.android.fluxc.example.ui.products import android.app.DatePickerDialog import android.app.DatePickerDialog.OnDateSetListener import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import androidx.fragment.app.Fragment import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_woo_update_variation.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.example.R.layout import org.wordpress.android.fluxc.example.prependToLog import org.wordpress.android.fluxc.example.ui.FloatingLabelEditText import org.wordpress.android.fluxc.example.ui.ListSelectorDialog import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.ARG_LIST_SELECTED_ITEM import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.LIST_SELECTOR_REQUEST_CODE import org.wordpress.android.fluxc.example.utils.showSingleLineDialog import org.wordpress.android.fluxc.model.WCProductVariationModel import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductBackOrders import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductTaxStatus import org.wordpress.android.fluxc.store.WCProductStore import org.wordpress.android.fluxc.store.WCProductStore.OnVariationUpdated import org.wordpress.android.fluxc.store.WCProductStore.UpdateVariationPayload import org.wordpress.android.fluxc.store.WooCommerceStore import org.wordpress.android.fluxc.utils.DateUtils import org.wordpress.android.util.StringUtils import java.util.Calendar import javax.inject.Inject class WooUpdateVariationFragment : Fragment() { @Inject internal lateinit var dispatcher: Dispatcher @Inject internal lateinit var wcProductStore: WCProductStore @Inject internal lateinit var wooCommerceStore: WooCommerceStore private var selectedSitePosition: Int = -1 private var selectedRemoteProductId: Long? = null private var selectedRemoteVariationId: Long? = null private var selectedVariationModel: WCProductVariationModel? = null private val coroutineScope = CoroutineScope(Dispatchers.Main) companion object { const val ARG_SELECTED_SITE_POS = "ARG_SELECTED_SITE_POS" const val ARG_SELECTED_PRODUCT_ID = "ARG_SELECTED_PRODUCT_ID" const val ARG_SELECTED_VARIATION_ID = "ARG_SELECTED_VARIATION_ID" const val LIST_RESULT_CODE_TAX_STATUS = 101 const val LIST_RESULT_CODE_STOCK_STATUS = 102 const val LIST_RESULT_CODE_BACK_ORDERS = 103 fun newInstance(selectedSitePosition: Int): WooUpdateVariationFragment { val fragment = WooUpdateVariationFragment() val args = Bundle() args.putInt(ARG_SELECTED_SITE_POS, selectedSitePosition) fragment.arguments = args return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { selectedSitePosition = it.getInt(ARG_SELECTED_SITE_POS, 0) } } override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(layout.fragment_woo_update_variation, container, false) override fun onStart() { super.onStart() dispatcher.register(this) } override fun onStop() { super.onStop() dispatcher.unregister(this) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(ARG_SELECTED_SITE_POS, selectedSitePosition) selectedRemoteProductId?.let { outState.putLong(ARG_SELECTED_PRODUCT_ID, it) } selectedRemoteVariationId?.let { outState.putLong(ARG_SELECTED_VARIATION_ID, it) } } @Suppress("LongMethod", "ComplexMethod") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) product_enter_product_id.setOnClickListener { showSingleLineDialog(activity, "Enter the remoteProductId of product to fetch:") { editText -> selectedRemoteProductId = editText.text.toString().toLongOrNull() selectedRemoteProductId?.let { productId -> showSingleLineDialog(activity, "Enter the remoteVariation of variation to fetch:") { editText -> selectedRemoteVariationId = editText.text.toString().toLongOrNull() selectedRemoteVariationId?.let { variationId -> updateSelectedProductId(productId, variationId) } ?: prependToLog("No valid remoteVariation defined...doing nothing") } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } product_description.onTextChanged { selectedVariationModel?.description = it } product_sku.onTextChanged { selectedVariationModel?.sku = it } product_regular_price.onTextChanged { selectedVariationModel?.regularPrice = it } product_sale_price.onTextChanged { selectedVariationModel?.salePrice = it } product_width.onTextChanged { selectedVariationModel?.width = it } product_height.onTextChanged { selectedVariationModel?.height = it } product_length.onTextChanged { selectedVariationModel?.length = it } product_weight.onTextChanged { selectedVariationModel?.weight = it } product_stock_quantity.onTextChanged { if (it.isNotEmpty()) { selectedVariationModel?.stockQuantity = it.toDouble() } } product_manage_stock.setOnCheckedChangeListener { _, isChecked -> selectedVariationModel?.manageStock = isChecked for (i in 0 until manageStockContainer.childCount) { val child = manageStockContainer.getChildAt(i) if (child is Button || child is FloatingLabelEditText) { child.isEnabled = isChecked } } } variation_visibility.setOnCheckedChangeListener { _, isChecked -> selectedVariationModel?.status = if (isChecked) "publish" else "private" } product_tax_status.setOnClickListener { showListSelectorDialog( CoreProductTaxStatus.values().map { it.value }.toList(), LIST_RESULT_CODE_TAX_STATUS, selectedVariationModel?.taxStatus ) } product_stock_status.setOnClickListener { showListSelectorDialog( CoreProductStockStatus.values().map { it.value }.toList(), LIST_RESULT_CODE_STOCK_STATUS, selectedVariationModel?.stockStatus ) } product_back_orders.setOnClickListener { showListSelectorDialog( CoreProductBackOrders.values().map { it.value }.toList(), LIST_RESULT_CODE_BACK_ORDERS, selectedVariationModel?.backorders ) } product_from_date.setOnClickListener { showDatePickerDialog(product_from_date.text.toString(), OnDateSetListener { _, year, month, dayOfMonth -> product_from_date.text = DateUtils.getFormattedDateString(year, month, dayOfMonth) selectedVariationModel?.dateOnSaleFromGmt = product_from_date.text.toString() }) } product_to_date.setOnClickListener { showDatePickerDialog(product_to_date.text.toString(), OnDateSetListener { _, year, month, dayOfMonth -> product_to_date.text = DateUtils.getFormattedDateString(year, month, dayOfMonth) selectedVariationModel?.dateOnSaleToGmt = product_to_date.text.toString() }) } product_update.setOnClickListener { getWCSite()?.let { site -> if (selectedVariationModel?.remoteProductId != null && selectedVariationModel?.remoteVariationId != null) { coroutineScope.launch { val result = wcProductStore.updateVariation( UpdateVariationPayload( site, selectedVariationModel!! ) ) if (result.isError) { prependToLog("Updating Variation Failed: " + result.error.type) } else { prependToLog("Variation updated ${result.rowsAffected}") } } } else { prependToLog("No valid remoteProductId or remoteVariationId defined...doing nothing") } } ?: prependToLog("No site found...doing nothing") } product_menu_order.onTextChanged { selectedVariationModel?.menuOrder = StringUtils.stringToInt(it) } savedInstanceState?.let { bundle -> selectedRemoteProductId = bundle.getLong(ARG_SELECTED_PRODUCT_ID) selectedRemoteVariationId = bundle.getLong(ARG_SELECTED_VARIATION_ID) selectedSitePosition = bundle.getInt(ARG_SELECTED_SITE_POS) } if (selectedRemoteProductId != null && selectedRemoteVariationId != null) { updateSelectedProductId(selectedRemoteProductId!!, selectedRemoteVariationId!!) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == LIST_SELECTOR_REQUEST_CODE) { val selectedItem = data?.getStringExtra(ARG_LIST_SELECTED_ITEM) when (resultCode) { LIST_RESULT_CODE_TAX_STATUS -> { selectedItem?.let { product_tax_status.text = it selectedVariationModel?.taxStatus = it } } LIST_RESULT_CODE_STOCK_STATUS -> { selectedItem?.let { product_stock_status.text = it selectedVariationModel?.stockStatus = it } } LIST_RESULT_CODE_BACK_ORDERS -> { selectedItem?.let { product_back_orders.text = it selectedVariationModel?.backorders = it } } } } } private fun updateSelectedProductId(remoteProductId: Long, remoteVariationId: Long) { getWCSite()?.let { siteModel -> enableProductDependentButtons() product_entered_product_id.text = "P: $remoteProductId, V: $remoteVariationId" selectedVariationModel = wcProductStore.getVariationByRemoteId( siteModel, remoteProductId, remoteVariationId )?.also { product_description.setText(it.description) product_sku.setText(it.sku) product_regular_price.setText(it.regularPrice) product_sale_price.setText(it.salePrice) product_width.setText(it.width) product_height.setText(it.height) product_length.setText(it.length) product_weight.setText(it.weight) product_tax_status.text = it.taxStatus product_from_date.text = it.dateOnSaleFromGmt.split('T')[0] product_to_date.text = it.dateOnSaleToGmt.split('T')[0] product_manage_stock.isChecked = it.manageStock product_stock_status.text = it.stockStatus product_back_orders.text = it.backorders product_stock_quantity.setText(it.stockQuantity.toString()) product_stock_quantity.isEnabled = product_manage_stock.isChecked product_menu_order.setText(it.menuOrder.toString()) variation_visibility.isChecked = it.status == "publish" } ?: WCProductVariationModel().apply { this.remoteProductId = remoteProductId this.remoteVariationId = remoteVariationId prependToLog("Variation not found in the DB. Did you fetch the variations?") } } ?: prependToLog("No valid site found...doing nothing") } private fun showListSelectorDialog(listItems: List<String>, resultCode: Int, selectedItem: String?) { fragmentManager?.let { fm -> val dialog = ListSelectorDialog.newInstance( this, listItems, resultCode, selectedItem ) dialog.show(fm, "ListSelectorDialog") } } private fun showDatePickerDialog(dateString: String?, listener: OnDateSetListener) { val date = if (dateString.isNullOrEmpty()) { DateUtils.getCurrentDateString() } else dateString val calendar = DateUtils.getCalendarInstance(date) DatePickerDialog(requireActivity(), listener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)) .show() } private fun getWCSite() = wooCommerceStore.getWooCommerceSites().getOrNull(selectedSitePosition) private fun enableProductDependentButtons() { for (i in 0 until productContainer.childCount) { val child = productContainer.getChildAt(i) if (child is Button || child is EditText) { child.isEnabled = true } } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductUpdated(event: OnVariationUpdated) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } prependToLog("Variation updated ${event.rowsAffected}") } }
gpl-2.0
645375c09abe04cc53db0d23035235e3
44.520249
117
0.643923
5.278902
false
false
false
false
lavenderx/foliage
foliage-api/src/main/kotlin/io/foliage/api/config/RpcCallableConfig.kt
1
2853
package io.foliage.api.config import com.google.common.base.CaseFormat import io.foliage.netty.rpc.annotation.RpcService import io.foliage.netty.rpc.core.MessageSendExecutor import io.foliage.netty.rpc.registry.ServiceDiscovery import io.foliage.utils.loggerFor import org.reflections.Reflections import org.springframework.beans.BeansException import org.springframework.beans.factory.config.BeanFactoryPostProcessor import org.springframework.beans.factory.config.ConfigurableListableBeanFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.util.Assert import java.io.IOException import java.util.* @Configuration open class RpcCallableConfig : BeanFactoryPostProcessor { private val logger = loggerFor<RpcCallableConfig>() private var registryAddress: String? = null private var serverAddress: String? = null init { loadRpcConfig() Assert.notNull(registryAddress) Assert.notNull(serverAddress) } @Bean open fun serviceDiscovery(): ServiceDiscovery { return ServiceDiscovery(registryAddress) } @Bean open fun rpcClient(): MessageSendExecutor { return MessageSendExecutor(serverAddress, serviceDiscovery()) } @Throws(BeansException::class) override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) { val rpcServicePackages = "io.foliage.netty.rpc.rpcservice" logger.info("Initializing RPC client stubs") val reflections = Reflections(rpcServicePackages) for (clazz in reflections.getTypesAnnotatedWith(RpcService::class.java)) { val rpcServiceName = clazz.simpleName logger.info("Processing rpc service annotation {}", rpcServiceName) // Register rpc stub val rpcClientStub = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, clazz.simpleName) logger.info("Registering rpc stub {}", rpcClientStub) val rpcServiceBean = MessageSendExecutor.execute(clazz) beanFactory.registerSingleton(rpcClientStub, clazz.cast(rpcServiceBean)) beanFactory.initializeBean(clazz.cast(rpcServiceBean), rpcClientStub) logger.info("Complete registering rpc service {}", rpcServiceName) } } private fun loadRpcConfig() { try { javaClass.classLoader.getResourceAsStream("rpc.properties").use { inputStream -> val props = Properties() props.load(inputStream) this.registryAddress = props.getProperty("registry.address") this.serverAddress = props.getProperty("server.address") } } catch (ex: IOException) { throw RuntimeException("Failed to read RPC config file") } } }
mit
ca22d331d72d305c8f9fe07c01e75f89
35.589744
99
0.716439
4.868601
false
true
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/ShowRecommendationsFragment.kt
1
5663
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.ui.suggestions.shows import android.content.Context import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import net.simonvt.cathode.R import net.simonvt.cathode.common.ui.fragment.SwipeRefreshRecyclerFragment import net.simonvt.cathode.entity.Show import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.settings.Settings import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler import net.simonvt.cathode.ui.CathodeViewModelFactory import net.simonvt.cathode.ui.LibraryType import net.simonvt.cathode.ui.NavigationListener import net.simonvt.cathode.ui.ShowsNavigationListener import net.simonvt.cathode.ui.lists.ListDialog import net.simonvt.cathode.ui.shows.ShowDescriptionAdapter import javax.inject.Inject class ShowRecommendationsFragment @Inject constructor( private val viewModelFactory: CathodeViewModelFactory, private val showScheduler: ShowTaskScheduler ) : SwipeRefreshRecyclerFragment<ShowDescriptionAdapter.ViewHolder>(), ShowRecommendationsAdapter.DismissListener, ListDialog.Callback, ShowDescriptionAdapter.ShowCallbacks { private lateinit var viewModel: ShowRecommendationsViewModel private var showsAdapter: ShowRecommendationsAdapter? = null private lateinit var navigationListener: ShowsNavigationListener private var shows: List<Show>? = null private lateinit var sortBy: SortBy private var columnCount: Int = 0 private var scrollToTop: Boolean = false enum class SortBy(val key: String, val sortOrder: String) { RELEVANCE("relevance", Shows.SORT_RECOMMENDED), RATING("rating", Shows.SORT_RATING); override fun toString(): String { return key } companion object { fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: RELEVANCE } } override fun onAttach(context: Context) { super.onAttach(context) navigationListener = requireActivity() as NavigationListener } override fun onCreate(inState: Bundle?) { super.onCreate(inState) sortBy = SortBy.fromValue( Settings.get(requireContext()) .getString(Settings.Sort.SHOW_RECOMMENDED, SortBy.RELEVANCE.key)!! ) columnCount = resources.getInteger(R.integer.showsColumns) setTitle(R.string.title_shows_recommended) setEmptyText(R.string.recommendations_empty) viewModel = ViewModelProviders.of(this, viewModelFactory).get(ShowRecommendationsViewModel::class.java) viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) }) viewModel.recommendations.observe(this, Observer { shows -> setShows(shows) }) } override fun getColumnCount(): Int { return columnCount } override fun onRefresh() { viewModel.refresh() } override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.sort_by -> { val items = arrayListOf<ListDialog.Item>() items.add(ListDialog.Item(R.id.sort_relevance, R.string.sort_relevance)) items.add(ListDialog.Item(R.id.sort_rating, R.string.sort_rating)) ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this) .show(requireFragmentManager(), DIALOG_SORT) return true } else -> return super.onMenuItemClick(item) } } override fun onItemSelected(id: Int) { when (id) { R.id.sort_relevance -> if (sortBy != SortBy.RELEVANCE) { sortBy = SortBy.RELEVANCE Settings.get(requireContext()) .edit() .putString(Settings.Sort.SHOW_RECOMMENDED, SortBy.RELEVANCE.key) .apply() viewModel.setSortBy(sortBy) scrollToTop = true } R.id.sort_rating -> if (sortBy != SortBy.RATING) { sortBy = SortBy.RATING Settings.get(requireContext()) .edit() .putString(Settings.Sort.SHOW_RECOMMENDED, SortBy.RATING.key) .apply() viewModel.setSortBy(sortBy) scrollToTop = true } } } override fun onShowClick(showId: Long, title: String?, overview: String?) { navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED) } override fun setIsInWatchlist(showId: Long, inWatchlist: Boolean) { showScheduler.setIsInWatchlist(showId, inWatchlist) } override fun onDismissItem(view: View, show: Show) { showScheduler.dismissRecommendation(show.id) showsAdapter!!.removeItem(show) } private fun setShows(shows: List<Show>) { this.shows = shows if (showsAdapter == null) { showsAdapter = ShowRecommendationsAdapter(requireContext(), this, this) adapter = showsAdapter return } showsAdapter!!.setList(shows) if (scrollToTop) { recyclerView.scrollToPosition(0) scrollToTop = false } } companion object { private const val DIALOG_SORT = "net.simonvt.cathode.ui.suggestions.shows.ShowRecommendationsFragment.sortDialog" } }
apache-2.0
37fbb6895c9c63165d2c30abee66aea0
30.99435
97
0.727
4.413874
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/ObjectGraphicInProminentMode.kt
1
4556
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.objectdetection import android.graphics.Canvas import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Paint.Style import android.graphics.PorterDuff import android.graphics.PorterDuffXfermode import android.graphics.Shader.TileMode import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.google.mlkit.md.camera.GraphicOverlay import com.google.mlkit.md.camera.GraphicOverlay.Graphic import com.google.mlkit.md.R import com.google.mlkit.vision.objects.DetectedObject /** * Draws the detected visionObject info over the camera preview for prominent visionObject detection mode. */ internal class ObjectGraphicInProminentMode( overlay: GraphicOverlay, private val visionObject: DetectedObject, private val confirmationController: ObjectConfirmationController ) : Graphic(overlay) { private val scrimPaint: Paint = Paint() private val eraserPaint: Paint private val boxPaint: Paint @ColorInt private val boxGradientStartColor: Int @ColorInt private val boxGradientEndColor: Int private val boxCornerRadius: Int init { // Sets up a gradient background color at vertical. scrimPaint.shader = if (confirmationController.isConfirmed) { LinearGradient( 0f, 0f, overlay.width.toFloat(), overlay.height.toFloat(), ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_start), ContextCompat.getColor(context, R.color.object_confirmed_bg_gradient_end), TileMode.CLAMP ) } else { LinearGradient( 0f, 0f, overlay.width.toFloat(), overlay.height.toFloat(), ContextCompat.getColor(context, R.color.object_detected_bg_gradient_start), ContextCompat.getColor(context, R.color.object_detected_bg_gradient_end), TileMode.CLAMP ) } eraserPaint = Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) } boxPaint = Paint().apply { style = Style.STROKE strokeWidth = context .resources .getDimensionPixelOffset( if (confirmationController.isConfirmed) { R.dimen.bounding_box_confirmed_stroke_width } else { R.dimen.bounding_box_stroke_width } ).toFloat() color = Color.WHITE } boxGradientStartColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_start) boxGradientEndColor = ContextCompat.getColor(context, R.color.bounding_box_gradient_end) boxCornerRadius = context.resources.getDimensionPixelOffset(R.dimen.bounding_box_corner_radius) } override fun draw(canvas: Canvas) { val rect = overlay.translateRect(visionObject.boundingBox) // Draws the dark background scrim and leaves the visionObject area clear. canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint) canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), eraserPaint) // Draws the bounding box with a gradient border color at vertical. boxPaint.shader = if (confirmationController.isConfirmed) { null } else { LinearGradient( rect.left, rect.top, rect.left, rect.bottom, boxGradientStartColor, boxGradientEndColor, TileMode.CLAMP ) } canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), boxPaint) } }
apache-2.0
301f25ce80c37647d84e483a2e5cbc09
35.741935
106
0.652985
4.831389
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/migration/MigrationPresenter.kt
1
6768
package cc.aoeiuv020.panovel.migration import android.content.Context import cc.aoeiuv020.panovel.Presenter import cc.aoeiuv020.panovel.api.NovelContext import cc.aoeiuv020.panovel.migration.impl.* import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.settings.SiteSettings import cc.aoeiuv020.panovel.util.Delegates import cc.aoeiuv020.panovel.util.Pref import cc.aoeiuv020.panovel.util.VersionName import cc.aoeiuv020.panovel.util.VersionUtil import org.jetbrains.anko.* import kotlin.reflect.KClass /** * mvp模式, * migration相关的尽量少用外面的拿数据的方法,以免相关方法过时被删除了, * 尽量不要用可能被混淆影响的代码, * * Created by AoEiuV020 on 2018.05.16-22:54:50. */ class MigrationPresenter( override val ctx: Context ) : Presenter<MigrationView>(), Pref, AnkoLogger { // sp file is App.ctx.packageName + "_$name" override val name: String = "Migration" /** * 缓存以前的版本, * key is "cachedVersion", * Delegate不受混淆影响, */ private var cachedVersion: String by Delegates.string("0") /** * 获取当前版本, */ private val currentVersion: String = VersionUtil.getAppVersionName(ctx) private fun list(vararg list: KClass<out Migration>): List<KClass<out Migration>> = list.toList() /** * 所有数据迁移封装的Migration, * 要保持按版本名排序, */ val list: List<Pair<String, List<KClass<out Migration>>>> = listOf( // listOf嵌套时智能识别类型有点问题,这里不用, "2.2.2" to list(DataMigration::class, LoginMigration::class), "3.2.4" to list(DownloadMigration::class), "3.4.1" to list(AdSettingsMigration::class) ) fun start() { debug { "start," } var cachedVersionName = VersionName(cachedVersion) val currentVersionName = VersionName(currentVersion) view?.doAsync({ e -> val message = if (e is MigrateException) { "迁移旧版数据失败,从<${cachedVersionName.name}>到<${e.migration.to.name}>" } else { "未知错误," } Reporter.post(message, e) error(message, e) ctx.runOnUiThread { if (e is MigrateException) { view?.showMigrateError(from = cachedVersionName, migration = e.migration) } else { view?.showError(message, e) } } }) { // 网站列表的迁移单独处理不影响版本号,直接同步最新支持的所有网站到数据库, // 由于操作了数据库,同时会触发room版本迁移, val sitesMigration = SitesMigration() if (NovelContext.sitesVersion > SiteSettings.cachedVersion) { uiThread { view?.showUpgrading(from = cachedVersionName, migration = sitesMigration) } sitesMigration.migrate(ctx, cachedVersionName) SiteSettings.cachedVersion = NovelContext.sitesVersion } when { cachedVersionName == currentVersionName -> uiThread { // 版本没变就直接返回, view?.showMigrateComplete(from = currentVersionName, to = currentVersionName) } cachedVersionName > currentVersionName -> uiThread { // 降级就记录一下现在的版本,防止反复显示降级,同时下次升级时能正常迁移降级后生成的数据, cachedVersion = currentVersion view?.showDowngrade(from = cachedVersionName, to = currentVersionName) view?.showMigrateComplete(from = cachedVersionName, to = currentVersionName) } cachedVersionName < currentVersionName -> { debug { "migrate start <${cachedVersionName.name} to ${currentVersionName.name}>" } // 缓存一开始的版本,迁移完成后展示, val beginVersionName = cachedVersionName list.dropWhile { (versionName, _) -> // 缓存的版本如果大于等于这个Migration的版本,就跳过这个Migration, cachedVersionName >= VersionName(versionName) }.forEach { (versionName, migrations) -> // 遍历所有剩下的Migration分段升级, // ui线程拿到这个cachedVersionName时可能已经变了,所以来个临时变量,虽然无所谓, val from = cachedVersionName migrations.forEach { clazz -> // 反射拿对象,免得加载不需要的migration, val migration = clazz.java.newInstance() uiThread { view?.showUpgrading(from = from, migration = migration) } debug { "migrate $cachedVersionName to ${migration.to}" } try { migration.migrate(ctx, cachedVersionName) } catch (e: Exception) { if (e is MigrateException) { throw e } else { throw MigrateException(migration = migration, cause = e) } } } // 每个阶段分别保存升级后的版本, cachedVersionName = VersionName(versionName) cachedVersion = cachedVersionName.name } // 最后缓存当前版本, cachedVersionName = currentVersionName cachedVersion = cachedVersionName.name uiThread { view?.showMigrateComplete(from = beginVersionName, to = currentVersionName) } } } } } fun ignoreMigration(migration: Migration) { debug { "ignoreMigration $migration" } view?.doAsync({ e -> val message = "sp保存出错," Reporter.post(message, e) error(message, e) ctx.runOnUiThread { view?.showError(message, e) } }) { cachedVersion = migration.to.name } } }
gpl-3.0
5de4e6a6154b6d5c5545a5bca0e7a5be
38.077419
99
0.530713
4.594841
false
false
false
false
ademar111190/Studies
Template/app/src/main/java/ademar/study/template/view/home/HomeFragment.kt
1
2314
package ademar.study.template.view.home import ademar.study.template.R import ademar.study.template.model.HelloWorldViewModel import ademar.study.template.presenter.home.HomePresenter import ademar.study.template.presenter.home.HomeView import ademar.study.template.view.base.BaseFragment import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.home_fragment.* import javax.inject.Inject class HomeFragment : BaseFragment(), HomeView { @Inject lateinit var presenter: HomePresenter @Inject lateinit var adapter: HomeAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater .inflate(R.layout.home_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) component.inject(this) presenter.onAttachView(this) reload.setOnClickListener { presenter.onReloadClick() } listRefresh.setOnRefreshListener { presenter.onReloadClick() } adapter.listener = presenter::onHelloWorldClick list.layoutManager = LinearLayoutManager(context) list.adapter = adapter } override fun onStart() { super.onStart() presenter.onStart() } override fun onDestroyView() { super.onDestroyView() presenter.onDetachView() } override fun showLoading() { list.visibility = View.GONE load.visibility = View.VISIBLE reload.visibility = View.GONE listRefresh.isRefreshing = false } override fun showRetry() { list.visibility = View.GONE load.visibility = View.GONE reload.visibility = View.VISIBLE listRefresh.isRefreshing = false } override fun showContent() { list.visibility = View.VISIBLE load.visibility = View.GONE reload.visibility = View.GONE listRefresh.isRefreshing = false } override fun clearHelloWorlds() { adapter.clear() } override fun bindHelloWorld(viewModel: HelloWorldViewModel) { adapter.addItem(viewModel) } }
mit
7a23c202cd9cfbe5c244fcbe0bd5863c
29.051948
125
0.709162
4.810811
false
false
false
false
dafi/photoshelf
birthday/src/main/java/com/ternaryop/photoshelf/birthday/util/notification/BirthdayNotification.kt
1
3703
package com.ternaryop.photoshelf.birthday.util.notification import android.app.Activity import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.Context import android.content.Intent import android.graphics.Color import android.text.TextUtils import androidx.core.app.NotificationCompat import com.ternaryop.photoshelf.api.birthday.Birthday import com.ternaryop.photoshelf.birthday.R import com.ternaryop.photoshelf.util.notification.notificationManager import com.ternaryop.utils.date.year import com.ternaryop.utils.date.yearsBetweenDates const val BIRTHDAY_CHANNEL_ID = "birthdayId" const val BIRTHDAY_CHANNEL_NAME = "Birthdays" const val BIRTHDAY_NOTIFICATION_ID = 1 private const val BIRTHDAY_TODAY_TAG = "com.ternaryop.photoshelf.birthday.today" fun List<Birthday>.notifyTodayBirthdays(context: Context, currYear: Int, activityClass: Class<out Activity>) { if (isEmpty()) { return } val builder = NotificationCompat.Builder(context, BIRTHDAY_CHANNEL_ID) .setContentIntent(createPendingIntent(context, activityClass)) .setSmallIcon(R.drawable.stat_notify_bday) .setAutoCancel(true) // remove notification when user clicks on it if (size == 1) { val birthday = this[0] builder.setContentTitle(context.resources.getQuantityString(R.plurals.birthday_title, size)) birthday.birthdate?.let { birthdate -> builder.setContentText( context.getString(R.string.birthday_years_old, birthday.name, birthdate.yearsBetweenDates()) ) } } else { builder.setStyle(buildBirthdayStyle(context, currYear)) // The text is shown when there isn't enough space for inboxStyle builder.setContentTitle(context.resources.getQuantityString(R.plurals.birthday_title, size, size)) builder.setContentText(TextUtils.join(", ", map { it.name })) } createBirthdayChannel(context).notify(BIRTHDAY_TODAY_TAG, BIRTHDAY_NOTIFICATION_ID, builder.build()) } private fun List<Birthday>.buildBirthdayStyle(context: Context, currYear: Int): NotificationCompat.Style { val inboxStyle = NotificationCompat.InboxStyle() inboxStyle.setBigContentTitle(context.getString(R.string.birthday_notification_title)) for (birthday in this) { birthday.birthdate?.let { birthdate -> val years = currYear - birthdate.year inboxStyle.addLine(context.getString(R.string.birthday_years_old, birthday.name, years)) } } return inboxStyle } private fun createPendingIntent(context: Context, activityClass: Class<out Activity>): PendingIntent { // Define Activity to start val resultIntent = Intent(context, activityClass) val stackBuilder = TaskStackBuilder.create(context) // Adds the back stack stackBuilder.addParentStack(activityClass) // Adds the Intent to the top of the stack stackBuilder.addNextIntent(resultIntent) // Gets a PendingIntent containing the entire back stack return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) } @Suppress("MagicNumber") fun createBirthdayChannel(context: Context): NotificationManager { val channel = NotificationChannel(BIRTHDAY_CHANNEL_ID, BIRTHDAY_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW) channel.enableLights(true) channel.lightColor = Color.GREEN channel.enableVibration(true) channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400) return context.notificationManager.also { it.createNotificationChannel(channel) } }
mit
03d177482056eb8ae80829f2291e5faf
41.563218
117
0.754523
4.413588
false
false
false
false
MisumiRize/HackerNews-Android
app/src/main/kotlin/org/misumirize/hackernews/app/StoryListFragment.kt
1
933
package org.misumirize.hackernews.app import android.os.Bundle import android.support.v4.app.ListFragment import java.util.* class StoryListFragment : ListFragment(), StoryView { val presenter = StoryListPresenter(this) var adapter: StoryListAdapter? = null var stories: ArrayList<Story> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App.getAppComponent().inject(presenter) adapter = StoryListAdapter(this.context) listAdapter = adapter presenter.onCreate(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putSerializable("stories", stories) } override fun onStories(stories: List<Story>) { this.stories.addAll(stories) adapter!!.addAll(stories) adapter!!.notifyDataSetChanged() } }
mit
72894b1e5a53d38a4ffb6a9fdff75fa8
29.096774
57
0.706324
4.809278
false
false
false
false
viniciussoares/ribot-android-boilerplate-kotlin
app/src/commonTest/kotlin/uk/co/ribot/androidboilerplate/test/common/TestDataFactory.kt
1
1218
package uk.co.ribot.androidboilerplate.test.common import uk.co.ribot.androidboilerplate.data.model.Name import uk.co.ribot.androidboilerplate.data.model.Profile import uk.co.ribot.androidboilerplate.data.model.Ribot import java.util.* object TestDataFactory { @JvmStatic fun randomUuid(): String { return UUID.randomUUID().toString() } @JvmStatic fun makeRibot(uniqueSuffix: String): Ribot { return Ribot(makeProfile(uniqueSuffix)) } @JvmStatic fun makeListRibots(number: Int): List<Ribot> { val ribots = ArrayList<Ribot>() for (i in 0..number.dec()) { ribots.add(makeRibot(i.toString())) } return ribots } @JvmStatic fun makeProfile(uniqueSuffix: String): Profile { return Profile( name = makeName(uniqueSuffix), email = "[email protected]", hexColor = "#0066FF", dateOfBirth = Date(), bio = randomUuid(), avatar = "http://api.ribot.io/images/" + uniqueSuffix) } @JvmStatic fun makeName(uniqueSuffix: String): Name { return Name("Name-" + uniqueSuffix, "Surname-" + uniqueSuffix) } }
apache-2.0
3f9e2a69c9e031be11852dbc0c8725ce
30.230769
70
0.623974
4.185567
false
true
false
false
nemerosa/ontrack
ontrack-extension-auto-versioning/src/test/java/net/nemerosa/ontrack/extension/av/AutoVersioningTestFixtures.kt
1
2688
package net.nemerosa.ontrack.extension.av import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.NullNode import net.nemerosa.ontrack.extension.av.config.AutoApprovalMode import net.nemerosa.ontrack.extension.av.config.AutoVersioningConfig import net.nemerosa.ontrack.extension.av.config.AutoVersioningNotification import net.nemerosa.ontrack.extension.av.config.AutoVersioningSourceConfig import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.test.TestUtils.uid import java.util.* object AutoVersioningTestFixtures { fun Branch.createOrder( sourceProject: String, targetVersion: String = "2.0.0" ) = AutoVersioningOrder( uuid = UUID.randomUUID().toString(), sourceProject = sourceProject, branch = this, targetPaths = listOf("gradle.properties"), targetRegex = null, targetProperty = "version", targetPropertyRegex = null, targetPropertyType = null, targetVersion = targetVersion, autoApproval = true, upgradeBranchPattern = "feature/version-<version>", postProcessing = null, postProcessingConfig = NullNode.instance, validationStamp = null, autoApprovalMode = AutoApprovalMode.SCM ) fun sampleConfig() = AutoVersioningConfig( configurations = listOf( sourceConfig(), sourceConfig(), ) ) fun sourceConfig( sourceProject: String = uid("P"), sourceBranch: String = "master", sourcePromotion: String = "IRON", targetRegex: String? = null, targetPath: String = "gradle.properties", targetProperty: String? = "version", upgradeBranchPattern: String? = null, postProcessing: String? = null, postProcessingConfig: JsonNode? = null, autoApprovalMode: AutoApprovalMode? = null, notifications: List<AutoVersioningNotification>? = null, ) = AutoVersioningSourceConfig( sourceProject = sourceProject, sourceBranch = sourceBranch, sourcePromotion = sourcePromotion, targetPath = targetPath, targetProperty = targetProperty, targetRegex = targetRegex, targetPropertyRegex = null, targetPropertyType = null, autoApproval = null, upgradeBranchPattern = upgradeBranchPattern, postProcessing = postProcessing, postProcessingConfig = postProcessingConfig, validationStamp = null, autoApprovalMode = autoApprovalMode, notifications = notifications, ) }
mit
24725ff0ac4366c2a562280fa2a87216
35.337838
74
0.688988
4.93211
false
true
false
false
binout/soccer-league
src/main/kotlin/io/github/binout/soccer/domain/season/MatchPlanning.kt
1
3602
/* * Copyright 2016 Benoît Prioux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.binout.soccer.domain.season import io.github.binout.soccer.domain.date.* import io.github.binout.soccer.domain.player.Player import io.github.binout.soccer.domain.player.PlayerRepository import org.springframework.stereotype.Component import java.lang.IllegalStateException import java.util.* @Component class MatchPlanning( private val seasonRepository: SeasonRepository, private val playerRepository: PlayerRepository, private val friendlyMatchDateRepository: FriendlyMatchDateRepository, private val leagueMatchDateRepository: LeagueMatchDateRepository) { fun substitutePlayer(season: Season, match: Match<*>, player: Player) { val matchDate = getMatchDate(match) ?: throw IllegalArgumentException("Unknown match date") val by = getSubstitutes(season, match).firstOrNull() if (by == null) { if (!match.removePlayer(player)) { throw IllegalStateException("Cannot substitute ${player.name.value}, no player available !") } } else { if (matchDate.isAbsent(by)) { throw IllegalArgumentException("${by.name.value} is not present for this date") } match.replacePlayer(player, by) } seasonRepository.replace(season) matchDate.absent(player) replaceMatchDate(matchDate) } private fun replaceMatchDate(matchDate: MatchDate) = when (matchDate) { is LeagueMatchDate -> leagueMatchDateRepository.replace(matchDate) is FriendlyMatchDate -> friendlyMatchDateRepository.replace(matchDate) } private fun getMatchDate(match: Match<*>): MatchDate? { val date = match.date return when (match) { is FriendlyMatch -> friendlyMatchDateRepository.byDate(date.year, date.month, date.dayOfMonth) is LeagueMatch -> leagueMatchDateRepository.byDate(date.year, date.month, date.dayOfMonth) } } fun getSubstitutes(season: Season, match: Match<*>): List<Player> { val date = getMatchDate(match) ?: throw IllegalArgumentException("Unknown match date") val players = match.players() val gamesPlayedComparator = getPlayerComparator(season, match) return playerRepository.all() .filter { date.isPresent(it) } .filterNot { it.name in players } .sortedWith(gamesPlayedComparator) } private fun getPlayerComparator(season: Season, match: Match<*>): Comparator<Player> { val counter = when (match) { is LeagueMatch -> leagueCounter(season) is FriendlyMatch -> globalCounter(season) } return Comparator.comparingInt { counter(it) } } companion object { internal fun leagueCounter(season: Season): (Player) -> Int = { season.statistics().leagueMatchPlayed(it) } internal fun globalCounter(season: Season): (Player) -> Int = { season.statistics().matchPlayed(it) } } }
apache-2.0
5ec23d05f8502f5cac5a7dc575be1a47
39.460674
115
0.683421
4.610755
false
false
false
false
aglne/mycollab
mycollab-web/src/main/java/com/mycollab/vaadin/ui/formatter/PrettyDateTimeHistoryFieldFormat.kt
3
2025
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.ui.formatter import com.hp.gagawa.java.elements.Span import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.core.utils.DateTimeUtils import com.mycollab.core.utils.StringUtils import com.mycollab.core.utils.TimezoneVal import com.mycollab.module.user.domain.SimpleUser import com.mycollab.vaadin.UserUIContext /** * @author MyCollab Ltd * @since 5.3.4 */ class PrettyDateTimeHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY)) override fun toString(currentViewUser: SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String = if (StringUtils.isNotBlank(value)) { val formatDate = DateTimeUtils.parseDateTimeWithMilisByW3C(value) if (displayAsHtml) { val lbl = Span().appendText(DateTimeUtils.getPrettyDateValue(formatDate, TimezoneVal.valueOf(currentViewUser.timezone), currentViewUser.locale)) lbl.title = value lbl.write() } else { UserUIContext.formatDateTime(formatDate) } } else { msgIfBlank } }
agpl-3.0
3c2055da216c37ed66045999f5bde219
40.306122
164
0.700593
4.448352
false
false
false
false
aglne/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/domain/SimpleTicketRelation.kt
3
372
package com.mycollab.module.project.domain /** * * @author MyCollab Ltd * @since 7.0.2 */ class SimpleTicketRelation : TicketRelation() { var ticketKey: Int? = null var ticketName: String? = null var ticketStatus: String? = null var typeKey: Int? = null var typeName: String? = null var typeStatus: String? = null var ltr: Boolean = true }
agpl-3.0
c2ccc816b1bad1c992333f3097c29d66
22.3125
47
0.66129
3.61165
false
false
false
false
kotlin-graphics/imgui
core/src/main/kotlin/imgui/internal/api/internalColumnsAPI.kt
2
10573
package imgui.internal.api import glm_.f import glm_.max import glm_.min import glm_.vec2.Vec2 import imgui.* import imgui.ImGui.buttonBehavior import imgui.ImGui.currentWindow import imgui.ImGui.currentWindowRead import imgui.ImGui.getColumnOffset import imgui.ImGui.isClippedEx import imgui.ImGui.keepAliveID import imgui.ImGui.popClipRect import imgui.ImGui.popID import imgui.ImGui.popItemWidth import imgui.ImGui.pushClipRect import imgui.ImGui.pushID import imgui.ImGui.pushItemWidth import imgui.ImGui.setColumnOffset import imgui.ImGui.style import imgui.api.g import imgui.internal.classes.Rect import imgui.internal.* import imgui.internal.classes.Window import imgui.internal.sections.OldColumnData import imgui.internal.sections.OldColumnsFlag import imgui.internal.sections.OldColumnsFlags import imgui.internal.sections.hasnt import kotlin.math.max import kotlin.math.min /** Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) */ internal interface internalColumnsAPI { /** [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, * they would meddle many times with the underlying ImDrawCmd. * Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let * the subsequent single call to SetCurrentChannel() does it things once. */ fun setWindowClipRectBeforeSetChannel(window: Window, clipRect: Rect) { val clipRectVec4 = clipRect.toVec4() window.clipRect put clipRect window.drawList._cmdHeader.clipRect put clipRectVec4 // safe, new instance window.drawList._clipRectStack[window.drawList._clipRectStack.lastIndex] put clipRectVec4 } /** setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). */ fun beginColumns(strId: String = "", columnsCount: Int, flags: OldColumnsFlags) { val window = currentWindow assert(columnsCount >= 1) assert(window.dc.currentColumns == null) { "Nested columns are currently not supported" } // Acquire storage for the columns set val id = getColumnsID(strId, columnsCount) val columns = window.findOrCreateColumns(id) assert(columns.id == id) columns.current = 0 columns.count = columnsCount columns.flags = flags window.dc.currentColumns = columns val columnPadding = style.itemSpacing.x val halfClipExtendX = floor((window.windowPadding.x * 0.5f) max window.windowBorderSize) val max1 = window.workRect.max.x + columnPadding - max(columnPadding - window.windowPadding.x, 0f) val max2 = window.workRect.max.x + halfClipExtendX columns.apply { hostCursorPosY = window.dc.cursorPos.y hostCursorMaxPosX = window.dc.cursorMaxPos.x hostInitialClipRect put window.clipRect hostBackupParentWorkRect put window.parentWorkRect window.parentWorkRect put window.workRect // Set state for first column // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect offMinX = window.dc.indent - columnPadding + max(columnPadding - window.windowPadding.x, 0f) offMaxX = max(min(max1, max2) - window.pos.x, columns.offMinX + 1f) lineMinY = window.dc.cursorPos.y lineMaxY = lineMinY } // Clear data if columns count changed if (columns.columns.isNotEmpty() && columns.columns.size != columnsCount + 1) columns.columns.clear() // Initialize default widths columns.isFirstFrame = columns.columns.isEmpty() if (columns.columns.isEmpty()) for (i in 0..columnsCount) columns.columns += OldColumnData().apply { offsetNorm = i / columnsCount.f } for (n in 0 until columnsCount) { // Compute clipping rectangle val column = columns.columns[n] val clipX1 = round(window.pos.x + getColumnOffset(n)) val clipX2 = round(window.pos.x + getColumnOffset(n + 1) - 1f) column.clipRect = Rect(clipX1, -Float.MAX_VALUE, clipX2, +Float.MAX_VALUE) column.clipRect clipWithFull window.clipRect } if (columns.count > 1) { columns.splitter.split(window.drawList, 1 + columns.count) columns.splitter.setCurrentChannel(window.drawList, 1) pushColumnClipRect(0) } // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. val offset0 = getColumnOffset(columns.current) val offset1 = getColumnOffset(columns.current + 1) val width = offset1 - offset0 pushItemWidth(width * 0.65f) window.dc.columnsOffset = (columnPadding - window.windowPadding.x) max 0f window.dc.cursorPos.x = floor(window.pos.x + window.dc.indent + window.dc.columnsOffset) window.workRect.max.x = window.pos.x + offset1 - columnPadding } fun endColumns() { val window = currentWindow val columns = window.dc.currentColumns!! // ~IM_ASSERT(columns != NULL) popItemWidth() if (columns.count > 1) { popClipRect() columns.splitter merge window.drawList } val flags = columns.flags columns.lineMaxY = columns.lineMaxY max window.dc.cursorPos.y window.dc.cursorPos.y = columns.lineMaxY if (flags hasnt OldColumnsFlag.GrowParentContentsSize) window.dc.cursorMaxPos.x = columns.hostCursorMaxPosX // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy var isBeingResized = false if (flags hasnt OldColumnsFlag.NoBorder && !window.skipItems) { // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. val y1 = columns.hostCursorPosY max window.clipRect.min.y val y2 = window.dc.cursorPos.y min window.clipRect.max.y var draggingColumn = -1 for (n in 1 until columns.count) { val column = columns.columns[n] val x = window.pos.x + getColumnOffset(n) val columnId = columns.id + n val columnHitHw = imgui.api.columns.COLUMNS_HIT_RECT_HALF_WIDTH val columnHitRect = Rect(Vec2(x - columnHitHw, y1), Vec2(x + columnHitHw, y2)) keepAliveID(columnId) if (isClippedEx(columnHitRect, columnId, false)) continue var hovered = false var held = false if (flags hasnt OldColumnsFlag.NoResize) { val (_, ho, he) = buttonBehavior(columnHitRect, columnId) hovered = ho held = he if (hovered || held) g.mouseCursor = MouseCursor.ResizeEW if (held && column.flags hasnt OldColumnsFlag.NoResize) draggingColumn = n } // Draw column val col = if (held) Col.SeparatorActive else if (hovered) Col.SeparatorHovered else Col.Separator val xi = floor(x) window.drawList.addLine(Vec2(xi, y1 + 1f), Vec2(xi, y2), col.u32) } // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. if (draggingColumn != -1) { if (!columns.isBeingResized) for (n in 0..columns.count) columns.columns[n].offsetNormBeforeResize = columns.columns[n].offsetNorm columns.isBeingResized = true isBeingResized = true val x = imgui.api.columns.getDraggedColumnOffset(columns, draggingColumn) setColumnOffset(draggingColumn, x) } } columns.isBeingResized = isBeingResized window.apply { workRect put window.parentWorkRect parentWorkRect put columns.hostBackupParentWorkRect dc.currentColumns = null dc.columnsOffset = 0f dc.cursorPos.x = floor(pos.x + dc.indent + dc.columnsOffset) } } fun pushColumnClipRect(columnIndex_: Int) { val window = currentWindowRead!! val columns = window.dc.currentColumns!! val columnIndex = if (columnIndex_ < 0) columns.current else columnIndex_ pushClipRect(columns.columns[columnIndex].clipRect.min, columns.columns[columnIndex].clipRect.max, false) } /** Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) */ fun pushColumnsBackground() { val window = currentWindowRead!! val columns = window.dc.currentColumns!! if (columns.count == 1) return // Optimization: avoid SetCurrentChannel() + PushClipRect() columns.hostBackupClipRect put window.clipRect setWindowClipRectBeforeSetChannel(window, columns.hostInitialClipRect) columns.splitter.setCurrentChannel(window.drawList, 0) } fun popColumnsBackground() { val window = currentWindowRead!! val columns = window.dc.currentColumns!! if (columns.count == 1) return // Optimization: avoid PopClipRect() + SetCurrentChannel() setWindowClipRectBeforeSetChannel(window, columns.hostBackupClipRect) columns.splitter.setCurrentChannel(window.drawList, columns.current + 1) } fun getColumnsID(strId: String, columnsCount: Int): ID { val window = g.currentWindow!! // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. pushID(0x11223347 + if (strId.isNotEmpty()) 0 else columnsCount) return window.getID(if (strId.isNotEmpty()) strId else "columns") .also { popID() } } // findOrCreateColumns is in Window class // GetColumnOffsetFromNorm and GetColumnNormFromOffset in Columns class }
mit
46115e8c4e200345bf7063f6e0b3e919
43.058333
143
0.658281
4.403582
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/util/History.kt
1
2570
package yuku.alkitab.base.util import androidx.annotation.Keep import yuku.afw.storage.Preferences import yuku.alkitab.base.App import yuku.alkitab.base.model.SyncShadow import yuku.alkitab.base.storage.Prefkey import yuku.alkitab.base.sync.Sync import yuku.alkitab.base.util.InstallationUtil.getInstallationId import yuku.alkitab.model.util.Gid import java.util.ArrayList private const val MAX_HISTORY_ENTRIES = 20 private const val TAG = "History" object History { @Keep data class Entry( @JvmField val gid: String, @JvmField val ari: Int, @JvmField val timestamp: Long, /** * The installationId of the device that creates this history entry. */ @JvmField val creator_id: String ) @Keep data class HistoryJson( val entries: List<Entry> ) private val entries = mutableListOf<Entry>().apply { Preferences.getString(Prefkey.history)?.let { s -> this.addAll(App.getDefaultGson().fromJson(s, HistoryJson::class.java).entries) } } @Synchronized fun save() { val obj = HistoryJson(entries) val new_json = App.getDefaultGson().toJson(obj) val old_json = Preferences.getString(Prefkey.history) if (old_json != new_json) { Preferences.setString(Prefkey.history, new_json) Sync.notifySyncNeeded(SyncShadow.SYNC_SET_HISTORY) } else { AppLog.d(TAG, "History not changed.") } } @Synchronized fun add(ari: Int) { // check: do we have this previously? for (i in entries.indices.reversed()) { val entry = entries[i] if (entry.ari == ari) { // YES. Remove this. entries.removeAt(i) } } // Add it to the front entries.add(0, Entry(Gid.newGid(), ari, System.currentTimeMillis(), getInstallationId())) // and remove if overflow while (entries.size > MAX_HISTORY_ENTRIES) { entries.removeAt(MAX_HISTORY_ENTRIES) } } @Synchronized fun replaceAllEntries(newEntries: List<Entry>) { entries.clear() entries.addAll(newEntries) } @Synchronized fun getEntry(position: Int): Entry { return entries[position] } @get:Synchronized val size get() = entries.size /** * Entries sorted from the newest to the oldest */ fun listAllEntries(): List<Entry> { return ArrayList(entries) } }
apache-2.0
6168f683f49be98793ca6edad5e3e2e8
24.7
97
0.607393
4.172078
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/test/kotlin/app/cash/sqldelight/core/queries/PgInsertOnConflictTest.kt
1
5343
package app.cash.sqldelight.core.queries import app.cash.sqldelight.core.compiler.MutatorQueryGenerator import app.cash.sqldelight.dialects.postgresql.PostgreSqlDialect import app.cash.sqldelight.test.util.FixtureCompiler import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class PgInsertOnConflictTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun `postgres INSERT DO UPDATE works with 1 column`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL PRIMARY KEY, | col1 TEXT DEFAULT '' |); | |upsertCols: |INSERT INTO data |VALUES (:id, :c1) |ON CONFLICT (id) DO UPDATE SET col1 = :c1; """.trimMargin(), tempFolder, dialect = PostgreSqlDialect(), ) val insert = file.namedMutators.first() val generator = MutatorQueryGenerator(insert) assertThat(generator.function().toString()).isEqualTo( """ |public fun upsertCols(id: kotlin.Int?, c1: kotlin.String?): kotlin.Unit { | driver.execute(${insert.id}, ""${'"'} | |INSERT INTO data | |VALUES (?, ?) | |ON CONFLICT (id) DO UPDATE SET col1 = ? | ""${'"'}.trimMargin(), 3) { | check(this is app.cash.sqldelight.driver.jdbc.JdbcPreparedStatement) | bindLong(0, id?.let { it.toLong() }) | bindString(1, c1) | bindString(2, c1) | } | notifyQueries(${insert.id}) { emit -> | emit("data") | } |} | """.trimMargin(), ) } @Test fun `postgres INSERT DO UPDATE works with 2 columns`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL PRIMARY KEY, | col1 TEXT DEFAULT '', | col2 TEXT DEFAULT '', | col3 TEXT DEFAULT '' |); | |upsertCols: |INSERT INTO data |VALUES (:id, :c1, :c2, :c3) |ON CONFLICT (id) DO UPDATE SET col1 = :c1, col2 = :c2; """.trimMargin(), tempFolder, dialect = PostgreSqlDialect(), ) val insert = file.namedMutators.first() val generator = MutatorQueryGenerator(insert) assertThat(generator.function().toString()).isEqualTo( """ |public fun upsertCols( | id: kotlin.Int?, | c1: kotlin.String?, | c2: kotlin.String?, | c3: kotlin.String?, |): kotlin.Unit { | driver.execute(${insert.id}, ""${'"'} | |INSERT INTO data | |VALUES (?, ?, ?, ?) | |ON CONFLICT (id) DO UPDATE SET col1 = ?, col2 = ? | ""${'"'}.trimMargin(), 6) { | check(this is app.cash.sqldelight.driver.jdbc.JdbcPreparedStatement) | bindLong(0, id?.let { it.toLong() }) | bindString(1, c1) | bindString(2, c2) | bindString(3, c3) | bindString(4, c1) | bindString(5, c2) | } | notifyQueries(${insert.id}) { emit -> | emit("data") | } |} | """.trimMargin(), ) } @Test fun `postgres INSERT DO UPDATE works with 3 columns`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL PRIMARY KEY, | col1 TEXT DEFAULT '', | col2 TEXT DEFAULT '', | col3 TEXT DEFAULT '' |); | |upsertCols: |INSERT INTO data |VALUES (:id, :c1, :c2, :c3) |ON CONFLICT (id) DO UPDATE SET col1 = :c1, col2 = :c2, col3 = :c3; """.trimMargin(), tempFolder, dialect = PostgreSqlDialect(), ) val insert = file.namedMutators.first() val generator = MutatorQueryGenerator(insert) assertThat(generator.function().toString()).isEqualTo( """ |public fun upsertCols( | id: kotlin.Int?, | c1: kotlin.String?, | c2: kotlin.String?, | c3: kotlin.String?, |): kotlin.Unit { | driver.execute(${insert.id}, ""${'"'} | |INSERT INTO data | |VALUES (?, ?, ?, ?) | |ON CONFLICT (id) DO UPDATE SET col1 = ?, col2 = ?, col3 = ? | ""${'"'}.trimMargin(), 7) { | check(this is app.cash.sqldelight.driver.jdbc.JdbcPreparedStatement) | bindLong(0, id?.let { it.toLong() }) | bindString(1, c1) | bindString(2, c2) | bindString(3, c3) | bindString(4, c1) | bindString(5, c2) | bindString(6, c3) | } | notifyQueries(${insert.id}) { emit -> | emit("data") | } |} | """.trimMargin(), ) } }
apache-2.0
6fb248b2234f3091da9fdbce50f0c61b
31.779141
89
0.471645
4.230404
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/colorpicker/renderer/AbsColorWheelRenderer.kt
1
1157
package com.tamsiree.rxui.view.colorpicker.renderer import com.tamsiree.rxui.view.colorpicker.ColorCircle import java.util.* /** * @author tamsiree * @date 2018/6/11 11:36:40 整合修改 */ abstract class AbsColorWheelRenderer : ColorWheelRenderer { protected var colorWheelRenderOption: ColorWheelRenderOption? = null override var colorCircleList: MutableList<ColorCircle> = ArrayList() override fun initWith(colorWheelRenderOption: ColorWheelRenderOption) { this.colorWheelRenderOption = colorWheelRenderOption colorCircleList.clear() } override val renderOption: ColorWheelRenderOption get() { if (colorWheelRenderOption == null) { colorWheelRenderOption = ColorWheelRenderOption() } return colorWheelRenderOption!! } protected val alphaValueAsInt: Int protected get() = Math.round(colorWheelRenderOption!!.alpha * 255) protected fun calcTotalCount(radius: Float, size: Float): Int { return Math.max(1, ((1f - ColorWheelRenderer.GAP_PERCENTAGE) * Math.PI / Math.asin(size / radius.toDouble()) + 0.5f).toInt()) } }
apache-2.0
0bc6eef7e99735ec647780e803115187
34.9375
133
0.70148
4.133094
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/iface/IStatusesAdapter.kt
1
2523
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter.iface import de.vanita5.twittnuker.annotation.PreviewStyle import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.util.TwidereLinkify import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder /** * */ interface IStatusesAdapter<in Data> : IContentAdapter, IGapSupportedAdapter { @TwidereLinkify.HighlightStyle val linkHighlightingStyle: Int val lightFont: Boolean @PreviewStyle val mediaPreviewStyle: Int val twidereLinkify: TwidereLinkify val mediaPreviewEnabled: Boolean val nameFirst: Boolean val sensitiveContentEnabled: Boolean val showAccountsColor: Boolean val useStarsForLikes: Boolean val statusClickListener: IStatusViewHolder.StatusClickListener? fun isCardActionsShown(position: Int): Boolean fun showCardActions(position: Int) fun isFullTextVisible(position: Int): Boolean fun setFullTextVisible(position: Int, visible: Boolean) fun setData(data: Data?): Boolean /** * @param raw Count hidden (filtered) item if `true ` */ fun getStatusCount(raw: Boolean = false): Int fun getStatus(position: Int, raw: Boolean = false): ParcelableStatus fun getStatusId(position: Int, raw: Boolean = false): String fun getStatusTimestamp(position: Int, raw: Boolean = false): Long fun getStatusPositionKey(position: Int, raw: Boolean = false): Long fun getAccountKey(position: Int, raw: Boolean = false): UserKey fun findStatusById(accountKey: UserKey, statusId: String): ParcelableStatus? }
gpl-3.0
bbece044c1105105b10234b3dfd953bb
28.694118
80
0.747126
4.327616
false
false
false
false
AndroidX/androidx
buildSrc/private/src/main/kotlin/androidx/build/LintConfiguration.kt
3
10218
/* * Copyright 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 androidx.build import com.android.build.api.dsl.Lint import com.android.build.gradle.internal.lint.AndroidLintAnalysisTask import com.android.build.gradle.internal.lint.AndroidLintTask import java.io.File import java.util.Locale import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.file.RegularFileProperty import org.gradle.api.services.BuildService import org.gradle.api.services.BuildServiceParameters import org.gradle.kotlin.dsl.getByType /** * Name of the service we use to limit the number of concurrent executions of lint */ public const val LINT_SERVICE_NAME = "androidxLintService" // service for limiting the number of concurrent lint tasks interface AndroidXLintService : BuildService<BuildServiceParameters.None> fun Project.configureRootProjectForLint() { // determine many lint tasks to run in parallel val memoryPerTask = 512 * 1024 * 1024 val maxLintMemory = Runtime.getRuntime().maxMemory() * 0.75 // save memory for other things too val maxNumParallelUsages = Math.max(1, (maxLintMemory / memoryPerTask).toInt()) project.gradle.sharedServices.registerIfAbsent( LINT_SERVICE_NAME, AndroidXLintService::class.java ) { spec -> spec.maxParallelUsages.set(maxNumParallelUsages) } } fun Project.configureNonAndroidProjectForLint(extension: AndroidXExtension) { apply(mapOf("plugin" to "com.android.lint")) // Create fake variant tasks since that is what is invoked by developers. val lintTask = tasks.named("lint") tasks.register("lintDebug") { it.dependsOn(lintTask) it.enabled = false } tasks.register("lintAnalyzeDebug") { it.enabled = false } tasks.register("lintRelease") { it.dependsOn(lintTask) it.enabled = false } addToBuildOnServer(lintTask) val lint = extensions.getByType<Lint>() // Support the lint standalone plugin case which, as yet, lacks AndroidComponents finalizeDsl afterEvaluate { configureLint(lint, extension, true) } } fun Project.configureAndroidProjectForLint( lint: Lint, extension: AndroidXExtension, isLibrary: Boolean ) { project.afterEvaluate { // makes sure that the lintDebug task will exist, so we can find it by name setUpLintDebugIfNeeded() } tasks.register("lintAnalyze") { it.enabled = false } configureLint(lint, extension, isLibrary) tasks.named("lint").configure { task -> // We already run lintDebug, we don't need to run lint which lints the release variant task.enabled = false } } private fun Project.setUpLintDebugIfNeeded() { val variants = project.agpVariants val variantNames = variants.map { v -> v.name } if (!variantNames.contains("debug")) { tasks.register("lintDebug") { for (variantName in variantNames) { if (variantName.lowercase(Locale.US).contains("debug")) { it.dependsOn( tasks.named( "lint${variantName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.US) else it.toString() }}" ) ) } } } } } fun Project.configureLint(lint: Lint, extension: AndroidXExtension, isLibrary: Boolean) { val lintChecksProject = project.rootProject.findProject(":lint-checks") ?: if (allowMissingLintProject()) { return } else { throw GradleException("Project :lint-checks does not exist") } project.dependencies.add("lintChecks", lintChecksProject) // The purpose of this specific project is to test that lint is running, so // it contains expected violations that we do not want to trigger a build failure val isTestingLintItself = (project.path == ":lint-checks:integration-tests") lint.apply { // Skip lintVital tasks on assemble. We explicitly run lintRelease for libraries. checkReleaseBuilds = false } tasks.withType(AndroidLintAnalysisTask::class.java).configureEach { task -> // don't run too many copies of lint at once due to memory limitations task.usesService( task.project.gradle.sharedServices.registrations.getByName(LINT_SERVICE_NAME).service ) } tasks.withType(AndroidLintTask::class.java).configureEach { task -> // Remove the lint and column attributes from generated lint baseline XML. if (task.name.startsWith("updateLintBaseline")) { task.doLast { task.outputs.files.find { it.name == "lint-baseline.xml" }?.let { file -> if (file.exists()) { file.writeText(removeLineAndColumnAttributes(file.readText())) } } } } } // Lint is configured entirely in finalizeDsl so that individual projects cannot easily // disable individual checks in the DSL for any reason. lint.apply { if (!isTestingLintItself) { abortOnError = true } ignoreWarnings = true // Run lint on tests. Uses top-level lint.xml to specify checks. checkTestSources = true // Write output directly to the console (and nowhere else). textReport = true htmlReport = false // Format output for convenience. explainIssues = true noLines = false quiet = true // We run lint on each library, so we don't want transitive checking of each dependency checkDependencies = false if (extension.type.allowCallingVisibleForTestsApis) { // Test libraries are allowed to call @VisibleForTests code disable.add("VisibleForTests") } else { fatal.add("VisibleForTests") } // Reenable after b/238892319 is resolved disable.add("NotificationPermission") // Disable dependency checks that suggest to change them. We want libraries to be // intentional with their dependency version bumps. disable.add("KtxExtensionAvailable") disable.add("GradleDependency") // Disable a check that's only relevant for real apps. For our test apps we're not // concerned with drawables potentially being a little bit blurry disable.add("IconMissingDensityFolder") // Disable until it works for our projects, b/171986505 disable.add("JavaPluginLanguageLevel") // Explicitly disable StopShip check (see b/244617216) disable.add("StopShip") // Broken in 7.0.0-alpha15 due to b/180408990 disable.add("RestrictedApi") // Provide stricter enforcement for project types intended to run on a device. if (extension.type.compilationTarget == CompilationTarget.DEVICE) { fatal.add("Assert") fatal.add("NewApi") fatal.add("ObsoleteSdkInt") fatal.add("NoHardKeywords") fatal.add("UnusedResources") fatal.add("KotlinPropertyAccess") fatal.add("LambdaLast") fatal.add("UnknownNullness") // Only override if not set explicitly. // Some Kotlin projects may wish to disable this. if ( isLibrary && !disable.contains("SyntheticAccessor") && extension.type != LibraryType.SAMPLES ) { fatal.add("SyntheticAccessor") } // Only check for missing translations in finalized (beta and later) modules. if (extension.mavenVersion?.isFinalApi() == true) { fatal.add("MissingTranslation") } else { disable.add("MissingTranslation") } } else { disable.add("BanUncheckedReflection") } // Broken in 7.0.0-alpha15 due to b/187343720 disable.add("UnusedResources") // Disable NullAnnotationGroup check for :compose:ui:ui-text (b/233788571) if (isLibrary && project.group == "androidx.compose.ui" && project.name == "ui-text") { disable.add("NullAnnotationGroup") } if (extension.type == LibraryType.SAMPLES) { // TODO: b/190833328 remove if / when AGP will analyze dependencies by default // This is needed because SampledAnnotationDetector uses partial analysis, and // hence requires dependencies to be analyzed. checkDependencies = true } // Only run certain checks where API tracking is important. if (extension.type.checkApi is RunApiTasks.No) { disable.add("IllegalExperimentalApiUsage") } // If the project has not overridden the lint config, set the default one. if (lintConfig == null) { val lintXmlPath = if (extension.type == LibraryType.SAMPLES) { "buildSrc/lint_samples.xml" } else { "buildSrc/lint.xml" } // suppress warnings more specifically than issue-wide severity (regexes) // Currently suppresses warnings from baseline files working as intended lintConfig = File(project.getSupportRootFolder(), lintXmlPath) } baseline = lintBaseline.get().asFile } } val Project.lintBaseline: RegularFileProperty get() = project.objects.fileProperty().fileValue(File(projectDir, "/lint-baseline.xml"))
apache-2.0
c572477295cc85705c3b85a7205a40e6
36.428571
99
0.641613
4.665753
false
false
false
false
AndroidX/androidx
activity/activity/src/main/java/androidx/activity/ComponentDialog.kt
3
3518
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.activity import android.app.Dialog import android.content.Context import android.os.Build import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.annotation.StyleRes import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.ViewTreeLifecycleOwner /** * Base class for dialogs that enables composition of higher level components. */ open class ComponentDialog @JvmOverloads constructor( context: Context, @StyleRes themeResId: Int = 0 ) : Dialog(context, themeResId), LifecycleOwner, OnBackPressedDispatcherOwner { private var _lifecycleRegistry: LifecycleRegistry? = null private val lifecycleRegistry: LifecycleRegistry get() = _lifecycleRegistry ?: LifecycleRegistry(this).also { _lifecycleRegistry = it } final override fun getLifecycle(): Lifecycle = lifecycleRegistry @Suppress("ClassVerificationFailure") // needed for onBackInvokedDispatcher call @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= 33) { onBackPressedDispatcher.setOnBackInvokedDispatcher(onBackInvokedDispatcher) } lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) } @CallSuper override fun onStart() { super.onStart() lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) } @CallSuper override fun onStop() { // This is the closest thing to onDestroy that a Dialog has lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) _lifecycleRegistry = null super.onStop() } @Suppress("DEPRECATION") private val onBackPressedDispatcher = OnBackPressedDispatcher { super.onBackPressed() } final override fun getOnBackPressedDispatcher() = onBackPressedDispatcher @CallSuper override fun onBackPressed() { onBackPressedDispatcher.onBackPressed() } override fun setContentView(layoutResID: Int) { initViewTreeOwners() super.setContentView(layoutResID) } override fun setContentView(view: View) { initViewTreeOwners() super.setContentView(view) } override fun setContentView(view: View, params: ViewGroup.LayoutParams?) { initViewTreeOwners() super.setContentView(view, params) } override fun addContentView(view: View, params: ViewGroup.LayoutParams?) { initViewTreeOwners() super.addContentView(view, params) } private fun initViewTreeOwners() { ViewTreeLifecycleOwner.set(window!!.decorView, this) window!!.decorView.setViewTreeOnBackPressedDispatcherOwner(this) } }
apache-2.0
a43dc5efde2d3e424deec0324af0cfd8
30.990909
87
0.726265
5.113372
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/crypto/CryptoModule.kt
2
1392
package abi44_0_0.expo.modules.crypto import android.content.Context import android.util.Base64 import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import java.security.MessageDigest import java.security.NoSuchAlgorithmException class CryptoModule(context: Context) : ExportedModule(context) { override fun getName() = "ExpoCrypto" @ExpoMethod fun digestStringAsync(algorithm: String, data: String, options: Map<String, Any?>, promise: Promise) { val encoding = options["encoding"] as String? val messageDigest = try { MessageDigest.getInstance(algorithm).apply { update(data.toByteArray()) } } catch (e: NoSuchAlgorithmException) { promise.reject("ERR_CRYPTO_DIGEST", e) return } val digest: ByteArray = messageDigest.digest() when (encoding) { "base64" -> { val output = Base64.encodeToString(digest, Base64.NO_WRAP) promise.resolve(output) } "hex" -> { val output = digest.joinToString(separator = "") { byte -> ((byte.toInt() and 0xff) + 0x100) .toString(radix = 16) .substring(startIndex = 1) } promise.resolve(output) } else -> { promise.reject("ERR_CRYPTO_DIGEST", "Invalid encoding type provided.") } } } }
bsd-3-clause
b32239f79b9b025e09b55d9827c803fa
29.26087
104
0.663793
3.954545
false
false
false
false
Gh0u1L5/WechatMagician
app/src/main/kotlin/com/gh0u1l5/wechatmagician/util/ImageUtil.kt
1
3144
package com.gh0u1l5.wechatmagician.util import android.graphics.Bitmap import android.os.Environment import android.os.Environment.MEDIA_MOUNTED import com.gh0u1l5.wechatmagician.spellbook.WechatGlobal.ImgStorageObject import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.Fields.ImgInfoStorage_mBitmapCache import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.Methods.ImgInfoStorage_load import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.Methods.LruCacheWithListener_put import com.gh0u1l5.wechatmagician.spellbook.util.FileUtil import com.gh0u1l5.wechatmagician.spellbook.util.FileUtil.createTimeTag import de.robv.android.xposed.XposedHelpers.callMethod // ImageUtil is a helper object for processing thumbnails. object ImageUtil { // blockTable records all the thumbnail files changed by ImageUtil // In WechatHook.hookImageStorage, the module hooks FileOutputStream // to prevent anyone from overwriting these files. @Volatile var blockTable: Set<String> = setOf() // getPathFromImgId maps the given imgId to corresponding absolute path. private fun getPathFromImgId(imgId: String): String? { val storage = ImgStorageObject ?: return null return ImgInfoStorage_load.invoke(storage, imgId, "th_", "", false) as? String } // replaceThumbDiskCache replaces the disk cache of a specific // thumbnail with the given bitmap. private fun replaceThumbDiskCache(path: String, bitmap: Bitmap) { try { FileUtil.writeBitmapToDisk(path, bitmap) } catch (_: Throwable) { return } // Update block table after successful write. synchronized(blockTable) { blockTable += path } } // replaceThumbMemoryCache replaces the memory cache of a specific // thumbnail with the given bitmap. private fun replaceThumbMemoryCache(path: String, bitmap: Bitmap) { // Check if memory cache and image storage are established val storage = ImgStorageObject ?: return val cache = ImgInfoStorage_mBitmapCache.get(storage) // Update memory cache callMethod(cache, "remove", path) callMethod(cache, LruCacheWithListener_put.name, "${path}hd", bitmap) // Notify storage update callMethod(storage, "doNotify") } // replaceThumbnail replaces the memory cache and disk cache of a // specific thumbnail with the given bitmap. fun replaceThumbnail(imgId: String, bitmap: Bitmap) { val path = getPathFromImgId(imgId) ?: return replaceThumbDiskCache("${path}hd", bitmap) replaceThumbMemoryCache(path, bitmap) } // createScreenshotPath generates a path for saving the new screenshot fun createScreenshotPath(): String { val state = Environment.getExternalStorageState() if (state != MEDIA_MOUNTED) { throw Error("SD card is not presented! (state: $state)") } val storage = Environment.getExternalStorageDirectory().absolutePath + "/WechatMagician" return "$storage/screenshot/SNS-${createTimeTag()}.jpg" } }
gpl-3.0
c717220487a0bae29f9ea47311e66703
41.5
100
0.718193
4.421941
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/RsDropRefInspectionTest.kt
4
3846
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor /** * Tests for Drop Reference inspection. */ @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) class RsDropRefInspectionTest : RsInspectionsTestBase(RsDropRefInspection::class) { fun testDropRefSimple() = checkByText(""" fn main() { let val1 = Box::new(10); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(&val1)</warning>; } """) fun testDropRefFullPath() = checkByText(""" fn main() { let val1 = Box::new(20); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">std::mem::drop(&val1)</warning>; } """) fun testDropRefAliased() = checkByText(""" use std::mem::drop as free; fn main() { let val1 = Box::new(30); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">free(&val1)</warning>; } """) fun testDropRefRefType() = checkByText(""" fn foo() {} fn main() { let val = &foo(); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(val)</warning>; } """) fun testDropRefShadowed() = checkByText(""" fn drop(val: &Box<u32>) {} fn main() { let val = Box::new(84); drop(&val); // This must not be highlighted } """) fun testDropManuallyDrop() = checkByText(""" use std::mem::ManuallyDrop; fn main() { let mut drop = ManuallyDrop::new("nodrop"); unsafe { ManuallyDrop::drop(&mut drop); // This must not be highlighted } } """) fun testDropRefMethodCall() = checkByText(""" struct Foo; impl Foo { pub fn drop(&self, val: &Foo) {} } fn main() { let f = Foo; f.drop(&f); // This must not be highlighted } """) fun testDropRefFix() = checkFixByText("Remove &", """ fn main() { let val1 = Box::new(40); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(&va<caret>l1)</warning>; } """, """ fn main() { let val1 = Box::new(40); drop(val1); } """) fun testDropRefFix2() = checkFixByText("Remove &", """ fn main() { let val1 = Box::new(40); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(& va<caret>l1)</warning>; } """, """ fn main() { let val1 = Box::new(40); drop(val1); } """) fun testRefMutDropFix() = checkFixByText("Remove &mut", """ fn main() { let val1 = Box::new(40); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(&mut<caret> val1)</warning>; } """, """ fn main() { let val1 = Box::new(40); drop(val1); } """) fun testRefMutDropFix2() = checkFixByText("Remove &mut", """ fn main() { let val1 = Box::new(40); <warning descr="Call to std::mem::drop with a reference argument. Dropping a reference does nothing">drop(& mut<caret> val1)</warning>; } """, """ fn main() { let val1 = Box::new(40); drop(val1); } """) }
mit
d8882f11fc6dcc5cf15b2d673da8b283
30.268293
149
0.536921
4.162338
false
true
false
false
HughG/yested
src/main/docsite/bootstrap/dialogs.kt
2
2369
package bootstrap import net.yested.bootstrap.row import net.yested.bootstrap.pageHeader import net.yested.div import net.yested.Div import net.yested.ButtonType import net.yested.bootstrap.Dialog import net.yested.bootstrap.ButtonLook import net.yested.with import net.yested.bootstrap.btsForm import net.yested.bootstrap.btsButton import net.yested.bootstrap.Medium import net.yested.bootstrap.DialogSize import net.yested.bootstrap.StringInputField fun createDialogs(id: String): Div { val dialog = Dialog(size = DialogSize.SMALL) dialog with { header { + "This is dialog with text input" } body { btsForm { item(forId = "nameId", label = { + "Name" }) { +(StringInputField(placeholder = "Name") with { this.id = "nameId" }) } } } footer { btsButton( type = ButtonType.SUBMIT, look = ButtonLook.PRIMARY, label = { +"Submit"}, onclick = { dialog.close() }) } } return div { this.id = id row { col(Medium(12)) { pageHeader { h3 { +"Dialogs" } } } } row { col(Medium(4)) { div { +"""This is a wrapper around Bootstrap dialogs.""" } h4 { +"Demo" } div { btsButton(label = { +"Open dialog" }, onclick = { dialog.open() }) } } col(Medium(8)) { h4 { +"Code" } code(lang = "kotlin", content="""val dialog = Dialog(size = DialogSize.SMALL) dialog with { header { + "This is dialog with text input" } body { btsForm { item(forId = "nameId", label = { + "Name" }) { textInput(placeholder = "Name") { id = "nameId"} } } } footer { btsButton( type = ButtonType.SUBMIT, look = ButtonLook.PRIMARY, label = { +"Submit"}, onclick = { dialog.close() }) } } //somewhere in a dom tree: div { btsButton(label = { +"Open dialog" }, onclick = { dialog.open() }) }""") } } } }
mit
df4463e55c9ff2f6326e26f4195198a1
25.333333
93
0.479949
4.322993
false
false
false
false
androidx/androidx
text/text/src/main/java/androidx/compose/ui/text/android/StaticLayoutFactory.kt
3
13105
/* * Copyright 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 androidx.compose.ui.text.android import android.graphics.text.LineBreakConfig import android.os.Build import android.text.Layout.Alignment import android.text.StaticLayout import android.text.StaticLayout.Builder import android.text.TextDirectionHeuristic import android.text.TextPaint import android.text.TextUtils.TruncateAt import android.util.Log import androidx.annotation.DoNotInline import androidx.annotation.FloatRange import androidx.annotation.IntRange import androidx.annotation.RequiresApi import androidx.compose.ui.text.android.LayoutCompat.BreakStrategy import androidx.compose.ui.text.android.LayoutCompat.HyphenationFrequency import androidx.compose.ui.text.android.LayoutCompat.JustificationMode import androidx.compose.ui.text.android.LayoutCompat.LineBreakStyle import androidx.compose.ui.text.android.LayoutCompat.LineBreakWordStyle import androidx.core.os.BuildCompat import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException private const val TAG = "StaticLayoutFactory" @OptIn(InternalPlatformTextApi::class) internal object StaticLayoutFactory { private val delegate: StaticLayoutFactoryImpl = if (Build.VERSION.SDK_INT >= 23) { StaticLayoutFactory23() } else { StaticLayoutFactoryDefault() } /** * Builder class for StaticLayout. */ fun create( text: CharSequence, start: Int = 0, end: Int = text.length, paint: TextPaint, width: Int, textDir: TextDirectionHeuristic = LayoutCompat.DEFAULT_TEXT_DIRECTION_HEURISTIC, alignment: Alignment = LayoutCompat.DEFAULT_LAYOUT_ALIGNMENT, @IntRange(from = 0) maxLines: Int = LayoutCompat.DEFAULT_MAX_LINES, ellipsize: TruncateAt? = null, @IntRange(from = 0) ellipsizedWidth: Int = width, @FloatRange(from = 0.0) lineSpacingMultiplier: Float = LayoutCompat.DEFAULT_LINESPACING_MULTIPLIER, lineSpacingExtra: Float = LayoutCompat.DEFAULT_LINESPACING_EXTRA, @JustificationMode justificationMode: Int = LayoutCompat.DEFAULT_JUSTIFICATION_MODE, includePadding: Boolean = LayoutCompat.DEFAULT_INCLUDE_PADDING, useFallbackLineSpacing: Boolean = LayoutCompat.DEFAULT_FALLBACK_LINE_SPACING, @BreakStrategy breakStrategy: Int = LayoutCompat.DEFAULT_BREAK_STRATEGY, @LineBreakStyle lineBreakStyle: Int = LayoutCompat.DEFAULT_LINE_BREAK_STYLE, @LineBreakWordStyle lineBreakWordStyle: Int = LayoutCompat.DEFAULT_LINE_BREAK_WORD_STYLE, @HyphenationFrequency hyphenationFrequency: Int = LayoutCompat.DEFAULT_HYPHENATION_FREQUENCY, leftIndents: IntArray? = null, rightIndents: IntArray? = null ): StaticLayout { return delegate.create( StaticLayoutParams( text = text, start = start, end = end, paint = paint, width = width, textDir = textDir, alignment = alignment, maxLines = maxLines, ellipsize = ellipsize, ellipsizedWidth = ellipsizedWidth, lineSpacingMultiplier = lineSpacingMultiplier, lineSpacingExtra = lineSpacingExtra, justificationMode = justificationMode, includePadding = includePadding, useFallbackLineSpacing = useFallbackLineSpacing, breakStrategy = breakStrategy, lineBreakStyle = lineBreakStyle, lineBreakWordStyle = lineBreakWordStyle, hyphenationFrequency = hyphenationFrequency, leftIndents = leftIndents, rightIndents = rightIndents ) ) } /** * Returns whether fallbackLineSpacing is enabled for the given layout. * * @param layout StaticLayout instance * @param useFallbackLineSpacing fallbackLineSpacing configuration passed while creating the * StaticLayout. */ fun isFallbackLineSpacingEnabled( layout: StaticLayout, useFallbackLineSpacing: Boolean ): Boolean { return delegate.isFallbackLineSpacingEnabled(layout, useFallbackLineSpacing) } } @OptIn(InternalPlatformTextApi::class) private class StaticLayoutParams constructor( val text: CharSequence, val start: Int = 0, val end: Int, val paint: TextPaint, val width: Int, val textDir: TextDirectionHeuristic, val alignment: Alignment, val maxLines: Int, val ellipsize: TruncateAt?, val ellipsizedWidth: Int, val lineSpacingMultiplier: Float, val lineSpacingExtra: Float, val justificationMode: Int, val includePadding: Boolean, val useFallbackLineSpacing: Boolean, val breakStrategy: Int, val lineBreakStyle: Int, val lineBreakWordStyle: Int, val hyphenationFrequency: Int, val leftIndents: IntArray?, val rightIndents: IntArray? ) { init { require(start in 0..end) require(end in 0..text.length) require(maxLines >= 0) require(width >= 0) require(ellipsizedWidth >= 0) require(lineSpacingMultiplier >= 0f) } } private interface StaticLayoutFactoryImpl { @DoNotInline // API level specific, do not inline to prevent ART class verification breakages fun create(params: StaticLayoutParams): StaticLayout fun isFallbackLineSpacingEnabled(layout: StaticLayout, useFallbackLineSpacing: Boolean): Boolean } @RequiresApi(23) private class StaticLayoutFactory23 : StaticLayoutFactoryImpl { @DoNotInline override fun create(params: StaticLayoutParams): StaticLayout { return Builder.obtain(params.text, params.start, params.end, params.paint, params.width) .apply { setTextDirection(params.textDir) setAlignment(params.alignment) setMaxLines(params.maxLines) setEllipsize(params.ellipsize) setEllipsizedWidth(params.ellipsizedWidth) setLineSpacing(params.lineSpacingExtra, params.lineSpacingMultiplier) setIncludePad(params.includePadding) setBreakStrategy(params.breakStrategy) setHyphenationFrequency(params.hyphenationFrequency) setIndents(params.leftIndents, params.rightIndents) if (Build.VERSION.SDK_INT >= 26) { StaticLayoutFactory26.setJustificationMode(this, params.justificationMode) } if (Build.VERSION.SDK_INT >= 28) { StaticLayoutFactory28.setUseLineSpacingFromFallbacks( this, params.useFallbackLineSpacing ) } if (Build.VERSION.SDK_INT >= 33) { StaticLayoutFactory33.setLineBreakConfig( this, params.lineBreakStyle, params.lineBreakWordStyle ) } }.build() } @androidx.annotation.OptIn(markerClass = [BuildCompat.PrereleaseSdkCheck::class]) override fun isFallbackLineSpacingEnabled( layout: StaticLayout, useFallbackLineSpacing: Boolean ): Boolean { return if (BuildCompat.isAtLeastT()) { StaticLayoutFactory33.isFallbackLineSpacingEnabled(layout) } else if (Build.VERSION.SDK_INT >= 28) { useFallbackLineSpacing } else { false } } } @RequiresApi(26) private object StaticLayoutFactory26 { @JvmStatic @DoNotInline fun setJustificationMode(builder: Builder, justificationMode: Int) { builder.setJustificationMode(justificationMode) } } @RequiresApi(28) private object StaticLayoutFactory28 { @JvmStatic @DoNotInline fun setUseLineSpacingFromFallbacks(builder: Builder, useFallbackLineSpacing: Boolean) { builder.setUseLineSpacingFromFallbacks(useFallbackLineSpacing) } } @RequiresApi(33) private object StaticLayoutFactory33 { @JvmStatic @DoNotInline fun isFallbackLineSpacingEnabled(layout: StaticLayout): Boolean { return layout.isFallbackLineSpacingEnabled } @JvmStatic @DoNotInline fun setLineBreakConfig(builder: Builder, lineBreakStyle: Int, lineBreakWordStyle: Int) { val lineBreakConfig = LineBreakConfig.Builder() .setLineBreakStyle(lineBreakStyle) .setLineBreakWordStyle(lineBreakWordStyle) .build() builder.setLineBreakConfig(lineBreakConfig) } } private class StaticLayoutFactoryDefault : StaticLayoutFactoryImpl { companion object { private var isInitialized = false private var staticLayoutConstructor: Constructor<StaticLayout>? = null private fun getStaticLayoutConstructor(): Constructor<StaticLayout>? { if (isInitialized) return staticLayoutConstructor isInitialized = true try { staticLayoutConstructor = StaticLayout::class.java.getConstructor( CharSequence::class.java, Int::class.javaPrimitiveType, /* start */ Int::class.javaPrimitiveType, /* end */ TextPaint::class.java, Int::class.javaPrimitiveType, /* width */ Alignment::class.java, TextDirectionHeuristic::class.java, Float::class.javaPrimitiveType, /* lineSpacingMultiplier */ Float::class.javaPrimitiveType, /* lineSpacingExtra */ Boolean::class.javaPrimitiveType, /* includePadding */ TruncateAt::class.java, Int::class.javaPrimitiveType, /* ellipsizeWidth */ Int::class.javaPrimitiveType /* maxLines */ ) } catch (e: NoSuchMethodException) { staticLayoutConstructor = null Log.e(TAG, "unable to collect necessary constructor.") } return staticLayoutConstructor } } @DoNotInline override fun create(params: StaticLayoutParams): StaticLayout { // On API 21 to 23, try to call the StaticLayoutConstructor which supports the // textDir and maxLines. val result = getStaticLayoutConstructor()?.let { try { it.newInstance( params.text, params.start, params.end, params.paint, params.width, params.alignment, params.textDir, params.lineSpacingMultiplier, params.lineSpacingExtra, params.includePadding, params.ellipsize, params.ellipsizedWidth, params.maxLines ) } catch (e: IllegalAccessException) { staticLayoutConstructor = null Log.e(TAG, "unable to call constructor") null } catch (e: InstantiationException) { staticLayoutConstructor = null Log.e(TAG, "unable to call constructor") null } catch (e: InvocationTargetException) { staticLayoutConstructor = null Log.e(TAG, "unable to call constructor") null } } if (result != null) return result // On API 21 to 23 where it failed to find StaticLayout.Builder, create with // deprecated constructor, textDir and maxLines won't work in this case. @Suppress("DEPRECATION") return StaticLayout( params.text, params.start, params.end, params.paint, params.width, params.alignment, params.lineSpacingMultiplier, params.lineSpacingExtra, params.includePadding, params.ellipsize, params.ellipsizedWidth ) } override fun isFallbackLineSpacingEnabled( layout: StaticLayout, useFallbackLineSpacing: Boolean ): Boolean { return false } }
apache-2.0
e12515be96c2c4a050c78519a5c1ecd9
35.915493
100
0.631362
5.121141
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/http/ConnectivityInterceptor.kt
1
1179
package me.proxer.app.util.http import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Build import android.provider.Settings import androidx.core.content.getSystemService import me.proxer.app.exception.NotConnectedException import me.proxer.app.util.compat.isConnected import okhttp3.Interceptor import okhttp3.Response import org.koin.core.KoinComponent /** * @author Ruben Gees */ class ConnectivityInterceptor(context: Context) : Interceptor, KoinComponent { private val connectivityManager = requireNotNull(context.getSystemService<ConnectivityManager>()) private val hasConnectionSettings = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY).resolveActivity(context.packageManager) != null || Intent(Settings.ACTION_WIRELESS_SETTINGS).resolveActivity(context.packageManager) != null override fun intercept(chain: Interceptor.Chain): Response { if (hasConnectionSettings && !connectivityManager.isConnected) { throw NotConnectedException() } return chain.proceed(chain.request()) } }
gpl-3.0
331a5a2ed5e4537abc7d3329222bfa89
34.727273
110
0.77693
4.697211
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/fabric/EntryPoint.kt
1
2084
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.fabric import com.demonwav.mcdev.creator.isValidClassName import com.intellij.openapi.project.Project import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.search.GlobalSearchScope data class EntryPoint( val category: String, val type: Type, val className: String, val interfaceName: String, val methodName: String? = null ) { private val dumbReference = when (type) { Type.CLASS -> className Type.METHOD -> "$className::$methodName" } val valid by lazy { category.isNotBlank() && isValidClassName(className) && isValidClassName(interfaceName) } fun computeReference(project: Project): String { if (type != Type.METHOD || methodName != null) { return dumbReference } return "$className::${findFunctionalMethod(project)?.name}" } fun findFunctionalMethod(project: Project): PsiMethod? { val classFinder = JavaPsiFacade.getInstance(project) val clazz = classFinder.findClass(className, GlobalSearchScope.projectScope(project)) ?: return null val interfaceClass = classFinder.findClass(interfaceName, clazz.resolveScope) ?: return null if (!interfaceClass.isInterface) { return null } val candidates = interfaceClass.allMethods .filter { !it.hasModifierProperty(PsiModifier.STATIC) && !it.hasModifierProperty(PsiModifier.DEFAULT) && it.containingClass?.qualifiedName != CommonClassNames.JAVA_LANG_OBJECT } return if (candidates.size == 1) { candidates[0] } else { null } } override fun toString() = "$category -> $dumbReference implements $interfaceName" enum class Type { CLASS, METHOD } }
mit
c7e159bdbcf66fc4835fa8fa46336886
30.104478
113
0.660269
4.768879
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/debugger/emmy/Transporter.kt
2
8651
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.debugger.emmy import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.SystemInfoRt import com.tang.intellij.lua.debugger.DebugLogger import com.tang.intellij.lua.debugger.LogConsoleType import org.scalasbt.ipcsocket.UnixDomainServerSocket import org.scalasbt.ipcsocket.UnixDomainSocket import org.scalasbt.ipcsocket.Win32NamedPipeServerSocket import org.scalasbt.ipcsocket.Win32NamedPipeSocket import java.io.* import java.net.InetAddress import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import java.nio.ByteBuffer import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel import java.util.concurrent.LinkedBlockingQueue class StopSign : Message(MessageCMD.Unknown) interface ITransportHandler { fun onReceiveMessage(cmd: MessageCMD, json: String) fun onDisconnect() fun onConnect(suc: Boolean) } abstract class Transporter { var handler: ITransportHandler? = null var logger: DebugLogger? = null protected val messageQueue = LinkedBlockingQueue<IMessage>() protected var stopped = false open fun start() { } open fun close() { stopped = true } fun send(msg: IMessage) { messageQueue.put(msg) } protected fun onConnect(suc: Boolean) { handler?.onConnect(suc) if (suc) { logger?.println("Connected.", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) } } protected open fun onDisconnect() { logger?.println("Disconnected.", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) } protected fun onReceiveMessage(type: MessageCMD, json: String) { try { handler?.onReceiveMessage(type, json) } catch (e: Exception) { println(e) } } } abstract class SocketChannelTransporter : Transporter() { protected var socket: SocketChannel? = null protected fun run() { ApplicationManager.getApplication().executeOnPooledThread { doReceive() } ApplicationManager.getApplication().executeOnPooledThread { doSend() } } protected open fun getInputStream(): InputStream? { return socket?.socket()?.getInputStream() } protected open fun write(ba: ByteArray) { socket?.write(ByteBuffer.wrap(ba)) } private fun doReceive() { val iss = getInputStream() ?: return val reader = BufferedReader(InputStreamReader(iss, "UTF-8")) while (true) { try { val cmdValue = reader.readLine() val cmd = cmdValue.toInt() val json = reader.readLine() val type = MessageCMD.values().find { it.ordinal == cmd } onReceiveMessage(type ?: MessageCMD.Unknown, json) } catch (e: Exception) { onDisconnect() break } } send(StopSign()) println(">>> stop receive") } private fun doSend() { while(true) { val msg = messageQueue.take() if (msg is StopSign) break try { val json = msg.toJSON() write("${msg.cmd}\n$json\n".toByteArray()) } catch (e: IOException) { break } } println(">>> stop send") } override fun close() { super.close() socket?.close() socket = null } override fun onDisconnect() { super.onDisconnect() socket = null } } class SocketClientTransporter(val host: String, val port: Int) : SocketChannelTransporter() { private var server: SocketChannel? = null override fun start() { logger?.println("Try connect $host:$port ...", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) val server = SocketChannel.open() val address = InetAddress.getByName(host) var connected = false if (server.connect(InetSocketAddress(address,port))) { this.server = server this.socket = server run() connected = true } onConnect(connected) } override fun onDisconnect() { super.onDisconnect() handler?.onDisconnect() } } class SocketServerTransporter(val host: String, val port: Int) : SocketChannelTransporter() { private var server = ServerSocketChannel.open() override fun start() { server.bind(InetSocketAddress(InetAddress.getByName(host), port)) logger?.println("Server($host:$port) open successfully, wait for connection...", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) ApplicationManager.getApplication().executeOnPooledThread { while (!stopped) { val channel = try { server.accept() } catch (e: Exception) { continue } if (socket != null) { try { channel.close() } catch (e: Exception) { e.printStackTrace() } } else { socket = channel run() onConnect(true) } } } } override fun close() { super.close() server.close() } } private fun getPipename(name: String): String { return if (SystemInfoRt.isWindows) { """\\.\pipe\emmylua-$name""" } else { val tmpdir = System.getProperty("java.io.tmpdir") "$tmpdir$name" } } class PipelineClientTransporter(val name: String) : SocketChannelTransporter() { private var pipe: Socket? = null override fun start() { pipe = if (SystemInfoRt.isWindows) { Win32NamedPipeSocket(getPipename(name)) } else { UnixDomainSocket(getPipename(name)) } logger?.println("Pipeline($name) connect successfully.", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) run() onConnect(true) } override fun getInputStream(): InputStream? { return pipe?.getInputStream() } override fun write(ba: ByteArray) { pipe?.getOutputStream()?.write(ba) } override fun close() { super.close() pipe?.close() } override fun onDisconnect() { super.onDisconnect() handler?.onDisconnect() } } class PipelineServerTransporter(val name: String) : SocketChannelTransporter() { private var pipe: ServerSocket? = null private var client: Socket? = null override fun start() { val pipeName = getPipename(name) pipe = if (SystemInfoRt.isWindows) { Win32NamedPipeServerSocket(pipeName) } else { val f = File(pipeName) if (f.exists()) { f.delete() } UnixDomainServerSocket(pipeName) } logger?.println("Pipeline($name) open successfully, wait for connection...", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT) ApplicationManager.getApplication().executeOnPooledThread { try { client = pipe?.accept() run() onConnect(true) } catch (e: Exception) { println(e) logger?.println(e.message ?: "Unknown error.", LogConsoleType.NORMAL, ConsoleViewContentType.ERROR_OUTPUT) } } } override fun getInputStream(): InputStream? { return client?.getInputStream() } override fun write(ba: ByteArray) { client?.getOutputStream()?.write(ba) } override fun close() { super.close() client?.close() client = null pipe?.close() pipe = null } }
apache-2.0
07c96ebc205fedf952875d4e377d7df4
28.030201
149
0.602936
4.769019
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/prettyCards/PrettyCardsService.kt
1
5816
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.prettyCards import com.google.gson.reflect.TypeToken import com.vk.api.sdk.requests.VKRequest import com.vk.sdk.api.GsonHolder import com.vk.sdk.api.NewApiRequest import com.vk.sdk.api.prettyCards.dto.PrettyCardsCreateResponse import com.vk.sdk.api.prettyCards.dto.PrettyCardsDeleteResponse import com.vk.sdk.api.prettyCards.dto.PrettyCardsEditResponse import com.vk.sdk.api.prettyCards.dto.PrettyCardsGetResponse import com.vk.sdk.api.prettyCards.dto.PrettyCardsPrettyCardOrError import kotlin.Int import kotlin.String import kotlin.collections.List class PrettyCardsService { /** * @param ownerId * @param photo * @param title * @param link * @param price * @param priceOld * @param button * @return [VKRequest] with [PrettyCardsCreateResponse] */ fun prettyCardsCreate( ownerId: Int, photo: String, title: String, link: String, price: String? = null, priceOld: String? = null, button: String? = null ): VKRequest<PrettyCardsCreateResponse> = NewApiRequest("prettyCards.create") { GsonHolder.gson.fromJson(it, PrettyCardsCreateResponse::class.java) } .apply { addParam("owner_id", ownerId) addParam("photo", photo) addParam("title", title) addParam("link", link, maxLength = 2000) price?.let { addParam("price", it, maxLength = 20) } priceOld?.let { addParam("price_old", it, maxLength = 20) } button?.let { addParam("button", it, maxLength = 255) } } /** * @param ownerId * @param cardId * @return [VKRequest] with [PrettyCardsDeleteResponse] */ fun prettyCardsDelete(ownerId: Int, cardId: Int): VKRequest<PrettyCardsDeleteResponse> = NewApiRequest("prettyCards.delete") { GsonHolder.gson.fromJson(it, PrettyCardsDeleteResponse::class.java) } .apply { addParam("owner_id", ownerId) addParam("card_id", cardId) } /** * @param ownerId * @param cardId * @param photo * @param title * @param link * @param price * @param priceOld * @param button * @return [VKRequest] with [PrettyCardsEditResponse] */ fun prettyCardsEdit( ownerId: Int, cardId: Int, photo: String? = null, title: String? = null, link: String? = null, price: String? = null, priceOld: String? = null, button: String? = null ): VKRequest<PrettyCardsEditResponse> = NewApiRequest("prettyCards.edit") { GsonHolder.gson.fromJson(it, PrettyCardsEditResponse::class.java) } .apply { addParam("owner_id", ownerId) addParam("card_id", cardId) photo?.let { addParam("photo", it) } title?.let { addParam("title", it) } link?.let { addParam("link", it, maxLength = 2000) } price?.let { addParam("price", it, maxLength = 20) } priceOld?.let { addParam("price_old", it, maxLength = 20) } button?.let { addParam("button", it, maxLength = 255) } } /** * @param ownerId * @param offset * @param count * @return [VKRequest] with [PrettyCardsGetResponse] */ fun prettyCardsGet( ownerId: Int, offset: Int? = null, count: Int? = null ): VKRequest<PrettyCardsGetResponse> = NewApiRequest("prettyCards.get") { GsonHolder.gson.fromJson(it, PrettyCardsGetResponse::class.java) } .apply { addParam("owner_id", ownerId) offset?.let { addParam("offset", it, min = 0) } count?.let { addParam("count", it, min = 0, max = 100) } } /** * @param ownerId * @param cardIds * @return [VKRequest] with [Unit] */ fun prettyCardsGetById(ownerId: Int, cardIds: List<Int>): VKRequest<List<PrettyCardsPrettyCardOrError>> = NewApiRequest("prettyCards.getById") { val typeToken = object: TypeToken<List<PrettyCardsPrettyCardOrError>>() {}.type GsonHolder.gson.fromJson<List<PrettyCardsPrettyCardOrError>>(it, typeToken) } .apply { addParam("owner_id", ownerId) addParam("card_ids", cardIds) } /** * @return [VKRequest] with [String] */ fun prettyCardsGetUploadURL(): VKRequest<String> = NewApiRequest("prettyCards.getUploadURL") { GsonHolder.gson.fromJson(it, String::class.java) } }
mit
d8eae9a26573149efad36a8e5c6b74c1
34.680982
98
0.636692
4.075683
false
false
false
false
sybila/ode-generator
src/test/kotlin/com/github/sybila/ode/generator/smt/remote/OneDimWithParamGeneratorTest.kt
1
5394
package com.github.sybila.ode.generator.smt.remote import com.github.sybila.checker.Transition import com.github.sybila.checker.decreaseProp import com.github.sybila.checker.increaseProp import com.github.sybila.huctl.DirectionFormula import com.github.sybila.ode.assertTransitionEquals import com.github.sybila.ode.model.OdeModel import com.github.sybila.ode.model.Summand import org.junit.Test class OneDimWithParamGeneratorTest { //dv1 = p(v1/2 + 1) - 1 //This one dimensional model should actually cover most of the behaviour //It only fails to cover a steady state in the middle of the model and //cases when parameter is multiplied by zero //dv2 = p(v1/2 - 2) - 1 //This model covers the two remaining cases. A stable state and a zero on threshold. private val v1 = OdeModel.Variable( name = "v1", range = Pair(0.0, 6.0), varPoints = null, thresholds = listOf(0.0, 2.0, 4.0, 6.0), equation = listOf( Summand(paramIndex = 0, variableIndices = listOf(0), constant = 0.5), Summand(paramIndex = 0), Summand(constant = -1.0)) ) private val v2 = v1.copy(name = "v1", equation = listOf( Summand(paramIndex = 0, variableIndices = listOf(0), constant = 0.5), Summand(paramIndex = 0, constant = -2.0), Summand(constant = -1.0))) private val loop = DirectionFormula.Atom.Loop private val up = "v1".increaseProp() private val down = "v1".decreaseProp() /** * WARNING - Because we don't know how to compare <= and < properly, some answers have * non-strict operators that don't make that much sense, but are necessary */ @Test fun parameterTestOne() { val fragmentOne = Z3OdeFragment(OdeModel(listOf(v1), listOf( OdeModel.Parameter("p", Pair(0.0, 2.0)) ))) fragmentOne.run { val p = "p" val one = "1" val two = "2" val three = "3" val four = "4" val half = one div two val third = one div three val fourth = one div four val thirdApprox = "0.3333333333" //bounds are already in the solver assertTransitionEquals(0.successors(true), Transition(0, loop, (p le one).toParams()), Transition(1, up, (p gt half).toParams()) ) assertTransitionEquals(1.successors(true), Transition(0, down, ((p lt half).toParams())), Transition(1, loop, ((p ge thirdApprox) and (p le half)).toParams()), Transition(2, up, (p gt thirdApprox).toParams()) ) assertTransitionEquals(2.successors(true), Transition(1, down, (p lt thirdApprox).toParams()), Transition(2, loop, (p ge fourth).toParams()) ) assertTransitionEquals(0.predecessors(true), Transition(0, loop, (p le one).toParams()), Transition(1, down, (p lt half).toParams()) ) assertTransitionEquals(1.predecessors(true), Transition(0, up, ((p gt half).toParams())), Transition(1, loop, ((p ge thirdApprox) and (p le half)).toParams()), Transition(2, down, (p lt thirdApprox).toParams()) ) assertTransitionEquals(2.predecessors(true), Transition(1, up, (p gt thirdApprox).toParams()), Transition(2, loop, (p ge fourth).toParams()) ) } } @Test fun parameterTestTwo() { val fragmentTwo = Z3OdeFragment(OdeModel(listOf(v2), listOf( OdeModel.Parameter("p", Pair(-2.0, 2.0)) ))) //dv2 = p(v1 - 2) - 1 //(0) dv2 = p(-2) - 1 p>-1/2 => - // p < -1/2 => + //(1) dv2 = p(-1) - 1 p>-1 => - // p < -1 => + //(2) dv2 = p(0) - 1 // -1 //(3) dv2 = p(1) - 1 p<1 => - // p > 1 => + fragmentTwo.run { val q = "p" val one = "1" val mOne = "-1" assertTransitionEquals(0.successors(true), Transition(0, loop, (q ge mOne).toParams()), Transition(1, up, (q lt mOne).toParams()) ) assertTransitionEquals(1.successors(true), Transition(0, down, (q gt mOne).toParams()), Transition(1, loop, (q le mOne).toParams()) ) assertTransitionEquals(2.successors(true), Transition(1, down, tt), Transition(2, loop, (q ge one).toParams()) ) assertTransitionEquals(0.predecessors(true), Transition(0, loop, (q ge mOne).toParams()), Transition(1, down, (q gt mOne).toParams()) ) assertTransitionEquals(1.predecessors(true), Transition(0, up, (q lt mOne).toParams()), Transition(1, loop, (q le mOne).toParams()), Transition(2, down, tt) ) assertTransitionEquals(2.predecessors(true), Transition(2, loop, (q ge one).toParams()) ) } } }
gpl-3.0
acd6ed772e69be3fdaf6fda7f7779a8b
39.556391
91
0.525028
3.995556
false
false
false
false
ZieIony/Carbon
samples/src/main/java/tk/zielony/carbonsamples/AboutActivity.kt
1
953
package tk.zielony.carbonsamples import android.content.Intent import android.net.Uri import android.os.Bundle import kotlinx.android.synthetic.main.activity_about.* @SampleAnnotation(layoutId = R.layout.activity_about, titleId = R.string.aboutActivity_title) class AboutActivity : ThemedActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() website.setOnClickListener { val url = "https://github.com/ZieIony/Carbon" val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) startActivity(i) } issue.setOnClickListener { val url = "https://github.com/ZieIony/Carbon/issues" val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) startActivity(i) } version.text = "Carbon version: ${carbon.BuildConfig.VERSION_NAME}" } }
apache-2.0
baf44784753e6a64190bd8ce39fd6e80
28.78125
93
0.648478
4.161572
false
false
false
false
TimLavers/IndoFlashKotlin
app/src/main/java/org/grandtestauto/indoflash/activity/WordListDisplay.kt
1
7795
package org.grandtestauto.indoflash.activity import android.app.Activity import android.os.Bundle import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_word_list.* import org.grandtestauto.indoflash.IndoFlash import org.grandtestauto.indoflash.R import org.grandtestauto.indoflash.word.Word import org.grandtestauto.indoflash.word.WordList import org.jetbrains.anko.alert import org.jetbrains.anko.intentFor import org.jetbrains.anko.toast import org.jetbrains.anko.yesButton import java.util.* class WordListDisplay : Activity() { lateinit private var application: IndoFlash lateinit private var wordList: WordList private var showDefinition: Boolean = false private var finished = false private var currentPosition = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_word_list) indonesianFirstButton.setOnClickListener { toggleIndonesianFirst() } nextButton.setText(R.string.show) nextButton.setOnClickListener { next() } shuffleButton.setOnClickListener { toggleShuffle() } showWordListsButton.setImageResource(R.drawable.ic_lists) showWordListsButton.setOnClickListener { startActivity(intentFor<WordListSelecter>()) } addOrRemoveFavouriteButton.setOnClickListener { addRemoveFavourite() } application = getApplication() as IndoFlash doSetup() } private fun loadWordList() { wordList = application.wordList() if (application.shuffle()) { val toShuffle = LinkedList<Word>() toShuffle.addAll(wordList.words()) Collections.shuffle(toShuffle) wordList = WordList(toShuffle) } } override fun onResume() { super.onResume() doSetup() } override fun onRestart() { super.onRestart() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.actions, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle presses on the action bar items when (item.itemId) { R.id.action_info -> { alert(R.string.acknowledgements, R.string.info) {yesButton { }}.show() return true } R.id.action_help -> { alert(R.string.help_text, R.string.help) { yesButton { } }.show() return true } else -> return super.onOptionsItemSelected(item) } } private fun toggleIndonesianFirst() { application.toggleShowIndonesianFirst() showDefinition = false showFirstWord() setupIndonesianFirstButton(true) } private fun setupIndonesianFirstButton(showToast: Boolean) { var resourceId = R.string.indonesian_first if (application.showIndonesianFirst()) { indonesianFirstButton.setImageResource(R.drawable.ic_down_arrow) } else { resourceId = R.string.english_first indonesianFirstButton.setImageResource(R.drawable.ic_up_arrow) } val description = indonesianFirstButton.context.resources.getText(resourceId) indonesianFirstButton.contentDescription = description if (showToast) toast(description) } private fun toggleShuffle() { application.toggleShuffle() loadWordList() showFirstWord() setupShuffleButton() //todo simplify this if val msgId = if (application.shuffle()) R.string.shuffle_on_toast else R.string.shuffle_off_toast toast(msgId) } private fun setupShuffleButton() { var resourceId = R.string.unshuffle if (application.shuffle()) { shuffleButton.setImageResource(R.drawable.ic_shuffle) } else { shuffleButton.setImageResource(R.drawable.ic_unshuffle) resourceId = R.string.shuffle } val description = shuffleButton.context.resources.getText(resourceId) shuffleButton.contentDescription = description } private fun doSetup() { wordListTitleView.text = application.currentWordList().title setupIndonesianFirstButton(false) setupShuffleButton() setupFavouritesButton() loadWordList() showFirstWord() } private fun showFirstWord() { if (application.showingFavourites() && wordList.words().isEmpty()) { showForEmptyFavourites() } else { wordView.text = getWord(0).word definitionView.text = "" showDefinition = true currentPosition = 0 nextButton.isClickable = true addOrRemoveFavouriteButton.isClickable = true } } private fun showForEmptyFavourites() { finished = true wordView.setText(R.string.favourites_is_empty) nextButton.text = "" nextButton.isClickable = false addOrRemoveFavouriteButton.isClickable = false } private fun setupFavouritesButton() { var resourceId = R.string.add_to_favourites if (application.showingFavourites()) { resourceId = R.string.remove_from_favourites addOrRemoveFavouriteButton.setImageResource(R.drawable.ic_remove_from_favourites) } else { addOrRemoveFavouriteButton.setImageResource(R.drawable.ic_add_to_favourites) } val description = addOrRemoveFavouriteButton.context.resources.getText(resourceId) addOrRemoveFavouriteButton.contentDescription = description } private fun addRemoveFavourite() { application.addRemoveFavourite(getWord(currentPosition)) if (application.showingFavourites()) { toast(R.string.removed_from_favourites_toast) if (showDefinition) { //Removing a word is like activating Show but we don't want to see the definition of the word just removed. showDefinition = false } //The user may now be at the end of the list. if (currentPosition == wordList.words().size - 1) { finished = true if (application.storedFavourites().words().isEmpty()) { showForEmptyFavourites() } else { nextButton.setText(R.string.repeat) } } else { next() } } else { toast(R.string.added_to_favourites_toast) } } private fun getWord(index: Int): Word { val word = wordList.words()[index] if (application.showIndonesianFirst()) return word return Word(word.definition, word.word) } private operator fun next() { if (finished) { currentPosition = 0 wordView.text = getWord(currentPosition).word definitionView.text = "" nextButton.setText(R.string.show) showDefinition = true finished = false return } if (showDefinition) { definitionView.text = getWord(currentPosition).definition nextButton.setText(R.string.next) showDefinition = false if (currentPosition == wordList.words().size - 1) { finished = true nextButton.setText(R.string.repeat) } } else { currentPosition++ wordView.text = getWord(currentPosition).word definitionView.text = "" nextButton.setText(R.string.show) showDefinition = true } } }
mit
ebe1080e4d00e271d8e5ac01a453913a
33.803571
123
0.628865
4.94293
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathElementTestPsiImpl.kt
1
3305
/* * Copyright (C) 2016, 2019-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath import com.intellij.lang.ASTNode import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.psi.ASTWrapperPsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathElementTest import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathTypeName import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathWildcard import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement class XPathElementTestPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XpmSyntaxValidationElement, XPathElementTest { companion object { private val TYPE_NAME = Key.create<String>("TYPE_NAME") } // region ASTDelegatePsiElement override fun subtreeChanged() { super.subtreeChanged() clearUserData(TYPE_NAME) } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = children().filterIsInstance<XPathWildcard>().firstOrNull() ?: firstChild // endregion // region XPathElementTest override val nodeName: XsQNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull() override val nodeType: XdmSequenceType? get() = when (val type = children().filterIsInstance<XdmSequenceType>().firstOrNull()) { is XPathTypeName -> if (type.type.localName == null) null else type else -> type } // endregion // region XdmSequenceType override val typeName: String get() = computeUserDataIfAbsent(TYPE_NAME) { val name = nodeName val type = nodeType when { name == null -> { type?.let { "element(*,${type.typeName})" } ?: "element()" } type == null -> "element(${qname_presentation(name)})" else -> "element(${qname_presentation(name)},${type.typeName})" } } override val itemType: XdmItemType get() = this override val lowerBound: Int = 1 override val upperBound: Int = 1 // endregion // region XdmItemType override val typeClass: Class<*> = XdmElementNode::class.java // endregion }
apache-2.0
87f6c5b86e479a0ec1921ec94223f51f
34.923913
96
0.700151
4.47226
false
false
false
false
savvasdalkitsis/gameframe
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/swatch/view/SwatchView.kt
1
3611
/** * 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.workspace.element.swatch.view import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Path import android.graphics.RectF import android.graphics.drawable.Drawable import android.util.AttributeSet import com.afollestad.materialdialogs.color.CircleView import com.savvasdalkitsis.gameframe.feature.workspace.R import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view.PaletteView class SwatchView : CircleView { var color: Int = 0 private set var index: Int = 0 private set private lateinit var paletteView: PaletteView private lateinit var circlePath: Path private lateinit var circleRect: RectF private lateinit var tile: Drawable private var binding: Boolean = false constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onFinishInflate() { super.onFinishInflate() setOnClickListener { paletteView.deselectAllSwatches() isSelected = true paletteView.notifyListenerOfSwatchSelected(this) } setOnLongClickListener { paletteView.notifyListenerOfSwatchLongClicked(this) true } } @Suppress("DEPRECATION") override fun onAttachedToWindow() { super.onAttachedToWindow() paletteView = parent as PaletteView circlePath = Path() circleRect = RectF(0f, 0f, measuredWidth.toFloat(), measuredWidth.toFloat()) tile = resources.getDrawable(R.drawable.transparency_background) } @Suppress("OverridingDeprecatedMember") override fun setBackground(background: Drawable?) { // needed to avoid parent illegal argument exception when inflating from xml } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(measuredWidth, measuredWidth) circlePath.reset() circleRect.set(2f, 2f, (measuredWidth - 2).toFloat(), (measuredWidth - 2).toFloat()) circlePath.addOval(circleRect, Path.Direction.CW) } override fun onDraw(canvas: Canvas) { canvas.save() canvas.clipPath(circlePath) tile.setBounds(0, 0, measuredWidth, measuredWidth) tile.draw(canvas) canvas.restore() super.onDraw(canvas) } fun bind(color: Int, index: Int) { this.color = color this.index = index binding = true setBackgroundColor(color) binding = false } @SuppressLint("MissingSuperCall") override fun requestLayout() { if (!binding) { super.requestLayout() } } }
apache-2.0
0c043c9c4ab6b7a736f056fbaa8838cf
32.435185
111
0.702022
4.782781
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/img/ImgV1.kt
1
902
package nl.shadowlink.tools.shadowlib.img import nl.shadowlink.tools.io.ReadFunctions import nl.shadowlink.tools.shadowlib.utils.Utils import java.nio.file.Path import kotlin.io.path.nameWithoutExtension /** * @author Shadow-Link */ class ImgV1 : ImgLoader { override fun load(path: Path): Img { val items = ArrayList<ImgItem>() val rf = ReadFunctions("${path.nameWithoutExtension}.dir") while (rf.moreToRead() != 0) { val itemOffset = rf.readInt() * 2048 val itemSize = rf.readInt() * 2048 val itemName = rf.readNullTerminatedString(24) val itemType = Utils.getFileType(itemName) val item = ImgItem(itemName) item.offset = itemOffset item.size = itemSize item.type = itemType items.add(item) } return Img(items = items, path = path) } }
gpl-2.0
df1ad6ad2044b9f5fcb729ba2e562d89
27.1875
66
0.620843
4.1
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandGive.kt
1
2121
package nl.sugcube.dirtyarrows.command import nl.sugcube.dirtyarrows.Broadcast import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowDistributor import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.onlinePlayer import nl.sugcube.dirtyarrows.util.sendError import nl.sugcube.dirtyarrows.util.sendFormattedMessage import org.bukkit.Bukkit import org.bukkit.command.CommandSender /** * @author SugarCaney */ open class CommandGive : SubCommand<DirtyArrows>( name = "give", usage = "/da give <player> <bow> ['ench']", argumentCount = 2, description = "Give DirtyArrows bows to players." ) { init { addPermissions("dirtyarrows.admin") addAutoCompleteMeta(0, AutoCompleteArgument.PLAYERS) addAutoCompleteMeta(1, AutoCompleteArgument.BOWS) addAutoCompleteMeta(2, AutoCompleteArgument.ENCHANTED) } override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) { // All players to give the resulting bow. val playerName = arguments.firstOrNull() ?: run { sender.sendError("No player name specified."); return } val players = if (playerName == "@a") { Bukkit.getOnlinePlayers() } else listOf(onlinePlayer(playerName) ?: run { sender.sendError("No online player '$playerName'"); return }) // Which bow to give. val bowNode = arguments.getOrNull(1) ?: run { sender.sendError("No bow specified."); return } val bow = DefaultBow.parseBow(bowNode) ?: run { sender.sendError("Unknown bow '$bowNode'."); return } val bowName = plugin.config.getString(bow.nameNode) // Whether the bow must have Unbreaking X with Infinity I. val isEnchanted = "ench".equals(arguments.getOrNull(2), ignoreCase = true) // Distribute. BowDistributor(plugin.config, players).giveBow(bow, isEnchanted) sender.sendFormattedMessage(Broadcast.GAVE_BOW.format(bowName, players.joinToString(", ") { it.name })) } override fun assertSender(sender: CommandSender) = true }
gpl-3.0
3839e94044c29f4341f8606593e942a8
39.807692
117
0.70297
4.310976
false
false
false
false
gurleensethi/LiteUtilities
liteutils/src/main/java/com/thetechnocafe/gurleensethi/liteutils/LogUtils.kt
1
4716
package com.thetechnocafe.gurleensethi.liteutils import android.util.Log import org.json.JSONObject /** * Created by gurleensethi on 17/09/17. */ /** * Created by gurleensethi on 17/09/17. * Motivation : Simplify android logging using Kotlin */ class LogUtils { /* * Maintain which log level the user has allowed to logged by * adding all the allowed log levels to a set. * */ companion object { private val logLevels = mutableSetOf<LogLevel>() fun addLevel(logLevel: LogLevel) { if (logLevel == LogLevel.ALL) { logLevels.add(LogLevel.DEBUG) logLevels.add(LogLevel.INFO) logLevels.add(LogLevel.WARN) logLevels.add(LogLevel.VERBOSE) logLevels.add(LogLevel.ERROR) logLevels.add(LogLevel.WTF) } else { logLevels.add(logLevel) } } fun addLevel(vararg logLevel: LogLevel) { if (logLevel.contains(LogLevel.ALL)) { logLevels.add(LogLevel.DEBUG) logLevels.add(LogLevel.INFO) logLevels.add(LogLevel.WARN) logLevels.add(LogLevel.VERBOSE) logLevels.add(LogLevel.ERROR) logLevels.add(LogLevel.WTF) } else { logLevels.addAll(logLevel) } } fun removeLevel(logLevel: LogLevel) { logLevels.remove(logLevel) } fun containsLevel(logLevel: LogLevel): Boolean = logLevel in logLevels } } //Different log levels that user can select enum class LogLevel { ALL, INFO, DEBUG, WARN, VERBOSE, WTF, ERROR, } fun Any.info(message: String) { if (LogUtils.containsLevel(LogLevel.INFO)) { Log.i(javaClass.simpleName, message) } } fun Any.debug(message: String) { if (LogUtils.containsLevel(LogLevel.DEBUG)) { Log.d(javaClass.simpleName, message) } } fun Any.error(message: String) { if (LogUtils.containsLevel(LogLevel.ERROR)) { Log.e(javaClass.simpleName, message) } } fun Any.verbose(message: String) { if (LogUtils.containsLevel(LogLevel.VERBOSE)) { Log.v(javaClass.simpleName, message) } } fun Any.warn(message: String) { if (LogUtils.containsLevel(LogLevel.WARN)) { Log.w(javaClass.simpleName, message) } } fun Any.wtf(message: String) { if (LogUtils.containsLevel(LogLevel.WTF)) { Log.wtf(javaClass.simpleName, message) } } /** * Pretty Print the message inside a box of characters. * The default boundary character is '*', but a different one can be provided by * the user * @param message to be logged * @param boundaryCharacter of the box * */ fun Any.shout(message: String, boundaryCharacter: Char = '*') { val listOfStrings = message.split("\n") val largestLength = listOfStrings.maxBy { it.length }?.length ?: message.length val logWidth = largestLength + 11 var lineWithCharsAtEnd = "" var lineTop = "" var lineBelow = "" for (count in 0..logWidth) { lineTop += boundaryCharacter lineBelow += boundaryCharacter lineWithCharsAtEnd += if (count == 0 || count == logWidth) { boundaryCharacter } else { " " } } var finalMessage = "$lineTop\n$lineWithCharsAtEnd\n" for (string in listOfStrings) { var leftSpace = "$boundaryCharacter " var rightSpace = " " val differenceFromLargestString = largestLength - string.length val rightAddedSpace = differenceFromLargestString / 2 val leftAddedSpace = differenceFromLargestString - rightAddedSpace for (count in 0..leftAddedSpace) { leftSpace += " " } for (count in 0..rightAddedSpace) { rightSpace += " " } rightSpace += "$boundaryCharacter" finalMessage += "$leftSpace$string$rightSpace\n" } debug("$finalMessage$lineWithCharsAtEnd\n$lineBelow") } /* * Pretty print string that contains data in json format. * Use debug log level tp print data and error to print error. * */ fun Any.json(message: String) { try { val jsonString = JSONObject(message).toString(4) debug(jsonString) } catch (e: Exception) { if (LogUtils.containsLevel(LogLevel.ERROR)) { Log.e(javaClass.simpleName, "Wrong JSON format. Please check the structure.", e) } } } /* * Print the stack trace for an exception. * Use Error log level to print. * */ fun Any.exception(e: Exception) { if (LogUtils.containsLevel(LogLevel.ERROR)) { Log.e(javaClass.simpleName, "", e) } }
mit
232238a5d1d503a7b2c4dd26215959d5
26.109195
92
0.613656
3.989848
false
false
false
false
pyamsoft/pydroid
autopsy/src/main/java/com/pyamsoft/pydroid/autopsy/CrashActivity.kt
1
3077
/* * Copyright 2022 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pydroid.autopsy import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.CheckResult import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.Modifier import com.pyamsoft.pydroid.core.requireNotNull import com.pyamsoft.pydroid.theme.PYDroidTheme import kotlin.system.exitProcess /** * The screen that will show up on device when a crash occurs * * Will also log the crash to logcat */ internal class CrashActivity internal constructor() : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Hide ActionBar actionBar?.hide() val launchIntent = intent val threadName = launchIntent.getStringExtra(KEY_THREAD_NAME).requireNotNull() val throwableName = launchIntent.getStringExtra(KEY_THROWABLE).requireNotNull() val throwableMessage = launchIntent.getStringExtra(KEY_MESSAGE).requireNotNull() val stackTrace = launchIntent.getStringExtra(KEY_TRACE).requireNotNull() setContent { PYDroidTheme { SystemBars() CrashScreen( modifier = Modifier.fillMaxSize(), threadName = threadName, throwableName = throwableName, throwableMessage = throwableMessage, stackTrace = stackTrace, ) } } } override fun onStop() { super.onStop() finish() } override fun onDestroy() { super.onDestroy() exitProcess(0) } companion object { private const val KEY_THREAD_NAME = "key_thread_name" private const val KEY_THROWABLE = "key_throwable" private const val KEY_MESSAGE = "key_message" private const val KEY_TRACE = "key_trace" @CheckResult @JvmStatic internal fun newIntent(context: Context, threadName: String, throwable: Throwable): Intent { return Intent(context.applicationContext, CrashActivity::class.java).apply { putExtra(KEY_THREAD_NAME, threadName) putExtra(KEY_THROWABLE, throwable::class.java.simpleName) putExtra(KEY_MESSAGE, throwable.message.orEmpty()) putExtra(KEY_TRACE, throwable.stackTraceToString()) flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION } } } }
apache-2.0
98149145c19f00d91f1164cc664937f1
31.052083
96
0.714332
4.613193
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ComponentContainer.kt
1
2069
package org.hexworks.zircon.api.component import org.hexworks.zircon.api.behavior.ColorThemeOverride import org.hexworks.zircon.api.builder.Builder /** * Represents an object that can contain gui [Component]s and also maintains * a [theme] property that's synchronized between its child [Component]s. * Note that a [ComponentContainer] won't enforce consistency: the child * themes can be changed individually, but they will be overwritten whenever * the [ComponentContainer]'s theme changes. * @see Component * @see ColorThemeOverride */ interface ComponentContainer : ColorThemeOverride { /** * Adds a child [Component] to this [ComponentContainer]. It can either be * a leaf component (like a label) or a [Container] which can itself * contain components within itself. */ fun addComponent(component: Component): AttachedComponent /** * Builds a [Component] using the given component [Builder] * and adds it to this [ComponentContainer]. */ fun addComponent(builder: Builder<Component>): AttachedComponent = addComponent(builder.build()) /** * Adds the given [Component]s to this [ComponentContainer]. * @see addComponent */ fun addComponents(vararg components: Component): List<AttachedComponent> = components.map(::addComponent) /** * Adds the given [Component]s to this [ComponentContainer]. * @see addComponent */ fun addComponents(vararg components: Builder<Component>): List<AttachedComponent> = components.map(::addComponent) /** * Adds the [Fragment.root] of the given [Fragment] to this [ComponentContainer]. */ fun addFragment(fragment: Fragment): AttachedComponent = addComponent(fragment.root) /** * Adds the [Fragment.root] of the given [Fragment] to this [ComponentContainer]. */ fun addFragments(vararg fragments: Fragment): List<AttachedComponent> = fragments.map(::addFragment) /** * Detaches all child components and returns them. */ fun detachAllComponents(): List<Component> }
apache-2.0
9b85f26218615625f1b45960154367e5
35.298246
118
0.710971
4.65991
false
false
false
false
qoncept/TensorKotlin
src/jp/co/qoncept/tensorkotlin/TensorNN.kt
1
5080
package jp.co.qoncept.tensorkotlin val Tensor.softmax: Tensor get() { val exps = exp val sum = exps.elements.fold(0.0f) { r, x -> r + x } return exps / sum } val Tensor.relu: Tensor get() { return Tensor(shape, this.elements.map { Math.max(it, 0.0f) }) } fun Tensor.maxPool(kernelSize: IntArray, strides: IntArray): Tensor { assert({ shape.dimensions.size == 3 }, { "`shape.dimensions.size` must be 3: ${shape.dimensions.size}" }) assert({ kernelSize.size == 3 }, { "`kernelSize.size` must be 3: ${kernelSize.size}" }) assert({ kernelSize[2] == 1 } , { "`kernelSize[2]` != 1 is not supported: ${ kernelSize[2] }" }) assert({ strides.size == 3 }, { "`strides.size` must be 3: ${ strides.size }" }) assert({ strides[2] == 1 } , { "`strides[2]` != 1 is not supported: ${ strides[2] }" }) val inRows = shape.dimensions[0] val inCols = shape.dimensions[1] val numChannels = shape.dimensions[2] val filterHeight = kernelSize[0] val filterWidth = kernelSize[1] val inMinDy = -(filterHeight - 1) / 2 val inMaxDy = inMinDy + filterHeight - 1 val inMinDx = -(filterWidth - 1) / 2 val inMaxDx = inMinDx + filterWidth - 1 val rowStride = strides[0] val colStride = strides[1] val outRows = inRows ceilDiv rowStride val outCols = inCols ceilDiv colStride val elements = FloatArray(outCols * outRows * numChannels) var elementIndex = 0 for (y in 0 until outRows) { val inY0 = y * rowStride val inMinY = Math.max(inY0 + inMinDy, 0) val inMaxY = Math.min(inY0 + inMaxDy, inRows - 1) for (x in 0 until outCols) { val inX0 = x * colStride val inMinX = Math.max(inX0 + inMinDx, 0) val inMaxX = Math.min(inX0 + inMaxDx, inCols - 1) for (c in 0 until numChannels) { var maxElement = Float.MIN_VALUE for (inY in inMinY..inMaxY) { for (inX in inMinX..inMaxX) { maxElement = Math.max(maxElement, this.elements[(inY * inCols + inX) * numChannels + c]) } } elements[elementIndex++] = maxElement } } } return Tensor(Shape(outRows, outCols, numChannels), elements) } fun Tensor.conv2d(filter: Tensor, strides: IntArray): Tensor { val inChannels = filter.shape.dimensions[2] assert({ shape.dimensions.size == 3 }, { "`shape.dimensions.size` must be 3: ${shape.dimensions.size}" }) assert({ filter.shape.dimensions.size == 4 }, { "`filter.shape.dimensions.size` must be 4: ${filter.shape.dimensions.size}" }) assert({ strides.size == 3 }, { "`strides.size` must be 3: ${ strides.size }" }) assert({ strides[2] == 1 } , { "`strides[2]` != 1 is not supported: ${ strides[2] }" }) assert({ shape.dimensions[2] == inChannels }, { "The number of channels of this tensor and the filter are not compatible: ${shape.dimensions[2]} != ${inChannels}" }) val inRows = shape.dimensions[0] val inCols = shape.dimensions[1] val filterHeight = filter.shape.dimensions[0] val filterWidth = filter.shape.dimensions[1] val inMinDy = -(filterHeight - 1) / 2 val inMaxDy = inMinDy + filterHeight - 1 val inMinDx = -(filterWidth - 1) / 2 val inMaxDx = inMinDx + filterWidth - 1 val rowStride = strides[0] val colStride = strides[1] val outRows = shape.dimensions[0] ceilDiv rowStride val outCols = shape.dimensions[1] ceilDiv colStride val outChannels = filter.shape.dimensions[3] val elements = FloatArray(outCols * outRows * outChannels) for (y in 0 until outRows) { val inY0 = y * rowStride val inMinY = Math.max(inY0 + inMinDy, 0) val inMaxY = Math.min(inY0 + inMaxDy, inRows - 1) for (x in 0 until outCols) { val inX0 = x * colStride val inMinX = Math.max(inX0 + inMinDx, 0) val inMaxX = Math.min(inX0 + inMaxDx, inCols - 1) val inYOffset = inY0 + inMinDy val inXOffset = inX0 + inMinDx for (inY in inMinY..inMaxY) { for (inX in inMinX..inMaxX) { matmuladd( inChannels, outChannels, (inY * inCols + inX) * inChannels, this.elements, ((inY - inYOffset) * filterWidth + (inX - inXOffset)) * inChannels * outChannels, filter.elements, (y * outCols + x) * outChannels, elements ) } } } } return Tensor(Shape(outRows, outCols, outChannels), elements) } internal fun matmuladd(inCols1Rows2: Int, outCols: Int, o1: Int, vec: FloatArray, o2: Int, mat: FloatArray, oo: Int, out: FloatArray) { for (i in 0 until inCols1Rows2) { var elementIndex = oo val left = vec[i + o1] for (c in 0 until outCols) { out[elementIndex] += left * mat[i * outCols + c + o2] elementIndex++ } } }
mit
34881d57fc711fa8cafd38484c03e2cd
36.62963
169
0.577362
3.496215
false
false
false
false
mdaniel/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/problems/ClassProblemsTest.kt
9
13492
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.daemon.problems import com.intellij.codeInsight.daemon.problems.Problem import com.intellij.codeInsight.daemon.problems.pass.ProjectProblemUtils import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringFactory import com.intellij.refactoring.move.moveInner.MoveInnerImpl import com.intellij.refactoring.openapi.impl.MoveInnerRefactoringImpl internal class ClassProblemsTest : ProjectProblemsViewTest() { fun testRename() = doClassTest { psiClass, factory -> psiClass.nameIdentifier?.replace(factory.createIdentifier("Bar")) } fun testMakeClassFinal() = doClassTest { psiClass, _ -> psiClass.modifierList?.setModifierProperty(PsiModifier.FINAL, true) } fun testMakeClassPackagePrivate() = doClassTest { psiClass, _ -> psiClass.modifierList?.setModifierProperty(PsiModifier.PUBLIC, false) } fun testChangeClassHierarchy() = doClassTest { psiClass, factory -> psiClass.extendsList?.replace(factory.createReferenceList(PsiJavaCodeReferenceElement.EMPTY_ARRAY)) } fun testSealedClassPermittedInheritors() { val targetClass = myFixture.addClass(""" package foo; public sealed class A { } """.trimIndent()) val refClass = myFixture.addClass(""" package foo; public class B extends A { } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, _ -> val factory = PsiFileFactory.getInstance(project) val javaFile = factory.createFileFromText(JavaLanguage.INSTANCE, "class __Dummy permits B {}") as PsiJavaFile val dummyClass = javaFile.classes[0] val permitsList = dummyClass.permitsList psiClass.addAfter(permitsList!!, psiClass.implementsList) } assertTrue(hasReportedProblems<PsiClass>(refClass)) myFixture.openFileInEditor(refClass.containingFile.virtualFile) changeClass(refClass) { psiClass, _ -> psiClass.modifierList?.setModifierProperty(PsiModifier.FINAL, true) } myFixture.openFileInEditor(targetClass.containingFile.virtualFile) myFixture.doHighlighting() assertFalse(hasReportedProblems<PsiClass>(refClass)) } } fun testClassOverrideBecamePrivate() { myFixture.addClass(""" package foo; public abstract class Parent { abstract void test(); } """.trimIndent()) val targetClass = myFixture.addClass(""" package foo; public class Foo extends Parent { void test() {} } """.trimIndent()) val refClass = myFixture.addClass(""" package foo; public class Usage { void use() { Foo foo = new Foo(); foo.test(); } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, factory -> psiClass.methods[0].parameterList.add(factory.createParameterFromText("int a", psiClass)) } changeClass(targetClass) { psiClass, _ -> psiClass.methods[0].modifierList.setModifierProperty(PsiModifier.PUBLIC, true) } changeClass(targetClass) { psiClass, factory -> psiClass.extendsList?.replace(factory.createReferenceList(PsiJavaCodeReferenceElement.EMPTY_ARRAY)) } } assertTrue(hasReportedProblems<PsiMethod>(refClass)) } fun testMakeClassInterface() { val targetClass = myFixture.addClass(""" package foo; public class A { } """.trimIndent()) val refClass = myFixture.addClass(""" package bar; import foo.*; public class B { void test() { A a = new A();; } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, factory -> val classKeyword = PsiTreeUtil.getPrevSiblingOfType(psiClass.nameIdentifier, PsiKeyword::class.java) val interfaceKeyword = factory.createKeyword(PsiKeyword.INTERFACE) classKeyword?.replace(interfaceKeyword) } assertTrue(hasReportedProblems<PsiDeclarationStatement>(refClass)) } } fun testMakeNestedInner() { doNestedClassTest(true) } fun testMakeInnerNested() { doNestedClassTest(false) } fun testMakeClassAnnotationType() { var targetClass = myFixture.addClass(""" package foo; public class A { } """.trimIndent()) val refClass = myFixture.addClass(""" package bar; import foo.*; public class B { void test() { A a = new A(); } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { _, factory -> val annoType = factory.createAnnotationType("A") targetClass = targetClass.replace(annoType) as PsiClass } } assertTrue(hasReportedProblems<PsiDeclarationStatement>(refClass)) } fun testInheritedMethodUsage() { myFixture.addClass(""" package foo; public class Parent { public void foo() {} } """.trimIndent()) val aClass = myFixture.addClass(""" package foo; public class A extends Parent { } """.trimIndent()) val refClass = myFixture.addClass(""" package foo; public class Usage { void test() { (new A()).foo(); } } """.trimIndent()) doTest(aClass) { changeClass(aClass) { psiClass, factory -> psiClass.extendsList?.replace(factory.createReferenceList(PsiJavaCodeReferenceElement.EMPTY_ARRAY)) } assertTrue(hasReportedProblems<PsiClass>(refClass)) } } fun testMoveInnerClassAndUndo() { val refClass = myFixture.addClass(""" public class A { private String s = "foo"; public class Inner { void test() { System.out.println(s); } } } """.trimIndent()) myFixture.openFileInEditor(refClass.containingFile.virtualFile) doTest(refClass) { changeClass(refClass) { psiClass, _ -> val innerClass = psiClass.innerClasses[0] val targetContainer = MoveInnerImpl.getTargetContainer(innerClass, false)!! val moveRefactoring = MoveInnerRefactoringImpl(myFixture.project, innerClass, innerClass.name, true, "a", targetContainer) BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> { moveRefactoring.run() } } changeClass(refClass) { psiClass, _ -> psiClass.fields[0].modifierList?.setModifierProperty(PsiModifier.PRIVATE, false) } changeClass(refClass) { psiClass, _ -> psiClass.fields[0].modifierList?.setModifierProperty(PsiModifier.PRIVATE, true) } assertNotEmpty(getProblems()) val selectedEditor = FileEditorManager.getInstance(project).selectedEditor WriteCommandAction.runWriteCommandAction(project) { UndoManager.getInstance(project).undo(selectedEditor) UndoManager.getInstance(project).undo(selectedEditor) UndoManager.getInstance(project).undo(selectedEditor) } PsiDocumentManager.getInstance(project).commitAllDocuments() myFixture.doHighlighting() assertEmpty(ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) } } fun testRenameClassRenameMethodAndUndoAll() { val targetClass = myFixture.addClass(""" public class A { public void foo() {} public void bar() {} } """.trimIndent()) myFixture.addClass(""" public class RefClass { void test() { A a = new A(); a.foo(); a.bar(); } } """.trimIndent()) doTest(targetClass) { val factory = JavaPsiFacade.getInstance(project).elementFactory changeClass(targetClass) { psiClass, _ -> psiClass.identifyingElement?.replace(factory.createIdentifier("A1")) } val problems: Map<PsiMember, Set<Problem>> = ProjectProblemUtils.getReportedProblems(myFixture.editor) val reportedMembers = problems.map { it.key } assertSize(1, reportedMembers) assertTrue(targetClass in reportedMembers) WriteCommandAction.runWriteCommandAction(project) { val method = targetClass.findMethodsByName("foo", false)[0] method.identifyingElement?.replace(factory.createIdentifier("foo1")) } myFixture.doHighlighting() assertNotEmpty(ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) WriteCommandAction.runWriteCommandAction(project) { val method = targetClass.findMethodsByName("foo1", false)[0] method.identifyingElement?.replace(factory.createIdentifier("foo")) } myFixture.doHighlighting() assertSize(2, ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) changeClass(targetClass) { psiClass, _ -> psiClass.identifyingElement?.replace(factory.createIdentifier("A")) } assertEmpty(ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) } } fun testAddMissingTypeParam() { val targetClass = myFixture.addClass(""" class TargetClass { } """.trimIndent()) myFixture.addClass(""" public class RefClass extends TargetClass<T> { } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, _ -> psiClass.modifierList?.setModifierProperty(PsiModifier.PUBLIC, true) } assertSize(1, ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) changeClass(targetClass) { psiClass, factory -> val typeParameterList = factory.createTypeParameterList() typeParameterList.add(factory.createTypeParameterFromText("T", psiClass)) psiClass.typeParameterList?.replace(typeParameterList) } assertEmpty(ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) } } fun testRenameClassAndFixUsages() { val targetClass = myFixture.addClass(""" class AClass { } """.trimIndent()) myFixture.addClass(""" class BClass { AClass tmp; public void method1(String arg) { System.out.println(tmp.toString()); } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, factory -> psiClass.nameIdentifier?.replace(factory.createIdentifier("AClass1")) } assertSize(1, ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) changeClass(targetClass) { psiClass, _ -> psiClass.setName("AClass") val renameRefactoring = RefactoringFactory.getInstance(project).createRename(psiClass, "AClass1", true, false) renameRefactoring.run() } assertEmpty(ProjectProblemUtils.getReportedProblems(myFixture.editor).entries) } } private fun doNestedClassTest(isStatic: Boolean) { val staticModifier = if (isStatic) "static" else "" val targetClass = myFixture.addClass(""" package foo; public class A { public $staticModifier class Inner {} } """.trimIndent()) val initializer = if (isStatic) "new A.Inner();" else "new A().new Inner()" val refClass = myFixture.addClass(""" package bar; import foo.*; public class B { void test() { A.Inner aInner = $initializer; } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass) { psiClass, _ -> val innerClass = psiClass.findInnerClassByName("Inner", false) innerClass?.modifierList?.setModifierProperty(PsiModifier.STATIC, !isStatic) } assertTrue(hasReportedProblems<PsiDeclarationStatement>(refClass)) } } private fun doClassTest(classChangeAction: (PsiClass, PsiElementFactory) -> Unit) { myFixture.addClass(""" package foo; public class Parent { } """.trimIndent()) val targetClass = myFixture.addClass(""" package foo; public class A extends Parent { } """.trimIndent()) val refClass = myFixture.addClass(""" package bar; import foo.*; public class B { void test() { Parent parent = new A() {}; } } """.trimIndent()) doTest(targetClass) { changeClass(targetClass, classChangeAction) assertTrue(hasReportedProblems<PsiDeclarationStatement>(refClass)) } } private fun changeClass(targetClass: PsiClass, classChangeAction: (PsiClass, PsiElementFactory) -> Unit) { WriteCommandAction.runWriteCommandAction(project) { val factory = JavaPsiFacade.getInstance(project).elementFactory classChangeAction(targetClass, factory) } myFixture.doHighlighting() } }
apache-2.0
00cff77ed7573147ab2a31cae924e195
29.524887
158
0.64957
5.075997
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/settings/SettingContext.kt
6
1327
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.core.entity.settings import org.jetbrains.kotlin.tools.projectWizard.core.EventManager class SettingContext { private val values = mutableMapOf<String, Any>() private val pluginSettings = mutableMapOf<String, PluginSetting<*, *>>() val eventManager = EventManager() @Suppress("UNCHECKED_CAST") operator fun <V : Any, T : SettingType<V>> get( reference: SettingReference<V, T> ): V? = values[reference.path] as? V operator fun <V : Any, T : SettingType<V>> set( reference: SettingReference<V, T>, newValue: V ) { values[reference.path] = newValue eventManager.fireListeners(reference) } @Suppress("UNCHECKED_CAST") fun <V : Any, T : SettingType<V>> getPluginSetting(pluginSettingReference: PluginSettingReference<V, T>) = pluginSettings[pluginSettingReference.path] as PluginSetting<V, T> fun <V : Any, T : SettingType<V>> setPluginSetting( pluginSettingReference: PluginSettingReference<V, T>, setting: PluginSetting<V, T> ) { pluginSettings[pluginSettingReference.path] = setting } }
apache-2.0
39234d9cf32ac12ddb3a26212a082702
36.942857
158
0.694047
4.239617
false
false
false
false
GunoH/intellij-community
platform/execution-impl/src/com/intellij/execution/actions/ExecutionTargetComboBoxAction.kt
1
5574
// 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.execution.actions import com.intellij.execution.* import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.util.Condition import com.intellij.openapi.util.text.StringUtil import org.jetbrains.annotations.Nls import java.awt.Dimension import javax.swing.JComponent private const val MAX_TARGET_DISPLAY_LENGTH = 80 const val EXECUTION_TARGETS_COMBO_ADDITIONAL_ACTIONS_GROUP = "ExecutionTargets.Additional" @JvmField val EXECUTION_TARGETS_COMBO_ACTION_PLACE = ActionPlaces.getPopupPlace("ExecutionTargets") /** * Combo-box for selecting execution targets ([ExecutionTarget]) * * See [com.intellij.execution.actions.RunConfigurationsComboBoxAction] for reference */ class ExecutionTargetComboBoxAction : ComboBoxAction(), DumbAware { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val project = e.project val presentation = e.presentation if (project == null || project.isDisposed || !project.isOpen || RunManager.IS_RUN_MANAGER_INITIALIZED[project] != true) { presentation.isEnabledAndVisible = false return } val executionTarget = ExecutionTargetManager.getActiveTarget(project) if (executionTarget == DefaultExecutionTarget.INSTANCE || executionTarget.isExternallyManaged) { presentation.isEnabledAndVisible = false return } presentation.isEnabledAndVisible = true val name = StringUtil.trimMiddle(executionTarget.displayName, MAX_TARGET_DISPLAY_LENGTH) presentation.setText(name, false) } override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup { val actionGroup = DefaultActionGroup() val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(button)) ?: return actionGroup actionGroup.addAll(getTargetActions(project)) val additionalActions = ActionManager.getInstance().getAction(EXECUTION_TARGETS_COMBO_ADDITIONAL_ACTIONS_GROUP) as? ActionGroup if (additionalActions != null) { actionGroup.add(additionalActions) } return actionGroup } private fun getTargetActions(project: Project): List<AnAction> { val selectedConfiguration = RunManager.getInstance(project).selectedConfiguration ?: return emptyList() val targets = ExecutionTargetManager.getTargetsToChooseFor(project, selectedConfiguration.configuration) val activeTarget = ExecutionTargetManager.getActiveTarget(project) val targetsGroups = targets.groupBy { it.groupName } val actions = mutableListOf<AnAction>() val defaultGroup = targetsGroups[null] if (defaultGroup != null) { actions.addAll(getTargetGroupActions(project, defaultGroup, null, activeTarget)) } for ((name, targetsGroup) in targetsGroups.entries.sortedBy { it.key }) { if (name == null) continue actions.addAll(getTargetGroupActions(project, targetsGroup, name, activeTarget)) } return actions } private fun getTargetGroupActions(project: Project, targets: List<ExecutionTarget>, targetGroupName: @Nls String?, activeTarget: ExecutionTarget): List<AnAction> { val actions = mutableListOf<AnAction>() if (targetGroupName != null) { actions.add(Separator.create(targetGroupName)) } targets.forEach { actions.add(SelectTargetAction(project, it, it == activeTarget, it.isReady)) } return actions } override fun createActionPopup(group: DefaultActionGroup, context: DataContext, disposeCallback: Runnable?): ListPopup { val popup = JBPopupFactory.getInstance().createActionGroupPopup( myPopupTitle, group, context, null, shouldShowDisabledActions(), disposeCallback, maxRows, preselectCondition, EXECUTION_TARGETS_COMBO_ACTION_PLACE ) popup.setMinimumSize(Dimension(minWidth, minHeight)) return popup } override fun getPreselectCondition(): Condition<AnAction> = Condition { if (it is SelectTargetAction) it.isSelected else false } override fun shouldShowDisabledActions(): Boolean = true private class SelectTargetAction constructor(private val project: Project, private val target: ExecutionTarget, val isSelected: Boolean, private val isReady: Boolean) : DumbAwareAction() { init { val name = target.displayName templatePresentation.setText(name, false) templatePresentation.description = ExecutionBundle.message("select.0", name) templatePresentation.icon = target.icon } override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabled = isReady } override fun actionPerformed(e: AnActionEvent) { ExecutionTargetManager.setActiveTarget(project, target) } } }
apache-2.0
86d4ea12ab0e45e2d125cac07554ee44
35.913907
131
0.71995
5.090411
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/InvalidTargetReleaseQuickFix.kt
9
3976
// 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.idea.maven.externalSystemIntegration.output.quickfixes import com.intellij.build.events.BuildEvent import com.intellij.build.events.MessageEvent import com.intellij.build.events.impl.BuildIssueEventImpl import com.intellij.build.issue.BuildIssue import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.pom.Navigatable import com.intellij.pom.java.LanguageLevel import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenParsingContext import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenSpyLoggedEventParser import org.jetbrains.idea.maven.externalSystemIntegration.output.parsers.MavenEventType import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProjectBundle.message import org.jetbrains.idea.maven.project.MavenProjectsManager import java.util.function.Consumer class InvalidTargetReleaseQuickFix : MavenSpyLoggedEventParser { override fun supportsType(type: MavenEventType) = type == MavenEventType.MOJO_FAILED override fun processLogLine(parentId: Any, parsingContext: MavenParsingContext, logLine: String, messageConsumer: Consumer<in BuildEvent?>): Boolean { if (logLine.contains("invalid target release:")) { val lastErrorProject = parsingContext.startedProjects.last() + ":" val failedProject = parsingContext.projectsInReactor.find { it.startsWith(lastErrorProject) } ?: return false val project = parsingContext.ideaProject val mavenProject = MavenProjectsManager.getInstance(project).findProject(MavenId(failedProject)) ?: return false if (mavenProject.mavenId.artifactId == null) return false val module = ModuleManager.getInstance(project).findModuleByName(mavenProject.mavenId.artifactId!!) ?: return false val moduleRootManager = ModuleRootManager.getInstance(module) ?: return false val moduleJdk = moduleRootManager.sdk val moduleProjectLanguageLevel = moduleJdk?.let { LanguageLevel.parse(it.versionString) } ?: return false val sourceLanguageLevel = getLanguageLevelFromLog(logLine) ?: return false messageConsumer.accept( BuildIssueEventImpl(parentId, getBuildIssue(sourceLanguageLevel, moduleProjectLanguageLevel, logLine, moduleRootManager), MessageEvent.Kind.ERROR) ) return true } return false } private fun getLanguageLevelFromLog(logLine: String): LanguageLevel? { return logLine.split(" ").last().let { LanguageLevel.parse(it) } } private fun getBuildIssue(sourceLanguageLevel: LanguageLevel, moduleProjectLanguageLevel: LanguageLevel, errorMessage: String, moduleRootManager: ModuleRootManager): BuildIssue { val moduleName = moduleRootManager.module.name val setupModuleSdkQuickFix = SetupModuleSdkQuickFix(moduleName, moduleRootManager.isSdkInherited) val quickFixes = listOf(setupModuleSdkQuickFix) val issueDescription = StringBuilder(errorMessage) issueDescription.append("\n\n") issueDescription.append(message("maven.quickfix.source.version.great", moduleName, moduleProjectLanguageLevel.toJavaVersion(), sourceLanguageLevel.toJavaVersion(), setupModuleSdkQuickFix.id)) return object : BuildIssue { override val title: String = errorMessage override val description: String = issueDescription.toString() override val quickFixes = quickFixes override fun getNavigatable(project: Project): Navigatable? = null } } }
apache-2.0
ccbb18250e9b8f3ec5e3e0ad6763848f
49.974359
140
0.737676
5.380244
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/row/InsertRowAction.kt
5
2334
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.actions.row import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.editor.tables.TableUtils.isHeaderRow import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow internal abstract class InsertRowAction(private val insertAbove: Boolean): RowBasedTableAction(considerSeparatorRow = true) { override fun performAction(editor: Editor, table: MarkdownTable, rowElement: PsiElement) { runWriteAction { val widths = obtainCellWidths(rowElement) val newRow = MarkdownPsiElementFactory.createTableEmptyRow(table.project, widths) require(rowElement.parent == table) executeCommand(rowElement.project) { when { insertAbove -> table.addRangeBefore(newRow, newRow.nextSibling, rowElement) else -> table.addRangeAfter(newRow.prevSibling, newRow, rowElement) } } } } private fun obtainCellWidths(element: PsiElement): Collection<Int> { return when (element) { is MarkdownTableRow -> element.cells.map { it.textLength } is MarkdownTableSeparatorRow -> element.cellsRanges.map { it.length } else -> error("element should be either MarkdownTableRow or MarkdownTableSeparatorRow") } } override fun findRowOrSeparator(file: PsiFile, document: Document, offset: Int): PsiElement? { val element = super.findRowOrSeparator(file, document, offset) ?: return null return when { (element as? MarkdownTableRow)?.isHeaderRow == true -> null insertAbove && element is MarkdownTableSeparatorRow -> null else -> element } } class InsertAbove: InsertRowAction(insertAbove = true) class InsertBelow: InsertRowAction(insertAbove = false) }
apache-2.0
29c7af92919acc2a65cef6dea9184982
44.764706
158
0.765638
4.445714
false
false
false
false
GunoH/intellij-community
plugins/full-line/java/src/org/jetbrains/completion/full/line/java/supporters/JavaSupporter.kt
2
4121
package org.jetbrains.completion.full.line.java.supporters import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFix import com.intellij.codeInsight.template.Template import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import org.jetbrains.completion.full.line.java.JavaIconSet import org.jetbrains.completion.full.line.language.LangState import org.jetbrains.completion.full.line.language.ModelState import org.jetbrains.completion.full.line.java.formatters.JavaCodeFormatter import org.jetbrains.completion.full.line.java.formatters.JavaPsiCodeFormatter import org.jetbrains.completion.full.line.language.supporters.FullLineLanguageSupporterBase class JavaSupporter : FullLineLanguageSupporterBase() { override val fileType: FileType = JavaFileType.INSTANCE override val language = JavaLanguage.INSTANCE override val iconSet = JavaIconSet() override val formatter = JavaCodeFormatter() override val psiFormatter = JavaPsiCodeFormatter() override val langState: LangState = LangState( enabled = false, localModelState = ModelState(numIterations = 8), ) override fun autoImportFix(file: PsiFile, editor: Editor, suggestionRange: TextRange): List<PsiElement> { return SyntaxTraverser.psiTraverser() .withRoot(file) .filter { it.reference is PsiJavaCodeReferenceElement && suggestionRange.contains(it.startOffset) } .toList() .distinctBy { it.text } .mapNotNull { val fix = ImportClassFix(it.reference as PsiJavaCodeReferenceElement) if (fix.isAvailable(it.project, editor, file)) { fix.invoke(it.project, editor, file) it } else { null } } } override fun createStringTemplate(element: PsiElement, range: TextRange): Template? { var content = range.substring(element.text) var contentOffset = 0 return SyntaxTraverser.psiTraverser() .withRoot(element) .onRange(range) .filter { it is PsiJavaToken && (it.tokenType == JavaTokenType.STRING_LITERAL) } .asIterable() .mapIndexedNotNull { id, it -> if (it is PsiJavaToken) { val stringContentRange = TextRange(it.startOffset + 1, it.endOffset - 1) .shiftRight(contentOffset - range.startOffset) val name = "\$__Variable${id}\$" val stringContent = stringContentRange.substring(content) contentOffset += name.length - stringContentRange.length content = stringContentRange.replace(content, name) stringContent } else { null } }.let { createTemplate(content, it) } } override fun createCodeFragment(file: PsiFile, text: String, isPhysical: Boolean): PsiFile { return ServiceManager.getService(file.project, JavaCodeFragmentFactory::class.java) .createCodeBlockCodeFragment(text, file, isPhysical) } override fun containsReference(element: PsiElement, range: TextRange): Boolean { if (element is PsiExpressionStatement) { return element.expression .let { if (it is PsiParenthesizedExpression) it.expression != null else true } } // Find all references and psi errors return (element is PsiReference || element is PsiIdentifier || element is PsiStatement || element is PsiAnnotationOwner || element is PsiNamedElement) // Check if elements does not go beyond the boundaries && range.contains(element.textRange) } override fun isStringElement(element: PsiElement): Boolean { return element is PsiJavaToken && (element.tokenType == JavaTokenType.STRING_LITERAL) } override fun isStringWalkingEnabled(element: PsiElement): Boolean { return true } }
apache-2.0
283af09b0b912f2a53b703e0cb7ba12f
35.469027
107
0.719971
4.651242
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/InlineUtils.kt
5
2760
// 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.base.util import com.intellij.debugger.jdi.LocalVariableProxyImpl import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT import org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION val INLINED_THIS_REGEX = run { val escapedName = Regex.escape(AsmUtil.INLINE_DECLARATION_SITE_THIS) val escapedSuffix = Regex.escape(INLINE_FUN_VAR_SUFFIX) Regex("^$escapedName(?:$escapedSuffix)*$") } // Compute the current inline depth given a list of visible variables. // All usages of this function should probably use [InlineStackFrame] instead, // since the inline depth does not suffice to determine which variables // are visible and this function will not work on a dex VM. fun getInlineDepth(variables: List<LocalVariableProxyImpl>): Int { val rawInlineFunDepth = variables.count { it.name().startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) } for (variable in variables.sortedByDescending { it.variable }) { val name = variable.name() val depth = getInlineDepth(name) if (depth > 0) { return depth } else if (name.startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT)) { return 0 } } return rawInlineFunDepth } fun getInlineDepth(variableName: String): Int { var endIndex = variableName.length var depth = 0 val suffixLen = INLINE_FUN_VAR_SUFFIX.length while (endIndex >= suffixLen) { if (variableName.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) { break } depth++ endIndex -= suffixLen } return depth } fun dropInlineSuffix(name: String): String { val depth = getInlineDepth(name) if (depth == 0) { return name } return name.dropLast(depth * INLINE_FUN_VAR_SUFFIX.length) } fun isInlineFrameLineNumber(file: VirtualFile, lineNumber: Int, project: Project): Boolean { if (RootKindFilter.projectSources.matches(project, file)) { val linesInFile = file.toPsiFile(project)?.getLineCount() ?: return false return lineNumber > linesInFile } return true }
apache-2.0
eb58cfdb0739ec6f8b116dc619826c46
35.315789
120
0.72971
4.156627
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/media/AudioRecordSource.kt
1
4746
package com.haishinkit.media import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import android.os.Build import android.util.Log import com.haishinkit.BuildConfig import com.haishinkit.net.NetStream import java.lang.IllegalStateException import java.nio.ByteBuffer import java.util.Arrays import java.util.concurrent.atomic.AtomicBoolean /** * An audio source that captures a microphone by the AudioRecord api. */ class AudioRecordSource(override var utilizable: Boolean = false) : AudioSource { var channel = DEFAULT_CHANNEL var audioSource = DEFAULT_AUDIO_SOURCE var sampleRate = DEFAULT_SAMPLE_RATE @Volatile var muted = false override var stream: NetStream? = null override val isRunning = AtomicBoolean(false) var minBufferSize = -1 get() { if (field == -1) { field = AudioRecord.getMinBufferSize(sampleRate, channel, encoding) } return field } var audioRecord: AudioRecord? = null get() { if (field == null) { if (Build.VERSION_CODES.M <= Build.VERSION.SDK_INT) { field = AudioRecord.Builder() .setAudioSource(audioSource) .setAudioFormat( AudioFormat.Builder() .setEncoding(encoding) .setSampleRate(sampleRate) .setChannelMask(channel) .build() ) .setBufferSizeInBytes(minBufferSize) .build() } else { field = AudioRecord( audioSource, sampleRate, channel, encoding, minBufferSize ) } } return field } var currentPresentationTimestamp = DEFAULT_TIMESTAMP private set private var encoding = DEFAULT_ENCODING private var sampleCount = DEFAULT_SAMPLE_COUNT override fun setUp() { if (utilizable) return super.setUp() } override fun tearDown() { if (!utilizable) return super.tearDown() } override fun startRunning() { if (isRunning.get()) return if (BuildConfig.DEBUG) { Log.d(TAG, "startRunning()") } currentPresentationTimestamp = DEFAULT_TIMESTAMP audioRecord?.startRecording() isRunning.set(true) } override fun stopRunning() { if (!isRunning.get()) return if (BuildConfig.DEBUG) { Log.d(TAG, "stopRunning()") } audioRecord?.stop() isRunning.set(false) } override fun onInputBufferAvailable(codec: android.media.MediaCodec, index: Int) { try { if (!isRunning.get()) return val inputBuffer = codec.getInputBuffer(index) ?: return val result = read(inputBuffer) if (0 <= result) { codec.queueInputBuffer(index, 0, result, currentPresentationTimestamp, 0) } } catch (e: IllegalStateException) { Log.w(TAG, e) } } private fun read(audioBuffer: ByteBuffer): Int { val result = audioRecord?.read(audioBuffer, sampleCount * 2) ?: -1 if (0 <= result) { if (muted) { Arrays.fill(audioBuffer.array(), audioBuffer.position(), result, 0.toByte()) } currentPresentationTimestamp += timestamp(result / 2) } else { val error = when (result) { AudioRecord.ERROR_INVALID_OPERATION -> "ERROR_INVALID_OPERATION" AudioRecord.ERROR_BAD_VALUE -> "ERROR_BAD_VALUE" AudioRecord.ERROR_DEAD_OBJECT -> "ERROR_DEAD_OBJECT" AudioRecord.ERROR -> "ERROR" else -> "ERROR($result)" } Log.w(TAG, error) } return result } private fun timestamp(sampleCount: Int): Long { return (1000000.0F * (sampleCount.toFloat() / sampleRate.toFloat())).toLong() } companion object { const val DEFAULT_CHANNEL = AudioFormat.CHANNEL_IN_MONO const val DEFAULT_ENCODING = AudioFormat.ENCODING_PCM_16BIT const val DEFAULT_SAMPLE_RATE = 44100 const val DEFAULT_AUDIO_SOURCE = MediaRecorder.AudioSource.CAMCORDER const val DEFAULT_SAMPLE_COUNT = 1024 private const val DEFAULT_TIMESTAMP = 0L private val TAG = AudioRecordSource::class.java.simpleName } }
bsd-3-clause
adf97df5665fcf101e991bfb3e4601d1
31.506849
92
0.560472
4.918135
false
false
false
false
jk1/intellij-community
plugins/settings-repository/src/RepositoryManager.kt
3
4109
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.progress.ProgressIndicator import gnu.trove.THashSet import java.io.InputStream import java.util.* interface RepositoryManager { fun createRepositoryIfNeed(): Boolean /** * Think twice before use */ fun deleteRepository() fun isRepositoryExists(): Boolean fun getUpstream(): String? fun hasUpstream(): Boolean /** * Return error message if failed */ fun setUpstream(url: String?, branch: String? = null) fun <R> read(path: String, consumer: (InputStream?) -> R): R /** * Returns false if file is not written (for example, due to ignore rules). */ fun write(path: String, content: ByteArray, size: Int): Boolean fun delete(path: String): Boolean fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) /** * Not all implementations support progress indicator (will not be updated on progress). * * syncType will be passed if called before sync. * * If fixStateIfCannotCommit, repository state will be fixed before commit. */ fun commit(indicator: ProgressIndicator? = null, syncType: SyncType? = null, fixStateIfCannotCommit: Boolean = true): Boolean fun getAheadCommitsCount(): Int fun push(indicator: ProgressIndicator? = null) fun fetch(indicator: ProgressIndicator? = null): Updater fun pull(indicator: ProgressIndicator? = null): UpdateResult? fun has(path: String): Boolean fun resetToTheirs(indicator: ProgressIndicator): UpdateResult? fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?): UpdateResult? fun canCommit(): Boolean interface Updater { fun merge(): UpdateResult? // valid only if merge was called before val definitelySkipPush: Boolean } } interface UpdateResult { val changed: Collection<String> val deleted: Collection<String> } val EMPTY_UPDATE_RESULT: ImmutableUpdateResult = ImmutableUpdateResult(Collections.emptySet(), Collections.emptySet()) data class ImmutableUpdateResult(override val changed: Collection<String>, override val deleted: Collection<String>) : UpdateResult { fun toMutable(): MutableUpdateResult = MutableUpdateResult(changed, deleted) } class MutableUpdateResult(changed: Collection<String>, deleted: Collection<String>) : UpdateResult { override val changed: THashSet<String> = THashSet(changed) override val deleted: THashSet<String> = THashSet(deleted) fun add(result: UpdateResult?): MutableUpdateResult { if (result != null) { add(result.changed, result.deleted) } return this } fun add(newChanged: Collection<String>, newDeleted: Collection<String>): MutableUpdateResult { changed.removeAll(newDeleted) deleted.removeAll(newChanged) changed.addAll(newChanged) deleted.addAll(newDeleted) return this } fun addChanged(newChanged: Collection<String>): MutableUpdateResult { deleted.removeAll(newChanged) changed.addAll(newChanged) return this } } fun UpdateResult?.isEmpty(): Boolean = this == null || (changed.isEmpty() && deleted.isEmpty()) fun UpdateResult?.concat(result: UpdateResult?): UpdateResult? { if (result.isEmpty()) { return this } else if (isEmpty()) { return result } else { this!! return MutableUpdateResult(changed, deleted).add(result!!) } } class AuthenticationException(cause: Throwable) : RuntimeException(cause.message, cause)
apache-2.0
4a1fab5c87d257c6353c85d5aceb8989
28.568345
134
0.730591
4.53032
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt
1
19863
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth.jwt import com.auth0.jwk.* import com.auth0.jwt.* import com.auth0.jwt.algorithms.* import com.nhaarman.mockito_kotlin.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.Principal import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.* import java.security.* import java.security.interfaces.* import java.util.concurrent.* import kotlin.test.* @Suppress("DEPRECATION") class JWTAuthTest { @Test fun testJwtNoAuth() { withApplication { application.configureServerJwt() val response = handleRequest { uri = "/" } verifyResponseUnauthorized(response) } } @Test fun testJwtNoAuthCustomChallengeNoToken() { withApplication { application.configureServerJwt { challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom1", Charsets.UTF_8))) } } val response = handleRequest { uri = "/" } verifyResponseUnauthorized(response) assertEquals("Basic realm=custom1, charset=UTF-8", response.response.headers[HttpHeaders.WWWAuthenticate]) } } @Test fun testJwtMultipleNoAuthCustomChallengeNoToken() { withApplication { application.configureServerJwt { challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom1", Charsets.UTF_8))) } } val response = handleRequest { uri = "/" } verifyResponseUnauthorized(response) assertEquals("Basic realm=custom1, charset=UTF-8", response.response.headers[HttpHeaders.WWWAuthenticate]) } } @Test fun testJwtWithMultipleConfigurations() { val validated = mutableSetOf<String>() var currentPrincipal: (JWTCredential) -> Principal? = { null } withApplication { application.install(Authentication) { jwt(name = "first") { realm = "realm1" verifier(issuer, audience, algorithm) validate { validated.add("1"); currentPrincipal(it) } challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom1", Charsets.UTF_8))) } } jwt(name = "second") { realm = "realm2" verifier(issuer, audience, algorithm) validate { validated.add("2"); currentPrincipal(it) } challenge { _, _ -> call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge("custom2", Charsets.UTF_8))) } } } application.routing { authenticate("first", "second") { get("/") { val principal = call.authentication.principal<JWTPrincipal>()!! call.respondText("Secret info, ${principal.audience}") } } } val token = getToken() handleRequestWithToken(token).let { call -> verifyResponseUnauthorized(call) assertEquals( "Basic realm=custom1, charset=UTF-8", call.response.headers[HttpHeaders.WWWAuthenticate] ) } assertEquals(setOf("1", "2"), validated) currentPrincipal = { JWTPrincipal(it.payload) } validated.clear() handleRequestWithToken(token).let { call -> assertEquals(HttpStatusCode.OK, call.response.status()) assertEquals( "Secret info, [$audience]", call.response.content ) assertNull(call.response.headers[HttpHeaders.WWWAuthenticate]) } assertEquals(setOf("1"), validated) } } @Test fun testJwtSuccess() { withApplication { application.configureServerJwt() val token = getToken() val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwtSuccessWithCustomScheme() { withApplication { application.configureServerJwt { authSchemes("Bearer", "Token") } val token = getToken(scheme = "Token") val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwtSuccessWithCustomSchemeWithDifferentCases() { withApplication { application.configureServerJwt { authSchemes("Bearer", "tokEN") } val token = getToken(scheme = "TOKen") val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwtAlgorithmMismatch() { withApplication { application.configureServerJwt() val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false")) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwtAudienceMismatch() { withApplication { application.configureServerJwt() val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwtIssuerMismatch() { withApplication { application.configureServerJwt() val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkNoAuth() { withApplication { application.configureServerJwk() val response = handleRequest { uri = "/" } verifyResponseUnauthorized(response) } } @Test fun testJwkSuccess() { withApplication { application.configureServerJwk(mock = true) val token = getJwkToken() val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwkSuccessNoIssuer() { withApplication { application.configureServerJwkNoIssuer(mock = true) val token = getJwkToken() val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwkSuccessWithLeeway() { withApplication { application.configureServerJwtWithLeeway(mock = true) val token = getJwkToken() val response = handleRequestWithToken(token) assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } } @Test fun testJwtAuthSchemeMismatch() { withApplication { application.configureServerJwt() val token = getToken().removePrefix("Bearer ") val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwtAuthSchemeMismatch2() { withApplication { application.configureServerJwt() val token = getToken("Token") val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwtAuthSchemeMistake() { withApplication { application.configureServerJwt() val token = getToken().replace("Bearer", "Bearer:") val response = handleRequestWithToken(token) verifyResponseBadRequest(response) } } @Test fun testJwtBlobPatternMismatch() { withApplication { application.configureServerJwt() val token = getToken().let { val i = it.length - 2 it.replaceRange(i..i + 1, " ") } val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkAuthSchemeMismatch() { withApplication { application.configureServerJwk(mock = true) val token = getJwkToken(false) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkAuthSchemeMistake() { withApplication { application.configureServerJwk(mock = true) val token = getJwkToken(true).replace("Bearer", "Bearer:") val response = handleRequestWithToken(token) verifyResponseBadRequest(response) } } @Test fun testJwkBlobPatternMismatch() { withApplication { application.configureServerJwk(mock = true) val token = getJwkToken(true).let { val i = it.length - 2 it.replaceRange(i..i + 1, " ") } val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkAlgorithmMismatch() { withApplication { application.configureServerJwk(mock = true) val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false")) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkAudienceMismatch() { withApplication { application.configureServerJwk(mock = true) val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkIssuerMismatch() { withApplication { application.configureServerJwk(mock = true) val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkKidMismatch() { withApplication { application.configureServerJwk(mock = true) val token = "Bearer " + JWT.create() .withAudience(audience) .withIssuer(issuer) .withKeyId("wrong") .sign(jwkAlgorithm) val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkInvalidToken() { withApplication { application.configureServerJwk(mock = true) val token = "Bearer wrong" val response = handleRequestWithToken(token) verifyResponseUnauthorized(response) } } @Test fun testJwkInvalidTokenCustomChallenge() { withApplication { application.configureServerJwk(mock = true, challenge = true) val token = "Bearer wrong" val response = handleRequestWithToken(token) verifyResponseForbidden(response) } } @Test fun verifyWithMock() { val token = getJwkToken(prefix = false) val provider = getJwkProviderMock() val kid = JWT.decode(token).keyId val jwk = provider.get(kid) val algorithm = jwk.makeAlgorithm() val verifier = JWT.require(algorithm).withIssuer(issuer).build() verifier.verify(token) } @Test fun verifyNullAlgorithmWithMock() { val token = getJwkToken(prefix = false) val provider = getJwkProviderNullAlgorithmMock() val kid = JWT.decode(token).keyId val jwk = provider.get(kid) val algorithm = jwk.makeAlgorithm() val verifier = JWT.require(algorithm).withIssuer(issuer).build() verifier.verify(token) } @Test fun authHeaderFromCookie(): Unit = withApplication { application.configureServer { jwt { [email protected] = [email protected] authHeader { call -> call.request.cookies["JWT"]?.let { parseAuthorizationHeader(it) } } verifier(issuer, audience, algorithm) validate { jwt -> JWTPrincipal(jwt.payload) } } } val token = getToken() val response = handleRequest { uri = "/" addHeader(HttpHeaders.Cookie, "JWT=${token.encodeURLParameter()}") } assertEquals(HttpStatusCode.OK, response.response.status()) assertNotNull(response.response.content) } private fun verifyResponseUnauthorized(response: TestApplicationCall) { assertEquals(HttpStatusCode.Unauthorized, response.response.status()) assertNull(response.response.content) } private fun verifyResponseBadRequest(response: TestApplicationCall) { assertEquals(HttpStatusCode.BadRequest, response.response.status()) assertNull(response.response.content) } private fun verifyResponseForbidden(response: TestApplicationCall) { assertEquals(HttpStatusCode.Forbidden, response.response.status()) assertNull(response.response.content) } private fun TestApplicationEngine.handleRequestWithToken(token: String): TestApplicationCall { return handleRequest { uri = "/" addHeader(HttpHeaders.Authorization, token) } } private fun Application.configureServerJwk(mock: Boolean = false, challenge: Boolean = false) = configureServer { jwt { [email protected] = [email protected] if (mock) { verifier(getJwkProviderMock()) } else { verifier(issuer) } validate { credential -> when { credential.audience.contains(audience) -> JWTPrincipal(credential.payload) else -> null } } if (challenge) { challenge { defaultScheme, realm -> call.respond( ForbiddenResponse( HttpAuthHeader.Parameterized( defaultScheme, mapOf(HttpAuthHeader.Parameters.Realm to realm) ) ) ) } } } } private fun Application.configureServerJwkNoIssuer(mock: Boolean = false) = configureServer { jwt { [email protected] = [email protected] if (mock) { verifier(getJwkProviderMock()) } else { verifier(issuer) } verifier(if (mock) getJwkProviderMock() else makeJwkProvider()) validate { credential -> when { credential.audience.contains(audience) -> JWTPrincipal(credential.payload) else -> null } } } } private fun Application.configureServerJwtWithLeeway(mock: Boolean = false) = configureServer { jwt { [email protected] = [email protected] if (mock) { verifier(getJwkProviderMock()) { acceptLeeway(5) } } else { verifier(issuer) { acceptLeeway(5) } } validate { credential -> when { credential.audience.contains(audience) -> JWTPrincipal(credential.payload) else -> null } } } } private fun Application.configureServerJwt(extra: JWTAuthenticationProvider.Config.() -> Unit = {}) = configureServer { jwt { [email protected] = [email protected] verifier(issuer, audience, algorithm) validate { credential -> when { credential.audience.contains(audience) -> JWTPrincipal(credential.payload) else -> null } } extra() } } private fun Application.configureServer(authBlock: (AuthenticationConfig.() -> Unit)) { install(Authentication) { authBlock(this) } routing { authenticate { get("/") { val principal = call.authentication.principal<JWTPrincipal>()!! principal.payload call.respondText("Secret info") } } } } private val algorithm = Algorithm.HMAC256("secret") private val keyPair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048, SecureRandom()) }.generateKeyPair() private val jwkAlgorithm = Algorithm.RSA256(keyPair.public as RSAPublicKey, keyPair.private as RSAPrivateKey) private val issuer = "https://jwt-provider-domain/" private val audience = "jwt-audience" private val realm = "ktor jwt auth test" private fun makeJwkProvider(): JwkProvider = JwkProviderBuilder(issuer) .cached(10, 24, TimeUnit.HOURS) .rateLimited(10, 1, TimeUnit.MINUTES) .build() private val kid = "NkJCQzIyQzRBMEU4NjhGNUU4MzU4RkY0M0ZDQzkwOUQ0Q0VGNUMwQg" private fun getJwkProviderNullAlgorithmMock(): JwkProvider { val jwk = mock<Jwk> { on { publicKey } doReturn keyPair.public } return mock { on { get(kid) } doReturn jwk } } private fun getJwkProviderMock(): JwkProvider { val jwk = mock<Jwk> { on { algorithm } doReturn jwkAlgorithm.name on { publicKey } doReturn keyPair.public } return mock { on { get(kid) } doReturn jwk on { get("wrong") } doThrow (SigningKeyNotFoundException("Key not found", null)) } } private fun getJwkToken(prefix: Boolean = true): String = (if (prefix) "Bearer " else "") + JWT.create() .withAudience(audience) .withIssuer(issuer) .withKeyId(kid) .sign(jwkAlgorithm) private fun getToken(scheme: String = "Bearer"): String = "$scheme " + JWT.create() .withAudience(audience) .withIssuer(issuer) .sign(algorithm) }
apache-2.0
2590644cfec2a133fb689ce9b76360d7
30.7808
120
0.566732
5.161902
false
true
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/KobaltExecutors.kt
1
2591
package com.beust.kobalt.misc import java.util.concurrent.* class NamedThreadFactory(val n: String) : ThreadFactory { private val PREFIX = "K-" public val name: String get() = PREFIX + n override public fun newThread(r: Runnable) : Thread { val result = Thread(r) result.name = name + "-" + result.id return result } } class KobaltExecutor(name: String, threadCount: Int) : ThreadPoolExecutor(threadCount, threadCount, 5L, TimeUnit.SECONDS, LinkedBlockingQueue<Runnable>(), NamedThreadFactory(name)) { override protected fun afterExecute(r: Runnable, t: Throwable?) { super.afterExecute(r, t) var ex : Throwable? = null if (t == null && r is Future<*>) { try { if (r.isDone) r.get(); } catch (ce: CancellationException) { ex = ce; } catch (ee: ExecutionException) { ex = ee.cause; } catch (ie: InterruptedException) { Thread.currentThread().interrupt(); // ignore/reset } } if (ex != null) { error(ex.toString(), ex) } } } public class KobaltExecutors { public fun newExecutor(name: String, threadCount: Int) : ExecutorService = KobaltExecutor(name, threadCount) val dependencyExecutor = newExecutor("Dependency", 5) val miscExecutor = newExecutor("Misc", 2) fun shutdown() { dependencyExecutor.shutdown() miscExecutor.shutdown() } fun <T> completionService(name: String, threadCount: Int, maxMs: Long, tasks: List<Callable<T>>, progress: (T) -> Unit = {}) : List<T> { val result = arrayListOf<T>() val executor = newExecutor(name, threadCount) val cs = ExecutorCompletionService<T>(executor) tasks.map { cs.submit(it) } var remainingMs = maxMs var i = 0 while (i < tasks.size && remainingMs >= 0) { var start = System.currentTimeMillis() val r = cs.take().get(remainingMs, TimeUnit.MILLISECONDS) progress(r) result.add(r) remainingMs -= (System.currentTimeMillis() - start) log(2, "Received $r, remaining: $remainingMs ms") i++ } if (remainingMs < 0) { warn("Didn't receive all the results in time: $i / ${tasks.size}") } else { log(2, "Received all results in ${maxMs - remainingMs} ms") } executor.shutdown() return result } }
apache-2.0
dff542cfac20f48b02ee25ac3517e016
30.216867
100
0.563875
4.347315
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/ChapterTypeMapping.kt
2
4079
package eu.kanade.tachiyomi.data.database.mappers import android.database.Cursor import androidx.core.content.contentValuesOf import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.InsertQuery import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.ChapterImpl import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_BOOKMARK import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_CHAPTER_NUMBER import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_DATE_FETCH import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_DATE_UPLOAD import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_ID import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_LAST_PAGE_READ import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_MANGA_ID import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_NAME import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_READ import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_SCANLATOR import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_SOURCE_ORDER import eu.kanade.tachiyomi.data.database.tables.ChapterTable.COL_URL import eu.kanade.tachiyomi.data.database.tables.ChapterTable.TABLE class ChapterTypeMapping : SQLiteTypeMapping<Chapter>( ChapterPutResolver(), ChapterGetResolver(), ChapterDeleteResolver() ) class ChapterPutResolver : DefaultPutResolver<Chapter>() { override fun mapToInsertQuery(obj: Chapter) = InsertQuery.builder() .table(TABLE) .build() override fun mapToUpdateQuery(obj: Chapter) = UpdateQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() override fun mapToContentValues(obj: Chapter) = contentValuesOf( COL_ID to obj.id, COL_MANGA_ID to obj.manga_id, COL_URL to obj.url, COL_NAME to obj.name, COL_READ to obj.read, COL_SCANLATOR to obj.scanlator, COL_BOOKMARK to obj.bookmark, COL_DATE_FETCH to obj.date_fetch, COL_DATE_UPLOAD to obj.date_upload, COL_LAST_PAGE_READ to obj.last_page_read, COL_CHAPTER_NUMBER to obj.chapter_number, COL_SOURCE_ORDER to obj.source_order ) } class ChapterGetResolver : DefaultGetResolver<Chapter>() { override fun mapFromCursor(cursor: Cursor): Chapter = ChapterImpl().apply { id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_ID)) manga_id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_MANGA_ID)) url = cursor.getString(cursor.getColumnIndexOrThrow(COL_URL)) name = cursor.getString(cursor.getColumnIndexOrThrow(COL_NAME)) scanlator = cursor.getString(cursor.getColumnIndexOrThrow(COL_SCANLATOR)) read = cursor.getInt(cursor.getColumnIndexOrThrow(COL_READ)) == 1 bookmark = cursor.getInt(cursor.getColumnIndexOrThrow(COL_BOOKMARK)) == 1 date_fetch = cursor.getLong(cursor.getColumnIndexOrThrow(COL_DATE_FETCH)) date_upload = cursor.getLong(cursor.getColumnIndexOrThrow(COL_DATE_UPLOAD)) last_page_read = cursor.getInt(cursor.getColumnIndexOrThrow(COL_LAST_PAGE_READ)) chapter_number = cursor.getFloat(cursor.getColumnIndexOrThrow(COL_CHAPTER_NUMBER)) source_order = cursor.getInt(cursor.getColumnIndexOrThrow(COL_SOURCE_ORDER)) } } class ChapterDeleteResolver : DefaultDeleteResolver<Chapter>() { override fun mapToDeleteQuery(obj: Chapter) = DeleteQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() }
apache-2.0
5b05e742f9bd6c4c12f1e42647ba14d7
45.352273
90
0.747732
4.058706
false
false
false
false
Wilm0r/giggity
app/src/main/java/net/gaast/giggity/OkapiBM25.kt
1
2546
/* * MIT License * * Copyright (c) 2018 Pablo Pallocchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN */ package com.github.movies import kotlin.math.log class OkapiBM25 { companion object { fun score(matchinfo: Array<Int>, column: Int): Double { val b = 0.75 val k1 = 1.2 val pOffset = 0 val cOffset = 1 val nOffset = 2 val aOffset = 3 val termCount = matchinfo[pOffset] val colCount = matchinfo[cOffset] val lOffset = aOffset + colCount val xOffset = lOffset + colCount val totalDocs = matchinfo[nOffset].toDouble() val avgLength = matchinfo[aOffset + column].toDouble() val docLength = matchinfo[lOffset + column].toDouble() var score = 0.0 for (i in 0 until termCount) { val currentX = xOffset + (3 * (column + i * colCount)) val termFrequency = matchinfo[currentX].toDouble() val docsWithTerm = matchinfo[currentX + 2].toDouble() val p = totalDocs - docsWithTerm + 0.5 val q = docsWithTerm + 0.5 val idf = log(p,q) val r = termFrequency * (k1 + 1) val s = b * (docLength / avgLength) val t = termFrequency + (k1 * (1 - b + s)) val rightSide = r/t score += (idf * rightSide) } return score } } }
gpl-2.0
99a25d06eeb93a62b2439a5b2cdcae19
31.974026
80
0.613081
4.391003
false
false
false
false
cqjjjzr/Gensokyo
src/main/kotlin/charlie/gensokyo/ComponentExtension.kt
1
2031
@file:JvmName("Gensokyo") @file:JvmMultifileClass package charlie.gensokyo import java.awt.Component import java.awt.Container import java.awt.Dimension import java.awt.Point import javax.swing.JButton import javax.swing.JComponent import javax.swing.JTextField fun Component.size(width: Int, height: Int) = setSize(width, height) fun Component.minSize(width: Int, height: Int) { minimumSize = Dimension(width, height) } fun Component.maxSize(width: Int, height: Int) { maximumSize = Dimension(width, height) } fun Component.location(x: Int, y: Int) = setLocation(x, y) inline fun Component.size(block: Dimension.() -> Unit) { size = Dimension().apply(block) } inline fun Component.minSize(block: Dimension.() -> Unit) { minimumSize = Dimension().apply(block) } inline fun Component.maxSize(block: Dimension.() -> Unit) { maximumSize = Dimension().apply(block) } inline fun Component.location(block: Point.() -> Unit) { location = Point().apply(block) } val Component.show: Unit get() { isVisible = true } val Component.hide: Unit get() { isVisible = false } operator fun JComponent.contains(key: Any) = getClientProperty(key) != null operator fun JComponent.get(key: Any) = getClientProperty(key) ?: "" operator fun JComponent.set(key: Any, value: Any) = putClientProperty(key, value) const val gensokyoId = "Gensokyo.CompID" fun JComponent.assignID(ID: String) { this[gensokyoId] = ID } fun Container.componentFromID(ID: String): JComponent { fun findInContainer(container: Container): JComponent? { container.components.forEach { if (it is JComponent && it[gensokyoId] == ID) return it if (it is Container) findInContainer(it).apply { if (this != null) return this } } return null } return findInContainer(this) ?: throw NoSuchElementException(ID) } fun Container.textFieldFromID(ID: String) = componentFromID(ID) as JTextField fun Container.buttonFromID(ID: String) = componentFromID(ID) as JButton
apache-2.0
6db00514490032cc62bcd858a44ee5b9
29.787879
81
0.708518
3.733456
false
false
false
false
retomerz/intellij-community
plugins/settings-repository/src/settings/upstreamEditor.kt
2
4191
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ArrayUtil import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP import java.awt.Container import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action internal fun checkUrl(url: String?): Boolean { try { return url != null && url.length > 1 && icsManager.repositoryService.checkUrl(url, false) } catch (e: Throwable) { return false } } fun updateSyncButtonState(url: String?, syncActions: Array<Action>) { val enabled = checkUrl(url) for (syncAction in syncActions) { syncAction.isEnabled = enabled; } } fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogParent: Container, okAction: (() -> Unit)): Array<Action> { var syncTypes = SyncType.values() if (SystemInfo.isMac) { syncTypes = ArrayUtil.reverseArray(syncTypes) } val icsManager = icsManager return Array(3) { val syncType = syncTypes[it] object : AbstractAction(icsMessage("action.${if (syncType == SyncType.MERGE) "Merge" else (if (syncType == SyncType.OVERWRITE_LOCAL) "ResetToTheirs" else "ResetToMy")}Settings.text")) { private fun saveRemoteRepositoryUrl(): Boolean { val url = StringUtil.nullize(urlTextField.text) if (url != null && !icsManager.repositoryService.checkUrl(url, true, project)) { return false } val repositoryManager = icsManager.repositoryManager repositoryManager.createRepositoryIfNeed() repositoryManager.setUpstream(url, null) return true } override fun actionPerformed(event: ActionEvent) { val repositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists() var upstreamSet = false try { if (!saveRemoteRepositoryUrl()) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } return } upstreamSet = true if (repositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) { ApplicationManager.getApplication().saveSettings() icsManager.sync(syncType, project, { copyLocalConfig() }) } else { icsManager.sync(syncType, project, null) } } catch (e: Throwable) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } LOG.warn(e) if (!upstreamSet || e is NoRemoteRepositoryException) { Messages.showErrorDialog(dialogParent, icsMessage("set.upstream.failed.message", e.message), icsMessage("set.upstream.failed.title")) } else { Messages.showErrorDialog(dialogParent, StringUtil.notNullize(e.message, "Internal error"), icsMessage(if (e is AuthenticationException) "sync.not.authorized.title" else "sync.rejected.title")) } return } NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project) okAction() } } } }
apache-2.0
d217d6db3f83578374709271b2d85f78
35.137931
204
0.69172
4.708989
false
false
false
false
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/ui/AddressBookAdapter.kt
2
1921
// Copyright (c) 2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.gulden.jniunifiedbackend.AddressRecord import com.gulden.unity_wallet.R import com.gulden.unity_wallet.UnityCore import kotlinx.android.synthetic.main.address_book_list_item.view.* class AddressBookAdapter(private var dataSource: ArrayList<AddressRecord>, val onItemClick: (position: Int, address: AddressRecord) -> Unit) : RecyclerView.Adapter<AddressBookAdapter.MyViewHolder>() { fun updateDataSource(newDataSource: ArrayList<AddressRecord>) { dataSource = newDataSource notifyDataSetChanged() } class MyViewHolder(val view: View): RecyclerView.ViewHolder(view) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.address_book_list_item, parent, false) // set the view's size, margins, padding and layout parameters return MyViewHolder(view) } override fun getItemCount(): Int { return dataSource.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val view = holder.itemView val addressRecord = dataSource[position] view.textViewLabel.text = addressRecord.name view.setOnClickListener { onItemClick(position, addressRecord) } } override fun getItemId(position: Int): Long { return position.toLong() } fun removeAt(position: Int) { UnityCore.instance.deleteAddressBookRecord(dataSource[position]) } }
mit
4bb9706f79e996895c870d803e7895e3
33.927273
200
0.727746
4.477855
false
false
false
false
Sefford/brender
modules/brender-core/src/test/kotlin/com/sefford/brender/data/FilterableAdapterDataTest.kt
1
2597
/* * Copyright (C) 2015 Saúl Díaz * * 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.sefford.brender.data import android.widget.Filter import com.sefford.brender.components.Renderable import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.MockitoAnnotations.initMocks import org.robolectric.RobolectricTestRunner import java.util.* @RunWith(RobolectricTestRunner::class) class FilterableAdapterDataTest { @Mock lateinit var element: Renderable lateinit var master: MutableList<Renderable> lateinit var filtered: MutableList<Renderable> lateinit var adapterData: FilterableAdapterData @Before @Throws(Exception::class) fun setUp() { initMocks(this) master = mutableListOf(element, element, element) filtered = ArrayList() filtered.add(element) adapterData = object : FilterableAdapterData(master) { override val viewTypeCount: Int get() = 0 override fun notifyDataSetChanged() { } override fun performFiltering(constraint: CharSequence): Filter.FilterResults { val results = Filter.FilterResults() results.count = filtered.size results.values = filtered return results } } adapterData.filter("") } @Test @Throws(Exception::class) fun testSize() { assertEquals(master.size.toLong(), adapterData.size().toLong()) } @Test @Throws(Exception::class) fun testGetItemId() { assertEquals(EXPECTED_POS.toLong(), adapterData.getItemId(EXPECTED_POS)) } @Test @Throws(Exception::class) fun testGetItem() { assertEquals(element, adapterData.getItem(EXPECTED_POS)) } @Test @Throws(Exception::class) fun testGetFilter() { assertEquals(adapterData, adapterData.filter) } companion object { private val EXPECTED_POS = 1 } }
apache-2.0
74ca231990956048838e8a052bd30bc7
26.315789
91
0.675145
4.59292
false
true
false
false
psanders/sipio
src/main/kotlin/io/routr/core/Launcher.kt
1
3021
package io.routr.core import io.routr.util.getVersion import java.io.IOException import java.util.* import kotlin.system.exitProcess import org.apache.logging.log4j.LogManager import org.graalvm.polyglot.Context import org.graalvm.polyglot.HostAccess /** * @author Pedro Sanders * @since v1 */ class Launcher { @Throws(IOException::class, InterruptedException::class) fun launch() { val mainCtx = createJSContext(serverRunner, "server") val registryCtx = createJSContext(registryRunner, "reg") val routeLoaderCtx = createJSContext(routeLoaderRunner, "loader") // createJSContext(restRunner, "nop") val server = GRPCServer(mainCtx) val timer = Timer() timer.schedule( object : TimerTask() { override fun run() { // If it was null the error was reported already, but still need to // consider that the object was never created registryCtx.eval("js", "reg && reg.registerAll()") } }, 10 * 1000.toLong(), 60 * 1000.toLong() ) timer.schedule( object : TimerTask() { override fun run() { routeLoaderCtx.eval("js", "loader.loadStaticRoutes()") } }, 0, 120 * 1000.toLong() ) RestServer().start() server.start() server.blockUntilShutdown() } private fun createJSContext(src: String?, `var`: String?): Context { val ctx = Context.newBuilder("js") .allowExperimentalOptions(true) .allowIO(true) .allowHostClassLookup { true } .allowHostAccess(HostAccess.ALL) // .allowCreateThread(true) .build() ctx.eval("js", baseScript) ctx.getBindings("js").putMember(`var`, null) try { ctx.eval("js", src) } catch (ex: Exception) { LOG.error(ex.message) } return ctx } companion object { private val LOG = LogManager.getLogger(Launcher::class.java) private const val serverRunner = "load(System.getProperty('user.dir') + '/libs/server.bundle.js')" private const val routeLoaderRunner = "load(System.getProperty('user.dir') + '/libs/route_loader.bundle.js');" private const val registryRunner = "load(System.getProperty('user.dir') + '/libs/registry.bundle.js')" // private const val restRunner = "load(System.getProperty('user.dir') + // '/libs/rest.bundle.js')" private val baseScript = java.lang.String.join( System.getProperty("line.separator"), "var System = Java.type('java.lang.System')" ) @Throws(IOException::class, InterruptedException::class) @JvmStatic fun main(args: Array<String>) { // Checks Java version and show error if 8 < version > 11 val javaVersion = getVersion() if (javaVersion > 11 || javaVersion < 8) { LOG.fatal("Routr is only supported in Java versions 8 through 11") exitProcess(1) } Launcher().launch() } } }
mit
e00be306b9cac5d909509a0f35cc8701
28.617647
80
0.617676
4.028
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/bean/internship/release/InternshipReleaseBean.kt
1
1121
package top.zbeboy.isy.web.bean.internship.release import top.zbeboy.isy.domain.tables.pojos.InternshipRelease import top.zbeboy.isy.domain.tables.pojos.Science /** * Created by zbeboy 2017-12-18 . **/ class InternshipReleaseBean: InternshipRelease() { var departmentName: String? = null var schoolName: String? = null var collegeName: String? = null var internshipTypeName: String? = null var sciences: List<Science>? = null var schoolId: Int? = 0 var collegeId: Int? = 0 var teacherDistributionStartTimeStr: String? = null var teacherDistributionEndTimeStr: String? = null var startTimeStr: String? = null var endTimeStr: String? = null var releaseTimeStr: String? = null // 实习审核 统计总数 var waitTotalData: Int? = 0 var passTotalData: Int? = 0 var failTotalData: Int? = 0 var basicApplyTotalData: Int? = 0 var companyApplyTotalData: Int? = 0 var basicFillTotalData: Int? = 0 var companyFillTotalData: Int? = 0 // 实习统计 统计总数 var submittedTotalData: Int? = 0 var unsubmittedTotalData: Int? = 0 }
mit
97b959057a68e8834515d04851b0f3cb
30.142857
59
0.697888
3.691525
false
false
false
false
paplorinc/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUQualifiedReferenceExpression.kt
4
2057
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiElement import com.intellij.psi.PsiJavaCodeReferenceElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.ResolveResult import org.jetbrains.uast.* class JavaUQualifiedReferenceExpression( override val psi: PsiJavaCodeReferenceElement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UQualifiedReferenceExpression, UMultiResolvable { override val receiver: UExpression by lz { psi.qualifier?.let { JavaConverter.convertPsiElement(it, this) as? UExpression } ?: UastEmptyExpression(this) } override val selector: JavaUSimpleNameReferenceExpression by lz { JavaUSimpleNameReferenceExpression(psi.referenceNameElement, psi.referenceName ?: "<error>", this, psi) } override val accessType: UastQualifiedExpressionAccessType get() = UastQualifiedExpressionAccessType.SIMPLE override val resolvedName: String? get() = (psi.resolve() as? PsiNamedElement)?.name override fun resolve(): PsiElement? = psi.resolve() override fun multiResolve(): Iterable<ResolveResult> = psi.multiResolve(false).asIterable() } internal fun UElement.unwrapCompositeQualifiedReference(uParent: UElement?): UElement? = when (uParent) { is UQualifiedReferenceExpression -> { if (uParent.receiver == this || uParent.selector == this) uParent else uParent.selector as? JavaUCallExpression ?: uParent.uastParent } else -> uParent }
apache-2.0
c86384db7d4ddd2dba1e474dc3511f0b
36.418182
113
0.769081
4.750577
false
false
false
false
marcplouhinec/trust-service-reputation
src/test/kotlin/fr/marcsworld/service/AgencyServiceTest.kt
1
19741
package fr.marcsworld.service import fr.marcsworld.enums.AgencyType import fr.marcsworld.enums.DocumentType import fr.marcsworld.model.entity.Agency import fr.marcsworld.model.entity.AgencyName import fr.marcsworld.model.entity.Document import fr.marcsworld.repository.AgencyRepository import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.core.io.ClassPathResource import org.springframework.test.context.junit4.SpringRunner import javax.persistence.EntityManager import javax.persistence.PersistenceContext import javax.transaction.Transactional /** * Test for the [AgencyService]. * * @author Marc Plouhinec */ @RunWith(SpringRunner::class) @SpringBootTest @Transactional open class AgencyServiceTest { @PersistenceContext lateinit var entityManager: EntityManager @Autowired lateinit var agencyService : AgencyService @Autowired lateinit var documentParsingService: DocumentParsingService @Autowired lateinit var agencyRepository: AgencyRepository @Test fun testUpdateTrustServiceListOperatorAgencyWithEuropeanCommissionAgency() { val tsStatusListEuResource = ClassPathResource("ts_status_list_eu.xml") val topAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(topAgency) entityManager.flush() entityManager.clear() // Check the top agency has been updated val persistedTopAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertNull(persistedTopAgency.parentAgency) Assert.assertEquals(AgencyType.TRUST_SERVICE_LIST_OPERATOR, persistedTopAgency.type) Assert.assertNull(persistedTopAgency.referencedByDocumentUrl) Assert.assertNull(persistedTopAgency.isStillReferencedByDocument) Assert.assertEquals(23, persistedTopAgency.names.size) Assert.assertEquals(persistedTopAgency, persistedTopAgency.names[0].agency) Assert.assertEquals("en", persistedTopAgency.names[0].languageCode) Assert.assertEquals("European Commission", persistedTopAgency.names[0].name) Assert.assertEquals(1, persistedTopAgency.providingDocuments.size) Assert.assertEquals("https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml", persistedTopAgency.providingDocuments[0].url) Assert.assertEquals(DocumentType.TS_STATUS_LIST_XML, persistedTopAgency.providingDocuments[0].type) Assert.assertEquals("en", persistedTopAgency.providingDocuments[0].languageCode) Assert.assertEquals(persistedTopAgency, persistedTopAgency.providingDocuments[0].providedByAgency) Assert.assertEquals(true, persistedTopAgency.providingDocuments[0].isStillProvidedByAgency) Assert.assertEquals(31, persistedTopAgency.childrenAgencies.size) // Check the first child agency has been created val persistedChildAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("AT") ?: throw IllegalStateException() Assert.assertEquals(persistedTopAgency, persistedChildAgency.parentAgency) Assert.assertEquals(AgencyType.TRUST_SERVICE_LIST_OPERATOR, persistedChildAgency.type) Assert.assertEquals(tsStatusListEuResource.url.toString(), persistedChildAgency.referencedByDocumentUrl) Assert.assertEquals(true, persistedChildAgency.isStillReferencedByDocument) Assert.assertEquals(2, persistedChildAgency.names.size) Assert.assertEquals(persistedChildAgency, persistedChildAgency.names[0].agency) Assert.assertEquals("en", persistedChildAgency.names[0].languageCode) Assert.assertEquals("Rundfunk und Telekom Regulierungs-GmbH", persistedChildAgency.names[0].name) Assert.assertEquals(1, persistedChildAgency.providingDocuments.size) Assert.assertEquals("https://www.signatur.rtr.at/currenttl.xml", persistedChildAgency.providingDocuments[0].url) Assert.assertEquals(DocumentType.TS_STATUS_LIST_XML, persistedChildAgency.providingDocuments[0].type) Assert.assertEquals("en", persistedChildAgency.providingDocuments[0].languageCode) Assert.assertEquals(persistedChildAgency, persistedChildAgency.providingDocuments[0].providedByAgency) Assert.assertEquals(true, persistedChildAgency.providingDocuments[0].isStillProvidedByAgency) Assert.assertEquals(0, persistedChildAgency.childrenAgencies.size) } @Test fun testUpdateTrustServiceListOperatorAgencyWithMemberStateAgency() { val tsStatusListEuResource = ClassPathResource("ts_status_list_eu.xml") val euAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency) entityManager.flush() entityManager.clear() val tsStatusListFrResource = ClassPathResource("ts_status_list_fr.xml") val topAgency = documentParsingService.parseTsStatusList(tsStatusListFrResource) agencyService.updateTrustServiceListOperatorAgency(topAgency) entityManager.flush() entityManager.clear() // Check the top agency has been updated val persistedTopAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("FR") ?: throw IllegalStateException() val persistedEUAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(persistedEUAgency, persistedTopAgency.parentAgency) Assert.assertEquals(AgencyType.TRUST_SERVICE_LIST_OPERATOR, persistedTopAgency.type) Assert.assertEquals(tsStatusListEuResource.url.toString(), persistedTopAgency.referencedByDocumentUrl) Assert.assertEquals(true, persistedTopAgency.isStillReferencedByDocument) Assert.assertEquals(2, persistedTopAgency.names.size) Assert.assertEquals(persistedTopAgency, persistedTopAgency.names[0].agency) Assert.assertEquals("fr", persistedTopAgency.names[0].languageCode) Assert.assertEquals("Agence nationale de la sécurité des systèmes d'information (ANSSI)", persistedTopAgency.names[0].name) Assert.assertEquals(1, persistedTopAgency.providingDocuments.size) Assert.assertEquals("http://www.ssi.gouv.fr/eidas/TL-FR.xml", persistedTopAgency.providingDocuments[0].url) Assert.assertEquals(DocumentType.TS_STATUS_LIST_XML, persistedTopAgency.providingDocuments[0].type) Assert.assertEquals("en", persistedTopAgency.providingDocuments[0].languageCode) Assert.assertEquals(persistedTopAgency, persistedTopAgency.providingDocuments[0].providedByAgency) Assert.assertEquals(true, persistedTopAgency.providingDocuments[0].isStillProvidedByAgency) Assert.assertEquals(22, persistedTopAgency.childrenAgencies.size) // Check the first child agency has been created val persistedChildAgency = persistedTopAgency.childrenAgencies[0] Assert.assertEquals(persistedTopAgency, persistedChildAgency.parentAgency) Assert.assertEquals(AgencyType.TRUST_SERVICE_PROVIDER, persistedChildAgency.type) Assert.assertEquals(tsStatusListFrResource.url.toString(), persistedChildAgency.referencedByDocumentUrl) Assert.assertEquals(true, persistedChildAgency.isStillReferencedByDocument) Assert.assertEquals(2, persistedChildAgency.names.size) Assert.assertEquals(persistedChildAgency, persistedChildAgency.names[0].agency) Assert.assertEquals("en", persistedChildAgency.names[0].languageCode) Assert.assertEquals("Agence Nationale des Titres Sécurisés", persistedChildAgency.names[0].name) Assert.assertEquals(0, persistedChildAgency.providingDocuments.size) Assert.assertEquals(8, persistedChildAgency.childrenAgencies.size) // Check the first grand child agency has been created val persistedGrandChildAgency = persistedChildAgency.childrenAgencies[0] Assert.assertEquals(persistedChildAgency, persistedGrandChildAgency.parentAgency) Assert.assertEquals(AgencyType.TRUST_SERVICE, persistedGrandChildAgency.type) Assert.assertEquals(tsStatusListFrResource.url.toString(), persistedGrandChildAgency.referencedByDocumentUrl) Assert.assertEquals(true, persistedGrandChildAgency.isStillReferencedByDocument) Assert.assertEquals(2, persistedGrandChildAgency.names.size) Assert.assertEquals(persistedGrandChildAgency, persistedGrandChildAgency.names[0].agency) Assert.assertEquals("en", persistedGrandChildAgency.names[0].languageCode) Assert.assertEquals("Acteur de l'Administration d'Etat - Authentification 3 étoiles", persistedGrandChildAgency.names[0].name) Assert.assertEquals(2, persistedGrandChildAgency.providingDocuments.size) Assert.assertEquals("http://sp.ants.gouv.fr/antsv2/ANTS_AC_AAE_PC_v1.9.pdf", persistedGrandChildAgency.providingDocuments[0].url) Assert.assertEquals(DocumentType.TSP_SERVICE_DEFINITION, persistedGrandChildAgency.providingDocuments[0].type) Assert.assertEquals("fr", persistedGrandChildAgency.providingDocuments[0].languageCode) Assert.assertEquals(persistedGrandChildAgency, persistedGrandChildAgency.providingDocuments[0].providedByAgency) Assert.assertEquals(true, persistedGrandChildAgency.providingDocuments[0].isStillProvidedByAgency) Assert.assertEquals(0, persistedGrandChildAgency.childrenAgencies.size) // Check a special case when two agencies are merged into one val certinomisTSPAgency = topAgency.childrenAgencies.findLast { it.names.all { it.name == "Certinomis SA" } } ?: throw IllegalStateException() val persistedCertinomisTSPAgency = persistedTopAgency.childrenAgencies.findLast { it.names.all { it.name == "Certinomis SA" } } ?: throw IllegalStateException() Assert.assertEquals("The document contain 5 children of Certinomis.", 5, certinomisTSPAgency.childrenAgencies.size) Assert.assertEquals("Only 3 children of Certinomis were saved.", 3, persistedCertinomisTSPAgency.childrenAgencies.size) val certinomisPrimeTSAgencies = certinomisTSPAgency.childrenAgencies.filter { it.names.all { it.name == "Certinomis - Prime CA" } } val persistedCertinomisPrimeTSAgencies = persistedCertinomisTSPAgency.childrenAgencies.filter { it.names.all { it.name == "Certinomis - Prime CA" } } Assert.assertEquals(2, certinomisPrimeTSAgencies.size) Assert.assertEquals(1, persistedCertinomisPrimeTSAgencies.size) Assert.assertEquals(2, persistedCertinomisPrimeTSAgencies[0].names.size) val parsedDocuments = certinomisPrimeTSAgencies.flatMap { it.providingDocuments } val persistedDocuments = persistedCertinomisPrimeTSAgencies.flatMap { it.providingDocuments } val areAllParsedDocumentsPersisted = parsedDocuments.all { parsedDocument -> persistedDocuments.any { it.url == parsedDocument.url && it.languageCode == parsedDocument.languageCode } } Assert.assertTrue(areAllParsedDocumentsPersisted) } @Test fun testUpdateTrustServiceListOperatorAgencyWithMissingAndNewAgencyName() { // Populate the database with agencies val tsStatusListEuResource = ClassPathResource("ts_status_list_eu.xml") val euAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency) entityManager.flush() entityManager.clear() // Reload the same top agency, but add a new name and remove another one val modifiedEuAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) modifiedEuAgency.names = modifiedEuAgency.names.filter { it.languageCode != "fr" } // Remove the french name val englishAgencyName = modifiedEuAgency.names.findLast { it.languageCode == "en" } englishAgencyName?.name = "Modified name." // Modify the english name agencyService.updateTrustServiceListOperatorAgency(modifiedEuAgency) entityManager.flush() entityManager.clear() // Check the database was correctly updated val persistedEuAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(22, persistedEuAgency.names.size) Assert.assertNull(persistedEuAgency.names.findLast { it.languageCode == "fr" }) Assert.assertEquals("Modified name.", persistedEuAgency.names.findLast { it.languageCode == "en" }?.name) } @Test fun testUpdateTrustServiceListOperatorAgencyWithNewModifiedMissingAndFoundAgainDocument() { // Populate the database with agencies val tsStatusListEuResource = ClassPathResource("ts_status_list_eu.xml") val euAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency) entityManager.flush() entityManager.clear() // Reload the same agencies, but modify their documents val modifiedEuAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) modifiedEuAgency.childrenAgencies[0].providingDocuments += Document( // Add a new document to the first child agency url = "http://example.org", type = DocumentType.TS_STATUS_LIST_XML, languageCode = "en", providedByAgency = modifiedEuAgency.childrenAgencies[0] ) modifiedEuAgency.childrenAgencies[1].providingDocuments = listOf() // Remove the documents of the second child agency modifiedEuAgency.childrenAgencies[2].providingDocuments[0].languageCode = "zz" // Modify the document of the third child agency agencyService.updateTrustServiceListOperatorAgency(modifiedEuAgency) entityManager.flush() entityManager.clear() // Check the database was correctly updated val persistedEuAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(2, persistedEuAgency.childrenAgencies[0].providingDocuments.size) Assert.assertEquals("http://example.org", persistedEuAgency.childrenAgencies[0].providingDocuments[1].url) Assert.assertEquals(1, persistedEuAgency.childrenAgencies[1].providingDocuments.size) Assert.assertEquals(false, persistedEuAgency.childrenAgencies[1].providingDocuments[0].isStillProvidedByAgency) Assert.assertEquals(1, persistedEuAgency.childrenAgencies[2].providingDocuments.size) Assert.assertEquals("zz", persistedEuAgency.childrenAgencies[2].providingDocuments[0].languageCode) // Reload the same agencies again, but this time restore the original documents val euAgency2 = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency2) entityManager.flush() entityManager.clear() // Check the database was correctly updated val persistedEuAgency2 = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(1, persistedEuAgency2.childrenAgencies[1].providingDocuments.size) Assert.assertEquals(true, persistedEuAgency2.childrenAgencies[1].providingDocuments[0].isStillProvidedByAgency) } @Test fun testUpdateTrustServiceListOperatorAgencyWithNewModifiedMissingAndFoundAgainChildAgency() { // Populate the database with agencies val tsStatusListEuResource = ClassPathResource("ts_status_list_eu.xml") val euAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency) entityManager.flush() entityManager.clear() // Reload the same agencies, but modify the children: add a new agency, delete one and modify another val modifiedEuAgency = documentParsingService.parseTsStatusList(tsStatusListEuResource) val newAgency = Agency( parentAgency = modifiedEuAgency, type = AgencyType.TRUST_SERVICE_LIST_OPERATOR, referencedByDocumentUrl = "http://www.example.org", territoryCode = "ZZ" ) newAgency.names = listOf(AgencyName(agency = newAgency, name = "Example", languageCode = "en")) newAgency.providingDocuments = listOf(Document(url = "http://www.example.com", type = DocumentType.TS_STATUS_LIST_XML, languageCode = "en", providedByAgency = newAgency)) modifiedEuAgency.childrenAgencies += newAgency modifiedEuAgency.childrenAgencies = modifiedEuAgency.childrenAgencies.filter { it.territoryCode != "FR" } val atAgency = modifiedEuAgency.childrenAgencies.findLast { it.territoryCode == "AT" } atAgency?.referencedByDocumentUrl = "http://www.example.net" agencyService.updateTrustServiceListOperatorAgency(modifiedEuAgency) entityManager.flush() entityManager.clear() // Check the database was correctly updated val persistedEuAgency = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(32, persistedEuAgency.childrenAgencies.size) val lastChildAgency = persistedEuAgency.childrenAgencies[persistedEuAgency.childrenAgencies.size - 1] Assert.assertEquals("ZZ", lastChildAgency.territoryCode) Assert.assertEquals("http://www.example.org", lastChildAgency.referencedByDocumentUrl) Assert.assertEquals(AgencyType.TRUST_SERVICE_LIST_OPERATOR, lastChildAgency.type) Assert.assertEquals(persistedEuAgency, lastChildAgency.parentAgency) Assert.assertEquals(1, lastChildAgency.names.size) Assert.assertEquals("en", lastChildAgency.names[0].languageCode) Assert.assertEquals("Example", lastChildAgency.names[0].name) Assert.assertEquals(1, lastChildAgency.providingDocuments.size) Assert.assertEquals("en", lastChildAgency.providingDocuments[0].languageCode) Assert.assertEquals("http://www.example.com", lastChildAgency.providingDocuments[0].url) Assert.assertEquals(DocumentType.TS_STATUS_LIST_XML, lastChildAgency.providingDocuments[0].type) val frChildAgency = persistedEuAgency.childrenAgencies.findLast { it.territoryCode == "FR" } Assert.assertEquals(false, frChildAgency?.isStillReferencedByDocument) val atChildAgency = persistedEuAgency.childrenAgencies.findLast { it.territoryCode == "AT" } Assert.assertEquals("http://www.example.net", atChildAgency?.referencedByDocumentUrl) // Reload the same agencies again, but this time restore the original documents val euAgency2 = documentParsingService.parseTsStatusList(tsStatusListEuResource) agencyService.updateTrustServiceListOperatorAgency(euAgency2) entityManager.flush() entityManager.clear() // Check the database was correctly updated val persistedEuAgency2 = agencyRepository.findTrustServiceListOperatorByTerritoryCode("EU") ?: throw IllegalStateException() Assert.assertEquals(32, persistedEuAgency2.childrenAgencies.size) val frChildAgency2 = persistedEuAgency2.childrenAgencies.findLast { it.territoryCode == "FR" } Assert.assertEquals(true, frChildAgency2?.isStillReferencedByDocument) } }
mit
99a7052553d143550cb9626c72368bb4
63.708197
192
0.768178
4.389457
false
true
false
false
ralfstuckert/pdftools
src/main/kotlin/rst/pdftools/compare/Image.kt
1
1854
package rst.pdftools.compare import java.awt.Color import java.awt.image.BufferedImage import java.awt.image.DataBufferInt import java.io.IOException import java.util.concurrent.atomic.AtomicInteger import java.util.stream.IntStream @Throws(IOException::class) fun compareImage(expected: BufferedImage, other: BufferedImage, colorDistanceTolerance:Double): ImageCompareResult { if (expected.width != other.width || expected.height != other.height) { return ImageCompareResult.SizeDiffers(expected.width, expected.height, other.width, other.height) } val width = expected.width val height = expected.height val diffImage = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) val diffPixel = ( diffImage.raster.dataBuffer as DataBufferInt).data val expectedPixel = expected.getRGB(0, 0, width, height, null, 0, width) val otherPixel = other.getRGB(0, 0, width, height, null, 0, width) var errorCount = AtomicInteger(0) IntStream.range(0, expectedPixel.size).parallel().forEach { index -> if (expectedPixel[index].normalizedRgbDistanceTo(otherPixel[index]) > colorDistanceTolerance) { errorCount.incrementAndGet() diffPixel[index] = Color.red.rgb } else { diffPixel[index] = expectedPixel[index] } } if (errorCount.get() == 0) { return ImageCompareResult.Identical } return ImageCompareResult.ContentDiffers(errorCount.get(), diffImage) } sealed class ImageCompareResult() { object Identical : ImageCompareResult() data class SizeDiffers(val expectedWidth:Int, val expectedHeight:Int, val actualWidth:Int, val actualHeight:Int):ImageCompareResult() data class ContentDiffers(val diffPixelCount:Int, val diffImage:BufferedImage):ImageCompareResult() }
mit
9ad5b85863f61555c55dcda4e57ad68e
34.653846
105
0.716289
4.321678
false
false
false
false
vladmm/intellij-community
platform/configuration-store-impl/testSrc/SchemeManagerTest.kt
5
12402
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.options.BaseSchemeProcessor import com.intellij.openapi.options.ExternalizableScheme import com.intellij.openapi.options.SchemesManagerFactory import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.util.SmartList import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.xmlb.XmlSerializer import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.Transient import com.intellij.util.xmlb.serialize import com.intellij.util.xmlb.toByteArray import gnu.trove.THashMap import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.jdom.Element import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File internal val FILE_SPEC = "REMOTE" /** * Functionality without stream provider covered, ICS has own test suite */ internal class SchemeManagerTest { companion object { @ClassRule val projectRule = ProjectRule() } private val tempDirManager = TemporaryDirectory() @Rule fun getTemporaryFolder() = tempDirManager private var localBaseDir: File? = null private var remoteBaseDir: File? = null private fun getTestDataPath() = PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/options" @Test fun loadSchemes() { doLoadSaveTest("options1", "1->first;2->second") } @Test fun loadSimpleSchemes() { doLoadSaveTest("options", "1->1") } @Test fun deleteScheme() { val manager = createAndLoad("options1") manager.removeScheme(TestScheme("first")) manager.save() checkSchemes("2->second") } @Test fun renameScheme() { val manager = createAndLoad("options1") val scheme = manager.findSchemeByName("first") assertThat(scheme).isNotNull() scheme!!.name = "renamed" manager.save() checkSchemes("2->second;renamed->renamed") } @Test fun testRenameScheme2() { val manager = createAndLoad("options1") val first = manager.findSchemeByName("first") assertThat(first).isNotNull() assert(first != null) first!!.name = "2" val second = manager.findSchemeByName("second") assertThat(second).isNotNull() assert(second != null) second!!.name = "1" manager.save() checkSchemes("1->1;2->2") } @Test fun testDeleteRenamedScheme() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull() assert(firstScheme != null) firstScheme!!.name = "first_renamed" manager.save() checkSchemes(File(remoteBaseDir, "REMOTE"), "first_renamed->first_renamed;2->second", true) checkSchemes(localBaseDir!!, "", false) firstScheme.name = "first_renamed2" manager.removeScheme(firstScheme) manager.save() checkSchemes(File(remoteBaseDir, "REMOTE"), "2->second", true) checkSchemes(localBaseDir!!, "", false) } @Test fun testDeleteAndCreateSchemeWithTheSameName() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull() manager.removeScheme(firstScheme!!) manager.addScheme(TestScheme("first")) manager.save() checkSchemes("2->second;first->first") } @Test fun testGenerateUniqueSchemeName() { val manager = createAndLoad("options1") val scheme = TestScheme("first") manager.addNewScheme(scheme, false) assertThat("first2").isEqualTo(scheme.name) } fun TestScheme.save(file: File) { FileUtil.writeToFile(file, serialize().toByteArray()) } @Test fun `different extensions`() { val dir = tempDirManager.newDirectory() val scheme = TestScheme("local", "true") scheme.save(File(dir, "1.icls")) TestScheme("local", "false").save(File(dir, "1.xml")) val schemesManager = SchemeManagerImpl<TestScheme, TestScheme>(FILE_SPEC, object: TestSchemesProcessor() { override fun isUpgradeNeeded() = true override fun getSchemeExtension() = ".icls" }, null, dir) schemesManager.loadSchemes() assertThat(schemesManager.allSchemes).containsOnly(scheme) assertThat(File(dir, "1.icls")).isFile() assertThat(File(dir, "1.xml")).isFile() scheme.data = "newTrue" schemesManager.save() assertThat(File(dir, "1.icls")).isFile() assertThat(File(dir, "1.xml")).doesNotExist() } @Test fun setSchemes() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(File(dir, "s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(File(dir, "s1.xml")).isFile() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun `save only if scheme differs from bundled`() { val dir = tempDirManager.newDirectory() var schemeManager = createSchemeManager(dir) val converter: (Element) -> TestScheme = { XmlSerializer.deserialize(it, TestScheme::class.java)!! } val bundledPath = "/bundledSchemes/default" schemeManager.loadBundledScheme(bundledPath, this, converter) var schemes = schemeManager.allSchemes val customScheme = TestScheme("default") assertThat(schemes).containsOnly(customScheme) schemeManager.save() assertThat(dir).doesNotExist() schemeManager.save() schemeManager.setSchemes(listOf(customScheme)) assertThat(dir).doesNotExist() schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(customScheme) customScheme.data = "foo" schemeManager.save() assertThat(File(dir, "default.xml")).isFile() schemeManager = createSchemeManager(dir) schemeManager.loadBundledScheme(bundledPath, this, converter) schemeManager.loadSchemes() schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(customScheme) } @Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) schemeManager.save() val schemeFile = File(dir, "s1.xml") assertThat(schemeFile).isFile() schemeManager.setSchemes(emptyList()) FileUtil.writeToFile(File(dir, "empty"), byteArrayOf()) schemeManager.save() assertThat(schemeFile).doesNotExist() assertThat(dir).isDirectory() } @Test fun `remove empty directory only if some file was deleted`() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(dir.mkdirs()).isTrue() schemeManager.save() assertThat(dir).isDirectory() schemeManager.addScheme(TestScheme("test")) schemeManager.save() assertThat(dir).isDirectory() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun rename() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(File(dir, "s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(File(dir, "s1.xml")).isFile() scheme.name = "s2" schemeManager.save() assertThat(File(dir, "s1.xml")).doesNotExist() assertThat(File(dir, "s2.xml")).isFile() } @Test fun `path must not contains ROOT_CONFIG macro`() { assertThatThrownBy({ SchemesManagerFactory.getInstance().create<TestScheme, TestScheme>("\$ROOT_CONFIG$/foo", TestSchemesProcessor()) }).hasMessage("Path must not contains ROOT_CONFIG macro, corrected: foo") } @Test fun `path must be system-independent`() { assertThatThrownBy({SchemesManagerFactory.getInstance().create<TestScheme, TestScheme>("foo\\bar", TestSchemesProcessor())}).hasMessage("Path must be system-independent, use forward slash instead of backslash") } private fun createSchemeManager(dir: File) = SchemeManagerImpl<TestScheme, TestScheme>(FILE_SPEC, TestSchemesProcessor(), null, dir) private fun createAndLoad(testData: String): SchemeManagerImpl<TestScheme, TestScheme> { createTempFiles(testData) return createAndLoad() } private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") { val schemesManager = createAndLoad(testData) schemesManager.save() checkSchemes(File(remoteBaseDir, "REMOTE"), expected, true) checkSchemes(localBaseDir!!, localExpected, false) } private fun checkSchemes(expected: String) { checkSchemes(File(remoteBaseDir, "REMOTE"), expected, true) checkSchemes(localBaseDir!!, "", false) } private fun createAndLoad(): SchemeManagerImpl<TestScheme, TestScheme> { val schemesManager = SchemeManagerImpl<TestScheme, TestScheme>(FILE_SPEC, TestSchemesProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!) schemesManager.loadSchemes() return schemesManager } private fun createTempFiles(testData: String) { val temp = tempDirManager.newDirectory() localBaseDir = File(temp, "__local") remoteBaseDir = temp FileUtil.copyDir(File("${getTestDataPath()}/$testData"), File(temp, "REMOTE")) } } private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean) { val filesToScheme = StringUtil.split(expected, ";") val fileToSchemeMap = THashMap<String, String>() for (fileToScheme in filesToScheme) { val index = fileToScheme.indexOf("->") fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2)) } val files = baseDir.listFiles() if (files != null) { for (file in files) { val fileName = FileUtil.getNameWithoutExtension(file) if ("--deleted" == fileName && ignoreDeleted) { assertThat(fileToSchemeMap).containsKey(fileName) } } } for (file in fileToSchemeMap.keySet()) { assertThat(File(baseDir, "$file.xml")).isFile() } if (files != null) { val schemesProcessor = TestSchemesProcessor() for (file in files) { val scheme = schemesProcessor.readScheme(JDOMUtil.load(file), true)!! assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file))).isEqualTo(scheme.name) } } } @Tag("scheme") data class TestScheme(@field:Attribute private var name: String = "", @field:Attribute var data: String? = null) : ExternalizableScheme { override fun getName() = name override @Transient fun setName(newName: String) { name = newName } } open class TestSchemesProcessor : BaseSchemeProcessor<TestScheme>() { override fun readScheme(element: Element) = XmlSerializer.deserialize(element, TestScheme::class.java) override fun writeScheme(scheme: TestScheme) = scheme.serialize() } fun SchemeManagerImpl<*, *>.save() { val errors = SmartList<Throwable>() save(errors) CompoundRuntimeException.throwIfNotEmpty(errors) }
apache-2.0
5700262b4c070183f099e1f5b08772e7
30.884319
214
0.723512
4.574696
false
true
false
false
google/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/psi/KotlinStdlibInjectionTest.kt
2
2319
// 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.psi import org.intellij.lang.annotations.Language import org.intellij.lang.regexp.RegExpLanguage import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KotlinStdlibInjectionTest : AbstractInjectionTest() { fun testOnRegex0() = assertInjectionPresent( """ val test1 = Regex("<caret>some") """, RegExpLanguage.INSTANCE.id ) fun testOnRegex1() = assertInjectionPresent( """ val test1 = Regex("<caret>some", RegexOption.COMMENTS) """, RegExpLanguage.INSTANCE.id ) fun testOnRegex2() = assertInjectionPresent( """ val test1 = Regex("<caret>some", setOf(RegexOption.COMMENTS)) """, RegExpLanguage.INSTANCE.id ) fun testToRegex0() = assertInjectionPresent( """ val test = "hi<caret>".toRegex() """, RegExpLanguage.INSTANCE.id ) fun testToRegex1() = assertInjectionPresent( """ val test = "hi<caret>".toRegex(RegexOption.CANON_EQ) """, RegExpLanguage.INSTANCE.id ) fun testToRegex2() = assertInjectionPresent( """ val test = "hi<caret>".toRegex(setOf(RegexOption.LITERAL)) """, RegExpLanguage.INSTANCE.id ) fun testToPattern0() = assertInjectionPresent( """ val test = "a.*b<caret>".toPattern() """, RegExpLanguage.INSTANCE.id ) fun testToPattern1() = assertInjectionPresent( """ val test = "a.*b<caret>".toPattern(java.util.regex.Pattern.CASE_INSENSITIVE) """, RegExpLanguage.INSTANCE.id ) private fun assertInjectionPresent(@Language("kotlin") text: String, languageId: String) { doInjectionPresentTest(text, languageId = languageId, unInjectShouldBePresent = false) } override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE }
apache-2.0
9c8d97521b5bf0fbed2b963082829a4a
29.92
158
0.638206
4.573964
false
true
false
false
RuneSuite/client
updater-deob/src/main/java/org/runestar/client/updater/deob/util/Util.kt
1
1624
package org.runestar.client.updater.deob.util import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassWriter import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.analysis.Analyzer import org.objectweb.asm.tree.analysis.BasicInterpreter import org.zeroturnaround.zip.ByteSource import org.zeroturnaround.zip.ZipUtil import java.nio.file.Path fun ClassNode(classFile: ByteArray): ClassNode { val c = ClassNode() ClassReader(classFile).accept(c, 0) return c } fun parse(classFile: ByteArray, readOptions: Int, writeOptions: Int): ByteArray { val w = ClassWriter(writeOptions) ClassReader(classFile).accept(w, readOptions) return w.toByteArray() } fun ClassNode.toByteArray(writer: ClassWriter = ClassWriter(0)): ByteArray { accept(writer) return writer.toByteArray() } fun analyze(classNode: ClassNode) { for (m in classNode.methods) { try { Analyzer(BasicInterpreter()).analyze(classNode.name, m) } catch (e: Exception) { throw Exception("${classNode.name}.${m.name}${m.desc}", e) } } } fun readClasses(jar: Path): List<ByteArray> { val classes = ArrayList<ByteArray>() ZipUtil.iterate(jar.toFile()) { input, entry -> if (!entry.name.endsWith(".class")) return@iterate classes.add(input.readAllBytes()) } return classes } fun readClassNodes(jar: Path) = readClasses(jar).map { ClassNode(it) } fun writeClasses(classes: Iterable<ByteArray>, jar: Path) { ZipUtil.pack(classes.map { ByteSource("${ClassReader(it).className}.class", it) }.toTypedArray(), jar.toFile()) }
mit
6f4f11b022c85ce4bbad5cc1ae8efb73
30.25
115
0.707512
3.821176
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDirectInheritorsSearcher.kt
2
3007
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.ideaExtensions import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiClass import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.DirectClassInheritorsSearch import com.intellij.util.Processor import org.jetbrains.kotlin.asJava.toLightClassWithBuiltinMapping import org.jetbrains.kotlin.asJava.classes.KtFakeLightClass import org.jetbrains.kotlin.asJava.toFakeLightClass import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.util.fileScope import org.jetbrains.kotlin.idea.stubindex.KotlinSuperClassIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasByExpansionShortNameIndex open class KotlinDirectInheritorsSearcher : QueryExecutorBase<PsiClass, DirectClassInheritorsSearch.SearchParameters>(true) { override fun processQuery(queryParameters: DirectClassInheritorsSearch.SearchParameters, consumer: Processor<in PsiClass>) { val baseClass = queryParameters.classToProcess val baseClassName = baseClass.name ?: return val file = if (baseClass is KtFakeLightClass) baseClass.kotlinOrigin.containingFile else baseClass.containingFile val originalScope = queryParameters.scope val scope = originalScope as? GlobalSearchScope ?: file.fileScope() val names = mutableSetOf(baseClassName) val project = file.project fun searchForTypeAliasesRecursively(typeName: String) { ProgressManager.checkCanceled() KotlinTypeAliasByExpansionShortNameIndex .get(typeName, project, scope) .asSequence() .map { it.name } .filterNotNull() .filter { it !in names } .onEach { names.add(it) } .forEach(::searchForTypeAliasesRecursively) } searchForTypeAliasesRecursively(baseClassName) val noLibrarySourceScope = KotlinSourceFilterScope.projectFiles(scope, project) names.forEach { name -> ProgressManager.checkCanceled() KotlinSuperClassIndex .get(name, project, noLibrarySourceScope).asSequence() .map { candidate -> ProgressManager.checkCanceled() candidate.toLightClassWithBuiltinMapping() ?: candidate.toFakeLightClass() } .filter { candidate -> ProgressManager.checkCanceled() candidate.isInheritor(baseClass, false) } .forEach { candidate -> ProgressManager.checkCanceled() consumer.process(candidate) } } } }
apache-2.0
66f3cda3a1cfdf680a6dcc802c8dd34b
44.560606
158
0.69704
5.537753
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLazyPropertyToOrdinaryIntention.kt
1
2084
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren class ConvertLazyPropertyToOrdinaryIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.ordinary.property") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { val delegateExpression = element.delegate?.expression as? KtCallExpression ?: return false val lambdaBody = delegateExpression.functionLiteral()?.bodyExpression ?: return false if (lambdaBody.statements.isEmpty()) return false return delegateExpression.isCalling(FqName("kotlin.lazy")) } override fun applyTo(element: KtProperty, editor: Editor?) { val delegate = element.delegate ?: return val delegateExpression = delegate.expression as? KtCallExpression ?: return val functionLiteral = delegateExpression.functionLiteral() ?: return element.initializer = functionLiteral.singleStatement() ?: KtPsiFactory(element.project).createExpression("run ${functionLiteral.text}") delegate.delete() } private fun KtCallExpression.functionLiteral(): KtFunctionLiteral? { return lambdaArguments.singleOrNull()?.getLambdaExpression()?.functionLiteral } private fun KtFunctionLiteral.singleStatement(): KtExpression? { val body = this.bodyExpression ?: return null if (body.allChildren.any { it is PsiComment }) return null return body.statements.singleOrNull() } }
apache-2.0
b262f189f7da9b02e951dfa5a83c1f68
48.619048
158
0.759117
5.120393
false
false
false
false