repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/orders/OrdersViewModel.kt
1
1006
package com.marknkamau.justjava.ui.orders import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.marknjunge.core.data.model.Order import com.marknjunge.core.data.model.Resource import com.marknjunge.core.data.repository.OrdersRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class OrdersViewModel @Inject constructor(private val ordersRepository: OrdersRepository) : ViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = _loading private val _orders = MutableLiveData<Resource<List<Order>>>() val orders: LiveData<Resource<List<Order>>> = _orders fun getOrders() { viewModelScope.launch { _loading.value = true _orders.value = ordersRepository.getOrders() _loading.value = false } } }
apache-2.0
28c7fb50ba5c562addbce9aff70b17de
33.689655
105
0.757455
4.531532
false
false
false
false
robovm/robovm-studio
plugins/settings-repository/src/IcsUrlBuilder.kt
1
657
package org.jetbrains.settingsRepository import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.SystemInfo val PROJECTS_DIR_NAME: String = "_projects/" private fun getOsFolderName() = when { SystemInfo.isWindows -> "_windows" SystemInfo.isMac -> "_mac" SystemInfo.isLinux -> "_linux" SystemInfo.isFreeBSD -> "_freebsd" SystemInfo.isUnix -> "_unix" else -> "_unknown" } fun buildPath(path: String, roamingType: RoamingType, projectKey: String? = null) = when { projectKey != null -> "$PROJECTS_DIR_NAME$projectKey/$path" roamingType == RoamingType.PER_PLATFORM -> "${getOsFolderName()}/$path" else -> path }
apache-2.0
b583cb945aaa94fb99b1b80de89a2785
30.333333
90
0.722983
3.934132
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/api/AuthenticationRequestInterceptor.kt
2
1420
package com.commit451.gitlab.api import com.commit451.gitlab.model.Account import okhttp3.Interceptor import okhttp3.Response import java.io.IOException /** * Adds the private token to all requests of the same server as the account */ class AuthenticationRequestInterceptor(private val account: Account) : Interceptor { companion object { const val PRIVATE_TOKEN_HEADER_FIELD = "Private-Token" } @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { var request = chain.request() val url = request.url val serverUrl = account.serverUrl ?: "https://example.com" if (isSameServer(url.toString(), serverUrl)) { val privateToken = account.privateToken privateToken?.let { request = request.newBuilder() .header(PRIVATE_TOKEN_HEADER_FIELD, it) .url(url) .build() } } return chain.proceed(request) } private fun isSameServer(requestUrl: String, serverUrl: String): Boolean { var cleanUrl = requestUrl.toLowerCase() cleanUrl = cleanUrl.substring(cleanUrl.indexOf(':')) var cleanServerUrl = serverUrl.toLowerCase() cleanServerUrl = cleanServerUrl.substring(cleanServerUrl.indexOf(':')) return cleanUrl.startsWith(cleanServerUrl) } }
apache-2.0
e83eaf43d88971058bb11a8943c31aab
29.869565
84
0.642254
4.749164
false
false
false
false
haozileung/test
src/main/kotlin/com/haozileung/web/domain/logging/LoginLog.kt
1
676
/* * Powered By [rapid-framework] * Web Site: http://www.rapid-framework.org.cn * Google Code: http://code.google.com/p/rapid-framework/ * Since 2008 - 2016 */ package com.haozileung.web.domain.logging import java.io.Serializable import java.util.* /** * @author Haozi * * * @version 1.0 * * * @since 1.0 */ data class LoginLog(var loginLogId: Long? = null, var userId: Long? = null, var ipAddress: String? = null, var loginTime: Date? = null, var result: Int? = null, var browser: String? = null, var remarks: String? = null) : Serializable
mit
e45db9bc2563c9e0529925cef7ed4d43
24.074074
63
0.557692
3.595745
false
false
false
false
Asqatasun/Asqatasun
server/asqatasun-server/src/main/kotlin/org/asqatasun/web/audit/AuditService.kt
1
9059
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * This file is part of Asqatasun. * * Asqatasun 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.web.audit import org.asqatasun.entity.audit.Audit import org.asqatasun.entity.contract.* import org.asqatasun.entity.contract.ScopeEnum.* import org.asqatasun.entity.parameterization.Parameter import org.asqatasun.entity.service.audit.TagDataService import org.asqatasun.entity.service.contract.ActDataService import org.asqatasun.entity.service.contract.ContractDataService import org.asqatasun.entity.service.contract.ScopeDataService import org.asqatasun.entity.service.parameterization.ParameterDataService import org.asqatasun.entity.service.parameterization.ParameterElementDataService import org.asqatasun.service.AuditServiceListener import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.io.IOException import java.time.Instant import java.util.* import javax.annotation.PostConstruct import org.asqatasun.service.AuditService as EngineAuditService @Service class AuditService(private val auditService: EngineAuditService, private val contractDataService: ContractDataService, private val actDataService: ActDataService, private val scopeDataService: ScopeDataService, private val parameterDataService: ParameterDataService, private val parameterElementDataService: ParameterElementDataService, private val tagDataService: TagDataService) { private val scopeMap: MutableMap<ScopeEnum, Scope> = EnumMap(ScopeEnum::class.java) companion object { const val DEPTH_PARAM_KEY = "DEPTH" const val MAX_DOCUMENT_PARAM_KEY = "MAX_DOCUMENTS" const val MAX_DURATION_PARAM_KEY = "MAX_DURATION" const val EXCLUSION_URL_LIST_PARAM_KEY = "EXCLUSION_REGEXP" const val INCLUSION_URL_LIST_PARAM_KEY = "INCLUSION_REGEXP" const val ROBOTS_TXT_ACTIVATION_PARAM_KEY = "ROBOTS_TXT_ACTIVATION" } @PostConstruct private fun initializeScopeMap() { for (scope in scopeDataService.findAll()) { scopeMap[scope.code] = scope } } fun runPageAudit(par: PageAuditRequest, ipAddress: String): Long { val contract = getContract(par.contractId) return if (par.urls.size > 1) { getAuditId( auditService.auditSite( par.urls[0], par.urls, initialiseParamSet(par.referential.code, par.level.code), tagDataService.getTagListFromValues(par.tags)), ipAddress, GROUPOFPAGES, contract) } else { getAuditId( auditService.auditPage( par.urls[0], initialiseParamSet(par.referential.code, par.level.code), tagDataService.getTagListFromValues(par.tags)), ipAddress, PAGE, contract) } } fun runScenarioAudit(sar: ScenarioAuditRequest, ipAddress: String): Long { val contract = getContract(sar.contractId) return auditService.auditScenario( sar.name, readFile(sar.scenario), initialiseParamSet(sar.referential.code, sar.level.code), tagDataService.getTagListFromValues(sar.tags)).let { getAuditId(it, ipAddress, SCENARIO, contract) } } fun runSiteAudit(sar: SiteAuditRequest, ipAddress: String): Long { val contract = getContract(sar.contractId) val paramSet = initialiseParamSet(sar.referential.code, sar.level.code).toMutableSet() initSiteAuditParamSet(sar, paramSet) return auditService.auditSite( sar.url, paramSet, tagDataService.getTagListFromValues(sar.tags)).let { getAuditId(it, ipAddress, SCENARIO, contract) } } private fun getAuditId(audit: Audit, ipAddress: String, scope: ScopeEnum, contract: Contract?): Long { val act = initialiseAct(ipAddress, scope, audit, contract) auditService.add(RestAuditServiceListener(act?.id, actDataService, auditService)) return audit.id } private fun initialiseAct(ipAddress: String, scope: ScopeEnum, audit: Audit, contract: Contract?): Act? { return contract?.let { val a = actDataService.create() a.status = ActStatus.RUNNING a.beginDate = Date.from(Instant.now()) a.clientIp = ipAddress a.scope = scopeMap[scope] a.contract = it a.audit = audit actDataService.saveOrUpdate(a) } } private fun getContract(contractId: Long?) = contractId?.let { id -> contractDataService.read(id) ?: throw ContractNotFoundException() } private fun initialiseParamSet(referentialCode: String, levelCode: String) = parameterDataService.getParameterSetFromAuditLevel(referentialCode, levelCode) private fun initSiteAuditParamSet(sar: SiteAuditRequest, paramSet: MutableSet<Parameter>) { paramSet.removeIf { p -> p.parameterElement.parameterElementCode.equals(DEPTH_PARAM_KEY) || p.parameterElement.parameterElementCode.equals(MAX_DURATION_PARAM_KEY) || p.parameterElement.parameterElementCode.equals(MAX_DOCUMENT_PARAM_KEY) || p.parameterElement.parameterElementCode.equals(INCLUSION_URL_LIST_PARAM_KEY) || p.parameterElement.parameterElementCode.equals(EXCLUSION_URL_LIST_PARAM_KEY) || p.parameterElement.parameterElementCode.equals(ROBOTS_TXT_ACTIVATION_PARAM_KEY) } paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(DEPTH_PARAM_KEY), sar.depth.toString())) paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(MAX_DURATION_PARAM_KEY), sar.maxDuration.toString())) paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(MAX_DOCUMENT_PARAM_KEY), sar.maxPages.toString())) paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(INCLUSION_URL_LIST_PARAM_KEY), sar.inclusionRegexp)) paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(EXCLUSION_URL_LIST_PARAM_KEY), sar.exclusionRegexp)) paramSet.add(parameterDataService.getParameter( parameterElementDataService.getParameterElement(ROBOTS_TXT_ACTIVATION_PARAM_KEY), sar.robotsTxtActivation.toString())) } @Throws(IOException::class) // #57 issue quick fix....... private fun readFile(scenario: String) = scenario.replace("\"formatVersion\": 2", "\"formatVersion\":1") .replace("\"formatVersion\":2", "\"formatVersion\":1") } class ContractNotFoundException : Throwable() {} class RestAuditServiceListener(private val actId: Long?, private val actDataService: ActDataService, private val auditService: EngineAuditService) : AuditServiceListener { companion object { private val LOGGER = LoggerFactory.getLogger(RestAuditServiceListener::class.java) } override fun auditCompleted(audit: Audit?) { LOGGER.info("Rest audit ${audit!!.id} terminated successfully") actId?.let { val act = actDataService.read(it) act.endDate = Date.from(Instant.now()) act.status = ActStatus.COMPLETED actDataService.saveOrUpdate(act) } auditService.remove(this) } override fun auditCrashed(audit: Audit?, exception: Exception?) { LOGGER.info("Rest audit ${audit!!.id} crashed") LOGGER.info(exception!!.message) actId?.let { val act = actDataService.read(it) act.endDate = Date.from(Instant.now()) act.status = ActStatus.ERROR actDataService.saveOrUpdate(act) } auditService.remove(this) } }
agpl-3.0
5c38ebb213e86acc8afa81a8c396ec4f
42.138095
130
0.671708
4.524975
false
false
false
false
maiconhellmann/pomodoro
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/util/extension/StringExtension.kt
1
574
package br.com.maiconhellmann.pomodoro.util.extension fun String.Companion.empty(): String{ return "" } fun String.Companion.isEmpty(text: Any?): Boolean { return text==null || text.toString().trim() == String.empty() } fun String.Companion.isNotEmpty(text: Any?): Boolean { return text!=null && text.toString().trim() != String.empty() } fun String.leftPadding(size: Int, strToAdd: String): String { var newString = this while(newString.length < size) { newString = strToAdd + newString } return newString }
apache-2.0
5df2334986cd1ba28f2ab2aee4fc3c26
22.956522
65
0.649826
3.878378
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt
1
9789
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.extensions.toHex import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.PayloadJoiner import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.PayloadSplitter import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag sealed class MessageSendResult object MessageSendSuccess : MessageSendResult() data class MessageSendErrorSending(val msg: String, val cause: Throwable? = null) : MessageSendResult() { constructor(e: BleSendResult) : this("Could not send packet: $e") } data class MessageSendErrorConfirming(val msg: String, val cause: Throwable? = null) : MessageSendResult() { constructor(e: BleSendResult) : this("Could not confirm packet: $e") } sealed class PacketReceiveResult data class PacketReceiveSuccess(val payload: ByteArray) : PacketReceiveResult() data class PacketReceiveError(val msg: String) : PacketReceiveResult() class MessageIO( private val aapsLogger: AAPSLogger, private val cmdBleIO: CmdBleIO, private val dataBleIO: DataBleIO, ) { private val receivedOutOfOrder = LinkedHashMap<Byte, ByteArray>() var maxMessageReadTries = 3 var messageReadTries = 0 @Suppress("ReturnCount") fun sendMessage(msg: MessagePacket): MessageSendResult { val foundRTS = cmdBleIO.flushIncomingQueue() if (foundRTS) { val receivedMessage = receiveMessage(false) aapsLogger.warn(LTag.PUMPBTCOMM, "sendMessage received message=$receivedMessage") throw IllegalStateException("Received message while trying to send") } dataBleIO.flushIncomingQueue() val rtsSendResult = cmdBleIO.sendAndConfirmPacket(BleCommandRTS.data) if (rtsSendResult is BleSendErrorSending) { return MessageSendErrorSending(rtsSendResult) } val expectCTS = cmdBleIO.expectCommandType(BleCommandCTS) if (expectCTS !is BleConfirmSuccess) { return MessageSendErrorSending(expectCTS.toString()) } val payload = msg.asByteArray() aapsLogger.debug(LTag.PUMPBTCOMM, "Sending message: ${payload.toHex()}") val splitter = PayloadSplitter(payload) val packets = splitter.splitInPackets() for ((index, packet) in packets.withIndex()) { aapsLogger.debug(LTag.PUMPBTCOMM, "Sending DATA: ${packet.toByteArray().toHex()}") val sendResult = dataBleIO.sendAndConfirmPacket(packet.toByteArray()) val ret = handleSendResult(sendResult, index, packets) if (ret !is MessageSendSuccess) { return ret } val peek = peekForNack(index, packets) if (peek !is MessageSendSuccess) { return if (index == packets.size - 1) MessageSendErrorConfirming(peek.toString()) else MessageSendErrorSending(peek.toString()) } } return when (val expectSuccess = cmdBleIO.expectCommandType(BleCommandSuccess)) { is BleConfirmSuccess -> MessageSendSuccess is BleConfirmError -> MessageSendErrorConfirming("Error reading message confirmation: $expectSuccess") is BleConfirmIncorrectData -> when (val received = (BleCommand.parse((expectSuccess.payload)))) { is BleCommandFail -> // this can happen if CRC does not match MessageSendErrorSending("Received FAIL after sending message") else -> MessageSendErrorConfirming("Received confirmation message: $received") } } } @Suppress("ReturnCount") fun receiveMessage(readRTS: Boolean = true): MessagePacket? { if (readRTS) { val expectRTS = cmdBleIO.expectCommandType(BleCommandRTS, MESSAGE_READ_TIMEOUT_MS) if (expectRTS !is BleConfirmSuccess) { aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading RTS: $expectRTS") return null } } val sendResult = cmdBleIO.sendAndConfirmPacket(BleCommandCTS.data) if (sendResult !is BleSendSuccess) { aapsLogger.warn(LTag.PUMPBTCOMM, "Error sending CTS: $sendResult") return null } readReset() var expected: Byte = 0 try { val firstPacket = expectBlePacket(0) if (firstPacket !is PacketReceiveSuccess) { aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading first packet:$firstPacket") return null } val joiner = PayloadJoiner(firstPacket.payload) maxMessageReadTries = joiner.fullFragments * 2 + 2 for (i in 1 until joiner.fullFragments + 1) { expected++ val nackOnTimeout = !joiner.oneExtraPacket && i == joiner.fullFragments // last packet val packet = expectBlePacket(expected, nackOnTimeout) if (packet !is PacketReceiveSuccess) { aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading packet:$packet") return null } joiner.accumulate(packet.payload) } if (joiner.oneExtraPacket) { expected++ val packet = expectBlePacket(expected, true) if (packet !is PacketReceiveSuccess) { aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading packet:$packet") return null } joiner.accumulate(packet.payload) } val fullPayload = joiner.finalize() cmdBleIO.sendAndConfirmPacket(BleCommandSuccess.data) return MessagePacket.parse(fullPayload) } catch (e: IncorrectPacketException) { aapsLogger.warn(LTag.PUMPBTCOMM, "Received incorrect packet: $e") cmdBleIO.sendAndConfirmPacket(BleCommandAbort.data) return null } catch (e: CrcMismatchException) { aapsLogger.warn(LTag.PUMPBTCOMM, "CRC mismatch: $e") cmdBleIO.sendAndConfirmPacket(BleCommandFail.data) return null } finally { readReset() } } private fun handleSendResult(sendResult: BleSendResult, index: Int, packets: List<BlePacket>): MessageSendResult { return when { sendResult is BleSendSuccess -> MessageSendSuccess index == packets.size - 1 && sendResult is BleSendErrorConfirming -> MessageSendErrorConfirming("Error confirming last DATA packet $sendResult") else -> MessageSendErrorSending("Error sending DATA: $sendResult") } } private fun peekForNack(index: Int, packets: List<BlePacket>): MessageSendResult { val peekCmd = cmdBleIO.peekCommand() ?: return MessageSendSuccess return when (val receivedCmd = BleCommand.parse(peekCmd)) { is BleCommandNack -> { // // Consume NACK val received = cmdBleIO.receivePacket() if (received == null) { MessageSendErrorSending(received.toString()) } else { val sendResult = dataBleIO.sendAndConfirmPacket(packets[receivedCmd.idx.toInt()].toByteArray()) handleSendResult(sendResult, index, packets) } } BleCommandSuccess -> { if (index == packets.size - 1) MessageSendSuccess else MessageSendErrorSending("Received SUCCESS before sending all the data. $index") } else -> MessageSendErrorSending("Received unexpected command: ${peekCmd.toHex()}") } } @Suppress("ReturnCount") private fun expectBlePacket(index: Byte, nackOnTimeout: Boolean = false): PacketReceiveResult { receivedOutOfOrder[index]?.let { return PacketReceiveSuccess(it) } var packetTries = 0 while (messageReadTries < maxMessageReadTries && packetTries < MAX_PACKET_READ_TRIES) { messageReadTries++ packetTries++ val received = dataBleIO.receivePacket() if (received == null || received.isEmpty()) { if (nackOnTimeout) cmdBleIO.sendAndConfirmPacket(BleCommandNack(index).data) aapsLogger.info( LTag.PUMPBTCOMM, "Error reading index: $index. Received: $received. NackOnTimeout: " + "$nackOnTimeout" ) continue } if (received[0] == index) { return PacketReceiveSuccess(received) } receivedOutOfOrder[received[0]] = received cmdBleIO.sendAndConfirmPacket(BleCommandNack(index).data) } return PacketReceiveError("Reached the maximum number tries to read a packet") } private fun readReset() { maxMessageReadTries = 3 messageReadTries = 0 receivedOutOfOrder.clear() } companion object { private const val MAX_PACKET_READ_TRIES = 4 private const val MESSAGE_READ_TIMEOUT_MS = 5000.toLong() } }
agpl-3.0
e094a148db86d67db86689bb87f1dba4
41.376623
118
0.616508
4.84844
false
false
false
false
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/references/SubredditReference.kt
1
10002
package net.dean.jraw.references import com.squareup.moshi.Types import net.dean.jraw.* import net.dean.jraw.models.* import net.dean.jraw.models.internal.GenericJsonResponse import net.dean.jraw.models.internal.SubmissionData import net.dean.jraw.pagination.BarebonesPaginator import net.dean.jraw.pagination.DefaultPaginator import net.dean.jraw.pagination.SearchPaginator import net.dean.jraw.tree.RootCommentNode /** * Allows the user to perform API actions against a subreddit * * @constructor Creates a new SubredditReference for the given subreddit. Do not include the "/r/" prefix (e.g. "pics") * * @property subreddit The name of the subreddit without the "/r/" prefix. */ class SubredditReference internal constructor(reddit: RedditClient, val subreddit: String) : AbstractReference(reddit) { /** * Returns a [Subreddit] instance for this reference. Throws an ApiException if private or otherwise inaccessible by * the current user (if any). */ @EndpointImplementation(Endpoint.GET_SUBREDDIT_ABOUT) fun about(): Subreddit = reddit.request { it.endpoint(Endpoint.GET_SUBREDDIT_ABOUT, subreddit) }.deserializeEnveloped() /** * Creates a new [DefaultPaginator.Builder] to iterate over this subreddit's posts. Not a blocking call. */ @EndpointImplementation( Endpoint.GET_HOT, Endpoint.GET_NEW, Endpoint.GET_RISING, Endpoint.GET_SORT, Endpoint.GET_BEST, type = MethodType.NON_BLOCKING_CALL ) fun posts() = DefaultPaginator.Builder.create<Submission, SubredditSort>(reddit, "/r/$subreddit", sortingAlsoInPath = true) /** * Creates a BarebonesPaginator.Builder that will iterate over the latest comments from this subreddit when built. * * @see RedditClient.latestComments */ fun comments(): BarebonesPaginator.Builder<Comment> = reddit.latestComments(subreddit) /** * Creates a BarebonesPaginator.Builder that will iterate over the gilded contributions in this subreddit when built. * * @see RedditClient.gildedContributions */ fun gilded(): BarebonesPaginator.Builder<PublicContribution<*>> = reddit.gildedContributions(subreddit) /** * Creates a SearchPaginator.Builder to search for submissions in this subreddit. * * @see SearchPaginator.inSubreddits */ fun search(): SearchPaginator.Builder = SearchPaginator.inSubreddits(reddit, subreddit) /** * Gets a random submission from this subreddit. * * @see RedditClient.randomSubreddit */ @EndpointImplementation(Endpoint.GET_RANDOM) fun randomSubmission(): RootCommentNode { val data: SubmissionData = reddit.request { it.endpoint(Endpoint.GET_RANDOM, subreddit) }.deserialize() return RootCommentNode(data.submissions[0], data.comments, settings = null) } /** * Submits content to this subreddit * * @param kind Is this a self post (text) or a link post? * @param content If `kind` is [SubmissionKind.SELF], the Markdown-formatted body, else a URL. * @param sendReplies If direct replies to the submission should be sent to the user's inbox */ @EndpointImplementation(Endpoint.POST_SUBMIT) fun submit(kind: SubmissionKind, title: String, content: String, sendReplies: Boolean): SubmissionReference { val args = mutableMapOf( "api_type" to "json", "extension" to "json", "kind" to kind.name.toLowerCase(), "resubmit" to "false", "sendreplies" to sendReplies.toString(), "sr" to subreddit, "title" to title ) args[if (kind == SubmissionKind.SELF) "text" else "url"] = content val res = reddit.request { it.endpoint(Endpoint.POST_SUBMIT) .post(args) }.deserialize<GenericJsonResponse>() val id = res.json?.data?.get("id") as? String ?: throw IllegalArgumentException("ID not found") return SubmissionReference(reddit, id) } /** * Gets the text meant to be displayed on the submission form. */ @EndpointImplementation(Endpoint.GET_SUBMIT_TEXT) fun submitText(): String { return reddit.request { it.endpoint(Endpoint.GET_SUBMIT_TEXT, subreddit) }.deserialize<Map<String, String>>().getOrElse("submit_text") { throw IllegalArgumentException("Unexpected response: no `submit_text` key") } } /** Alias to `setSubscribed(true)` */ fun subscribe() = setSubscribed(true) /** Alias to `setSubscribed(false)` */ fun unsubscribe() = setSubscribed(false) /** Subscribes or unsubscribes to this subreddit. Requires an authenticated user. */ @EndpointImplementation(Endpoint.POST_SUBSCRIBE) fun setSubscribed(subscribe: Boolean) { val body = mutableMapOf( "sr_name" to subreddit, "action" to if (subscribe) "sub" else "unsub" ) if (subscribe) // "prevent automatically subscribing the user to the current set of defaults when they take their first // subscription action" body["skip_initial_defaults"] = "true" // Response is an empty JSON object reddit.request { it.endpoint(Endpoint.POST_SUBSCRIBE).post(body) } } /** * Lists all possible flairs for users. Requires an authenticated user. Will return nothing if flair is disabled on * the subreddit, the user cannot set their own flair, or they are not a moderator that can set flair. * * @see FlairReference.updateToTemplate */ @EndpointImplementation(Endpoint.GET_USER_FLAIR) fun userFlairOptions(): List<Flair> = requestFlair("user") /** * Lists all possible flairs for submissions to this subreddit. Requires an authenticated user. Will return nothing * if the user cannot set their own link flair and they are not a moderator that can set flair. * * @see FlairReference.updateToTemplate */ @EndpointImplementation(Endpoint.GET_LINK_FLAIR) fun linkFlairOptions(): List<Flair> = requestFlair("link") private fun requestFlair(type: String): List<Flair> { return reddit.request { it.path("/r/${JrawUtils.urlEncode(subreddit)}/api/${type}_flair") }.deserializeWith(JrawUtils.moshi.adapter(listOfFlairsType)) } /** * Returns a UserFlairReference for a user. * * Equivalent to `redditClient.user(name).flairOn(subreddit)`. */ fun otherUserFlair(name: String) = reddit.user(name).flairOn(subreddit) /** * Returns a UserFlairReference for the authenticated user. * * Equivalent to `redditClient.me().flairOn(subreddit)`. */ fun selfUserFlair() = reddit.me().flairOn(subreddit) /** * Returns a SubmissionFlairReference for the given submission id (without the kind prefix). */ fun submissionFlair(id: String) = SubmissionFlairReference(reddit, subreddit, id) /** * Returns the moderator-created rules for the subreddit. Users can report things in this subreddit using the String * specified in [SubredditRule.getViolationReason] */ @EndpointImplementation(Endpoint.GET_SUBREDDIT_ABOUT_RULES) fun rules(): Ruleset { return reddit.request { it.endpoint(Endpoint.GET_SUBREDDIT_ABOUT_RULES, subreddit) }.deserialize() } /** Returns a reference to the subreddit's wiki */ fun wiki() = WikiReference(reddit, subreddit) /** Fetches the stylesheet of a subreddit. Returned value is CSS. */ @EndpointImplementation(Endpoint.GET_STYLESHEET) fun stylesheet(): String { return reddit.request { it.endpoint(Endpoint.GET_STYLESHEET, subreddit) }.body } /** * Updates the stylesheet of a subreddit. Requires mod priveleges on the subreddit. * * @param stylesheet New stylesheet of the subreddit, completely replaces the pre-existing one * @param reason Reason for the update to be displayed in the stylesheet change history * */ @EndpointImplementation(Endpoint.POST_SUBREDDIT_STYLESHEET) fun updateStylesheet(stylesheet: String, reason: String) { reddit.request { it.endpoint(Endpoint.POST_SUBREDDIT_STYLESHEET, subreddit) .post(mapOf( "api_type" to "json", "op" to "save", "reason" to reason, "stylesheet_contents" to stylesheet )) } } /** * Returns a listing of currently set flairs on the subreddit (both custom and template-based ones) * Requires mod priveleges on the subreddit. */ @EndpointImplementation(Endpoint.GET_FLAIRLIST) fun flairList() = BarebonesPaginator.Builder.create<SimpleFlairInfo>(reddit, "/r/$subreddit/api/flairlist") /** * Updates users flairs on the subreddit in bulk (up to 100 rows, the rest are ignored by Reddit). * Requires mod privileges on the subreddit. If the CSS class and text are empty/null for a particular user, that * user's flair is cleared. * * Note that even if this call succeeds, reddit may still have rejected one or more of the changes. Make sure to * check the [FlairPatchReport]s that this method returns. */ @EndpointImplementation(Endpoint.POST_FLAIRCSV) fun patchFlairList(patch: List<SimpleFlairInfo>): List<FlairPatchReport> { return reddit.request { it.path("/r/$subreddit/api/flaircsv") .post(mapOf( "flair_csv" to (patch.joinToString(separator = "\n") { it.toCsvLine() }) )) }.deserializeWith(JrawUtils.moshi.adapter(Types.newParameterizedType(List::class.java, FlairPatchReport::class.java))) } /** */ companion object { private val listOfFlairsType = Types.newParameterizedType(List::class.java, Flair::class.java) } }
mit
e05737caa91de271a30830cba70b8167
38.690476
127
0.668566
4.495281
false
false
false
false
realm/realm-java
realm/realm-library/src/androidTestObjectServer/kotlin/io/realm/transport/HttpNetworkTransportInterceptor.kt
1
2061
/* * Copyright 2021 Realm 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 io.realm.transport import io.realm.internal.network.OkHttpNetworkTransport import io.realm.internal.objectstore.OsJavaNetworkTransport import io.realm.mongodb.log.obfuscator.HttpLogObfuscator /** * This class intercepts the response of an HTTP request instead of passing it on to ObjectStore. * This enables us to query it later. */ typealias Observer = (response: OsJavaNetworkTransport.Response) -> Unit class HttpNetworkTransportInterceptor(private val passOnToObjectStore: Boolean = false, obfuscator: HttpLogObfuscator?) : OkHttpNetworkTransport(obfuscator) { private var observer: Observer? = null var preExecuteAction : (() -> Unit)? = null override fun handleResponse( response: OsJavaNetworkTransport.Response, completionBlockPtr: Long ) { observer?.let { it(response) } if (passOnToObjectStore) { super.handleResponse(response, completionBlockPtr) } } override fun executeRequest( method: String, url: String, timeoutMs: Long, headers: MutableMap<String, String>, body: String ): OsJavaNetworkTransport.Response { preExecuteAction?.let { it() } return super.executeRequest(method, url, timeoutMs, headers, body) } fun observeResponses(callback: (response: OsJavaNetworkTransport.Response) -> Unit) { observer = callback } }
apache-2.0
91bd6bd6bf9b22e7361fa53896ddb692
32.786885
108
0.694323
4.385106
false
false
false
false
square/wire
wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/WireTest.kt
1
3106
/* * Copyright 2019 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.squareup.wire.protos.kotlin.person.Person import com.squareup.wire.protos.kotlin.simple.ExternalMessage import com.squareup.wire.protos.kotlin.simple.SimpleMessage import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class WireTest { @Test fun simpleMessage() { var msg = SimpleMessage(required_int32 = 456) assertNull(msg.optional_int32) assertNull(msg.optional_nested_msg) assertNull(msg.optional_external_msg) assertNull(msg.default_nested_enum) assertEquals(456, msg.required_int32) assertNotNull(msg.repeated_double) assertEquals(0, msg.repeated_double.size) val doubles = listOf(1.0, 2.0, 3.0) msg = msg.copy( optional_int32 = 789, optional_nested_msg = SimpleMessage.NestedMessage(bb = 2), optional_external_msg = ExternalMessage(f = 99.9f), default_nested_enum = SimpleMessage.NestedEnum.BAR, required_int32 = 456, repeated_double = doubles ) assertEquals(789, msg.optional_int32) assertEquals(2, msg.optional_nested_msg!!.bb) assertFloatEquals(99.9f, msg.optional_external_msg!!.f!!) assertEquals(SimpleMessage.NestedEnum.BAR, msg.default_nested_enum) assertEquals(456, msg.required_int32) assertEquals(doubles, msg.repeated_double) // Rebuilding will use the new list msg = msg.copy() assertEquals(doubles, msg.repeated_double) val adapter = SimpleMessage.ADAPTER val result = adapter.encode(msg) assertEquals(46, result.size) val newMsg = adapter.decode(result) assertEquals(789, newMsg.optional_int32) assertEquals(2, newMsg.optional_nested_msg!!.bb) assertFloatEquals(99.9f, newMsg.optional_external_msg!!.f!!) assertEquals(SimpleMessage.NestedEnum.BAR, newMsg.default_nested_enum) assertEquals(456, newMsg.required_int32) assertEquals(doubles, msg.repeated_double) } @Test fun sanitizedToString() { val person = Person( id = 1, name = "Such, I mean it, such [a] {funny} name.", phone = listOf(Person.PhoneNumber(number = "123,456,789")), aliases = listOf("B-lo,ved", "D{esperado}") ) val expected = """Person{ |name=Such\, I mean it\, such \[a\] \{funny\} name. |, id=1 |, phone=[PhoneNumber{number=123\,456\,789}] |, aliases=[B-lo\,ved, D\{esperado\}] |}""".trimMargin().replace("\n", "") assertEquals(expected, person.toString()) } }
apache-2.0
dcb6c15d90f9bd20638282ad10e15e5f
35.116279
75
0.698326
3.702026
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteCodeMigrationInspection.kt
2
8207
// 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.inspections.migration import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.* import com.intellij.codeInspection.actions.RunInspectionIntention import com.intellij.codeInspection.ex.InspectionManagerEx import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.openapi.project.Project import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.migration.MigrationInfo import org.jetbrains.kotlin.idea.migration.isLanguageVersionUpdate import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents internal abstract class ObsoleteCodeMigrationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool, MigrationFix { protected abstract val fromVersion: LanguageVersion protected abstract val toVersion: LanguageVersion protected abstract val problemReporters: List<ObsoleteCodeProblemReporter> final override fun isApplicable(migrationInfo: MigrationInfo): Boolean { return migrationInfo.isLanguageVersionUpdate(fromVersion, toVersion) } final override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): KtVisitorVoid { return simpleNameExpressionVisitor(fun(simpleNameExpression) { val versionIsSatisfied = simpleNameExpression.languageVersionSettings.languageVersion >= toVersion if (!versionIsSatisfied && !isUnitTestMode()) { return } for (reporter in problemReporters) { if (reporter.report(holder, isOnTheFly, simpleNameExpression)) { return } } }) } } internal interface ObsoleteCodeProblemReporter { fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean } internal interface ObsoleteCodeFix { fun applyFix(project: Project, descriptor: ProblemDescriptor) } // Shortcut quick fix for running inspection in the project scope. // Should work like RunInspectionAction.runInspection. internal abstract class ObsoleteCodeInWholeProjectFix : LocalQuickFix { protected abstract val inspectionName: String final override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val toolWrapper = InspectionProjectProfileManager.getInstance(project).currentProfile.getInspectionTool(inspectionName, project)!! runToolInProject(project, toolWrapper) } final override fun startInWriteAction(): Boolean = false private fun runToolInProject(project: Project, toolWrapper: InspectionToolWrapper<*, *>) { val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx val kotlinSourcesScope: GlobalSearchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.allScope(project), project) val cleanupScope = AnalysisScope(kotlinSourcesScope, project) val cleanupToolProfile = runInInspectionProfileInitMode { RunInspectionIntention.createProfile(toolWrapper, managerEx, null) } managerEx.createNewGlobalContext().codeCleanup( cleanupScope, cleanupToolProfile, KotlinBundle.message("apply.in.the.project.0", toolWrapper.displayName), null, false ) } // Overcome failure during profile creating because of absent tools in tests private inline fun <T> runInInspectionProfileInitMode(runnable: () -> T): T { return if (!isUnitTestMode()) { runnable() } else { val old = InspectionProfileImpl.INIT_INSPECTIONS try { InspectionProfileImpl.INIT_INSPECTIONS = true runnable() } finally { InspectionProfileImpl.INIT_INSPECTIONS = old } } } } /** * There should be a single fix class with the same family name, this way it can be executed for all found problems from UI. */ internal abstract class ObsoleteCodeFixDelegateQuickFix(private val delegate: ObsoleteCodeFix) : LocalQuickFix { final override fun applyFix(project: Project, descriptor: ProblemDescriptor) { delegate.applyFix(project, descriptor) } } internal abstract class ObsoleteImportsUsageReporter : ObsoleteCodeProblemReporter { /** * Required to report the problem only on one psi element instead of the every single qualifier * in the import statement. */ protected abstract val textMarker: String protected abstract val packageBindings: Map<String, String> protected open val importsToRemove: Set<String> = emptySet() protected abstract val wholeProjectFix: LocalQuickFix @Nls protected abstract fun problemMessage(): String protected abstract fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix final override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean { if (simpleNameExpression.text != textMarker) return false val parent = simpleNameExpression.parent as? KtExpression ?: return false val reportExpression = parent as? KtDotQualifiedExpression ?: simpleNameExpression findBinding(simpleNameExpression) ?: return false holder.registerProblem( reportExpression, problemMessage(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixesWithWholeProject(isOnTheFly, wrapFix(ObsoleteImportFix()), wholeProjectFix) ) return true } private fun findBinding(simpleNameExpression: KtSimpleNameExpression): Binding? { if (simpleNameExpression.text != textMarker) return null val importDirective = simpleNameExpression.parents .takeWhile { it is KtDotQualifiedExpression || it is KtImportDirective } .lastOrNull() as? KtImportDirective ?: return null val fqNameStr = importDirective.importedFqName?.asString() ?: return null val bindEntry = packageBindings.entries.find { (affectedImportPrefix, _) -> fqNameStr.startsWith(affectedImportPrefix) } ?: return null return Binding( FqName(bindEntry.value), fqNameStr in importsToRemove, importDirective ) } private inner class ObsoleteImportFix : ObsoleteCodeFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val simpleNameExpression = when (val element = descriptor.psiElement) { is KtSimpleNameExpression -> element is KtDotQualifiedExpression -> element.selectorExpression as? KtSimpleNameExpression else -> null } ?: return val binding = findBinding(simpleNameExpression) ?: return if (binding.shouldRemove) { binding.importDirective.delete() } else { simpleNameExpression.mainReference.bindToFqName( binding.bindTo, shorteningMode = KtSimpleNameReference.ShorteningMode.NO_SHORTENING ) } } } private class Binding( val bindTo: FqName, val shouldRemove: Boolean, val importDirective: KtImportDirective ) }
apache-2.0
1e7fdf98c04d01ed8d915f73847f51ad
41.087179
138
0.726697
5.52288
false
false
false
false
PolymerLabs/arcs
javatests/arcs/android/host/TestExternalArcHostService.kt
1
2738
package arcs.android.host import android.app.Service import android.content.Context import android.content.Intent import android.os.IBinder import arcs.core.data.Capabilities import arcs.core.data.Capability.Shareable import arcs.core.host.HandleManagerFactory import arcs.core.host.ParticleRegistration import arcs.core.host.SchedulerProvider import arcs.core.host.SimpleSchedulerProvider import arcs.core.host.TestingHost import arcs.core.storage.StorageKeyManager import arcs.jvm.util.testutil.FakeTime import arcs.sdk.android.labs.host.ArcHostHelper import arcs.sdk.android.labs.host.ResurrectableHost import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager import arcs.sdk.android.storage.ResurrectionHelper import arcs.sdk.android.storage.service.BindHelper import arcs.sdk.android.storage.service.DefaultBindHelper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel @OptIn(ExperimentalCoroutinesApi::class) abstract class TestExternalArcHostService : Service() { protected val scope: CoroutineScope = MainScope() abstract val arcHost: TestingAndroidHost val schedulerProvider = SimpleSchedulerProvider(Dispatchers.Default) // TODO(b/174432505): Don't use the GLOBAL_INSTANCE, use a test-specific instance. private val storageKeyManager = StorageKeyManager.GLOBAL_INSTANCE private val arcHostHelper: ArcHostHelper by lazy { ArcHostHelper(this, storageKeyManager, arcHost) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val result = super.onStartCommand(intent, flags, startId) arcHostHelper.onStartCommand(intent) return result } override fun onBind(intent: Intent?): IBinder? = null override fun onDestroy() { super.onDestroy() scope.cancel() } @OptIn(ExperimentalCoroutinesApi::class) abstract class TestingAndroidHost( context: Context, scope: CoroutineScope, schedulerProvider: SchedulerProvider, vararg particles: ParticleRegistration ) : TestingHost( handleManagerFactory = HandleManagerFactory( schedulerProvider = schedulerProvider, storageEndpointManager = AndroidStorageServiceEndpointManager( scope, testBindHelper ?: DefaultBindHelper(context) ), platformTime = FakeTime() ), arcHostContextCapabilities = testingCapability, *particles ), ResurrectableHost { override val resurrectionHelper: ResurrectionHelper = ResurrectionHelper(context) } companion object { var testBindHelper: BindHelper? = null var testingCapability = Capabilities(Shareable(true)) } }
bsd-3-clause
f06ba0f36ea3021d5581553c8209e217
31.987952
84
0.792184
4.656463
false
true
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleTask.kt
1
8052
package com.bajdcc.LALR1.interpret.module import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.* import com.bajdcc.OP.grammar.error.GrammarException import com.bajdcc.OP.grammar.handler.IPatternHandler import com.bajdcc.OP.syntax.handler.SyntaxException import com.bajdcc.util.ResourceLoader import com.bajdcc.util.lexer.error.RegexException import com.bajdcc.util.lexer.token.OperatorType import com.bajdcc.util.lexer.token.Token import com.bajdcc.util.lexer.token.TokenType import org.apache.log4j.Logger import java.text.SimpleDateFormat import java.util.* @Suppress("UNUSED_ANONYMOUS_PARAMETER") /** * 【模块】服务模块 * * @author bajdcc */ class ModuleTask : IInterpreterModule { private var runtimeCodePage: RuntimeCodePage? = null override val moduleName: String get() = "sys.task" override val moduleCode: String get() = ResourceLoader.load(javaClass) override val codePage: RuntimeCodePage @Throws(Exception::class) get() { if (runtimeCodePage != null) return runtimeCodePage!! val base = ResourceLoader.load(javaClass) val grammar = Grammar(base) val page = grammar.codePage val info = page.info buildSystemMethod(info) buildUtilMethod(info) runtimeCodePage = page return page } private fun buildSystemMethod(info: IRuntimeDebugInfo) { info.addExternalFunc("g_task_get_time", RuntimeDebugExec("获取当前时间", arrayOf(RuntimeObjectType.kString)) { args: List<RuntimeObject>, status: IRuntimeStatus -> run { val format = args[0].obj.toString() RuntimeObject(SimpleDateFormat(format).format(Date())) } }) info.addExternalFunc("g_task_get_pipe_stat", RuntimeDebugExec("获取管道信息") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.pipeService.stat(false)) }) info.addExternalFunc("g_task_get_share_stat", RuntimeDebugExec("获取共享信息") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.shareService.stat(false)) }) info.addExternalFunc("g_task_get_file_stat", RuntimeDebugExec("获取文件信息") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.fileService.stat(false)) }) info.addExternalFunc("g_task_get_vfs_stat", RuntimeDebugExec("获取虚拟文件信息") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.fileService.getVfsList(false)) }) info.addExternalFunc("g_task_get_user_stat", RuntimeDebugExec("获取用户服务信息") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.userService.stat(false)) }) info.addExternalFunc("g_task_get_guid", RuntimeDebugExec("获取GUID") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(guid.toString()) }) info.addExternalFunc("g_task_sys_speed", RuntimeDebugExec("获取虚拟机运行速度") { args: List<RuntimeObject>, status: IRuntimeStatus -> RuntimeObject(status.service.processService.speed) }) } private fun buildUtilMethod(info: IRuntimeDebugInfo) { info.addExternalFunc("g_task_calc", RuntimeDebugExec("四则运算", arrayOf(RuntimeObjectType.kString)) { args: List<RuntimeObject>, status: IRuntimeStatus -> run { val expr = args[0].obj.toString() RuntimeObject(util_calc(expr)) } }) } companion object { val instance = ModuleTask() private val logger = Logger.getLogger("task") val TASK_NUM = 16 private val guid = UUID.randomUUID() private fun util_calc(expr: String): String { try { val grammar = com.bajdcc.OP.grammar.Grammar(expr) grammar.addTerminal("i", TokenType.INTEGER, null) grammar.addTerminal("PLUS", TokenType.OPERATOR, OperatorType.PLUS) grammar.addTerminal("MINUS", TokenType.OPERATOR, OperatorType.MINUS) grammar.addTerminal("TIMES", TokenType.OPERATOR, OperatorType.TIMES) grammar.addTerminal("DIVIDE", TokenType.OPERATOR, OperatorType.DIVIDE) grammar.addTerminal("LPA", TokenType.OPERATOR, OperatorType.LPARAN) grammar.addTerminal("RPA", TokenType.OPERATOR, OperatorType.RPARAN) val nons = arrayOf("E", "T", "F") for (non in nons) { grammar.addNonTerminal(non) } grammar.addPatternHandler("1", object : IPatternHandler { override fun handle(tokens: List<Token>, symbols: List<Any>): Any { return Integer.parseInt(tokens[0].obj!!.toString()) } override val patternName: String get() = "操作数转换" }) grammar.addPatternHandler("010", object : IPatternHandler { override fun handle(tokens: List<Token>, symbols: List<Any>): Any { val lop = symbols[0] as Int val rop = symbols[1] as Int val op = tokens[0] if (op.type === TokenType.OPERATOR) { val kop = op.obj as OperatorType? when (kop) { OperatorType.PLUS -> return lop + rop OperatorType.MINUS -> return lop - rop OperatorType.TIMES -> return lop * rop OperatorType.DIVIDE -> return if (rop == 0) { lop } else { lop / rop } else -> return 0 } } else { return 0 } } override val patternName: String get() = "二元运算\"" }) grammar.addPatternHandler("101", object : IPatternHandler { override fun handle(tokens: List<Token>, symbols: List<Any>): Any? { val ltok = tokens[0] val rtok = tokens[1] val exp = symbols[0] return if (ltok.obj === OperatorType.LPARAN && rtok.obj === OperatorType.RPARAN) {// 判断括号 exp } else null } override val patternName: String get() = "括号运算" }) grammar.infer("E -> E @PLUS T | E @MINUS T | T") grammar.infer("T -> T @TIMES F | T @DIVIDE F | F") grammar.infer("F -> @LPA E @RPA | @i") grammar.initialize("E") return grammar.run().toString() } catch (e: RegexException) { logger.error("#CALC# Error: " + e.position + "," + e.message) } catch (e: SyntaxException) { logger.error("#CALC#Error: " + e.position + "," + e.message + " " + e.info) } catch (e: GrammarException) { logger.error("#CALC#Error: " + e.position + "," + e.message + " " + e.info) } return "#CALC#Error" } } }
mit
c76d5ee6a948e342bee4d3b44cfaf085
43.089385
133
0.52965
4.941766
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/ScanFragment.kt
1
8449
package org.wordpress.android.ui.jetpack.scan import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.ScanFragmentBinding import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.ActivityLauncher import org.wordpress.android.ui.accounts.HelpActivity.Origin.SCAN_SCREEN_HELP import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.OpenFixThreatsConfirmationDialog import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.ShowContactSupport import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.ShowJetpackSettings import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.ShowThreatDetails import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.VisitVaultPressDashboard import org.wordpress.android.ui.jetpack.scan.ScanViewModel.UiState.ContentUiState import org.wordpress.android.ui.jetpack.scan.ScanViewModel.UiState.ErrorUiState import org.wordpress.android.ui.jetpack.scan.ScanViewModel.UiState.FullScreenLoadingUiState import org.wordpress.android.ui.jetpack.scan.adapters.HorizontalMarginItemDecoration import org.wordpress.android.ui.jetpack.scan.adapters.ScanAdapter import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.ColorUtils import org.wordpress.android.util.image.ImageManager import org.wordpress.android.viewmodel.observeEvent import org.wordpress.android.widgets.WPSnackbar import javax.inject.Inject class ScanFragment : Fragment(R.layout.scan_fragment) { @Inject lateinit var imageManager: ImageManager @Inject lateinit var uiHelpers: UiHelpers @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: ScanViewModel private var fixThreatsConfirmationDialog: AlertDialog? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(ScanFragmentBinding.bind(view)) { initDagger() initRecyclerView() initViewModel(getSite(savedInstanceState)) } } private fun initDagger() { (requireActivity().application as WordPress).component().inject(this) } private fun ScanFragmentBinding.initRecyclerView() { recyclerView.itemAnimator = null recyclerView.addItemDecoration( HorizontalMarginItemDecoration(resources.getDimensionPixelSize(R.dimen.margin_extra_large)) ) initAdapter() initActionableEmptyView() } private fun ScanFragmentBinding.initActionableEmptyView() { recyclerView.setEmptyView(actionableEmptyView) uiHelpers.updateVisibility(actionableEmptyView, false) } private fun ScanFragmentBinding.initAdapter() { recyclerView.adapter = ScanAdapter(imageManager, uiHelpers) } private fun ScanFragmentBinding.initViewModel(site: SiteModel) { viewModel = ViewModelProvider(this@ScanFragment, viewModelFactory).get(ScanViewModel::class.java) setupObservers() viewModel.start(site) } private fun ScanFragmentBinding.setupObservers() { viewModel.uiState.observe( viewLifecycleOwner, { uiState -> uiHelpers.updateVisibility(progressBar, uiState.loadingVisible) uiHelpers.updateVisibility(recyclerView, uiState.contentVisible) uiHelpers.updateVisibility(actionableEmptyView, uiState.errorVisible) when (uiState) { is ContentUiState -> updateContentLayout(uiState) is FullScreenLoadingUiState -> { // Do Nothing } is ErrorUiState.NoConnection, is ErrorUiState.GenericRequestFailed, is ErrorUiState.ScanRequestFailed, is ErrorUiState.MultisiteNotSupported, is ErrorUiState.VaultPressActiveOnSite -> updateErrorLayout(uiState as ErrorUiState) } } ) viewModel.snackbarEvents.observeEvent(viewLifecycleOwner, { it.showSnackbar() }) viewModel.navigationEvents.observeEvent( viewLifecycleOwner ) { events -> when (events) { is OpenFixThreatsConfirmationDialog -> showFixThreatsConfirmationDialog(events) is ShowThreatDetails -> ActivityLauncher.viewThreatDetails( this@ScanFragment, events.siteModel, events.threatId ) is ShowContactSupport -> ActivityLauncher.viewHelpAndSupport(requireContext(), SCAN_SCREEN_HELP, events.site, null) is ShowJetpackSettings -> ActivityLauncher.openUrlExternal(context, events.url) is VisitVaultPressDashboard -> ActivityLauncher.openUrlExternal(context, events.url) } } } private fun ScanFragmentBinding.updateContentLayout(state: ContentUiState) { ((recyclerView.adapter) as ScanAdapter).update(state.items) } private fun ScanFragmentBinding.updateErrorLayout(state: ErrorUiState) { uiHelpers.setTextOrHide(actionableEmptyView.title, state.title) uiHelpers.setTextOrHide(actionableEmptyView.subtitle, state.subtitle) actionableEmptyView.image.setImageResource(state.image) state.imageColorResId?.let { ColorUtils.setImageResourceWithTint(actionableEmptyView.image, state.image, it) } ?: actionableEmptyView.image.setImageResource(state.image) state.buttonText?.let { uiHelpers.setTextOrHide(actionableEmptyView.button, state.buttonText) } state.action?.let { action -> actionableEmptyView.button.setOnClickListener { action.invoke() } } } private fun SnackbarMessageHolder.showSnackbar() { view?.let { val snackbar = WPSnackbar.make( it, uiHelpers.getTextOfUiString(requireContext(), message), Snackbar.LENGTH_LONG ) snackbar.show() } } private fun showFixThreatsConfirmationDialog(holder: OpenFixThreatsConfirmationDialog) { fixThreatsConfirmationDialog = MaterialAlertDialogBuilder(requireActivity()) .setTitle(uiHelpers.getTextOfUiString(requireContext(), holder.title)) .setMessage(uiHelpers.getTextOfUiString(requireContext(), holder.message)) .setPositiveButton(holder.positiveButtonLabel) { _, _ -> holder.okButtonAction.invoke() } .setNegativeButton(holder.negativeButtonLabel) { _, _ -> fixThreatsConfirmationDialog?.dismiss() } .setCancelable(true) .create() fixThreatsConfirmationDialog?.show() } override fun onPause() { super.onPause() fixThreatsConfirmationDialog?.dismiss() } private fun getSite(savedInstanceState: Bundle?): SiteModel { return if (savedInstanceState == null) { requireActivity().intent.getSerializableExtra(WordPress.SITE) as SiteModel } else { savedInstanceState.getSerializable(WordPress.SITE) as SiteModel } } override fun onSaveInstanceState(outState: Bundle) { outState.putSerializable(WordPress.SITE, viewModel.site) super.onSaveInstanceState(outState) } fun onNewIntent(intent: Intent?) { intent?.let { val threatId = intent.getLongExtra(ScanActivity.REQUEST_FIX_STATE, 0L) val messageRes = intent.getIntExtra(ScanActivity.REQUEST_SCAN_STATE, 0) if (threatId > 0L) { viewModel.onFixStateRequested(threatId) } else if (messageRes > 0) { viewModel.onScanStateRequestedWithMessage(messageRes) } } } companion object { const val ARG_THREAT_ID = "arg_threat_id" } }
gpl-2.0
3e351c316cb55267c1a0dfa9358bc5fa
42.107143
114
0.695822
5.357641
false
false
false
false
NCBSinfo/NCBSinfo
app/src/main/java/com/rohitsuratekar/NCBSinfo/models/Contact.kt
2
652
package com.rohitsuratekar.NCBSinfo.models class Contact { enum class AREA { NAME, EXTENSION, EXTRA_NUMBERS, DETAILS } var type: String? = null var name: String? = null var primaryExtension: String? = null var otherExtensions: String? = null var details: String? = null var searchString = "" val searchArea = mutableListOf<AREA>() fun extraExtensions(): List<String> { val tempList = mutableListOf<String>() otherExtensions?.let { for (c in it.split(",")) { tempList.add(c) } } return tempList } }
mit
6ad78937c75296cb18c6ebd3c4f72882
22.222222
47
0.56135
4.690647
false
false
false
false
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/common/fcm/MyFirebaseInstanceIDService.kt
1
2816
package com.microland.microlandone.firebase.utils import android.content.Context import android.content.Intent import android.util.Log import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceIdService import io.skytreasure.kotlingroupchat.chat.MyChatManager import io.skytreasure.kotlingroupchat.common.constants.AppConstants class MyFirebaseInstanceIDService : FirebaseInstanceIdService() { companion object { private val TAG = "MyFirebaseIIDService" } override fun onTokenRefresh() { sendRegistrationToServer(FirebaseInstanceId.getInstance().token) } private fun sendRegistrationToServer(token: String?) { val i = Intent() i.action = AppConstants.NOTIFICATION_ID_REFRESHED i.putExtra(AppConstants.NEW_TOKEN, token) sendBroadcast(i) MyChatManager.updateFCMTokenAndDeviceId(this, token!!) /*if (token != null && token.isNotBlank()) { FirebaseUtils.saveFCMToSharedPref(this, token, "", "") FirebaseUtils.saveFCMonRTDB(context = this) } val sharedPrefs = getSharedPreferences("FCM", Context.MODE_PRIVATE) sharedPrefs.edit().putString("token", token).apply() val deviceID = sharedPrefs.getString("device_id", "") val myUID = sharedPrefs.getString("emp_uid", "") Log.e(TAG, String.format("\nNEW_TOKEN\nuid: %s,\ndevice_id: %s,\nfcm_ids: %s\n", myUID, deviceID, token)) if (myUID!!.trim { it <= ' ' } != "" && myUID.matches("/^uid-[1-9][0-9]*$/".toRegex())) { sharedPrefs.edit().putString("token", token).apply() } else { FirebaseDatabase.getInstance().reference.child("devices").child(deviceID!!).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists() && dataSnapshot.value != null && dataSnapshot.value !== myUID) { val existingUID = dataSnapshot.value!!.toString() dataSnapshot.ref.child("fcm_ids").child(existingUID).child(deviceID).removeValue() } FirebaseDatabase.getInstance().reference.child("devices").child(deviceID).setValue(myUID) FirebaseDatabase.getInstance().reference.child("fcm_ids").child(myUID).child(deviceID).setValue(token) } override fun onCancelled(databaseError: DatabaseError) { Log.e(TAG, "Push Error") } }) }*/ } }
mit
1ba8fa725a38b25e46fb6a014d355e14
43.698413
148
0.660866
4.601307
false
false
false
false
ingokegel/intellij-community
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/OutputEventSplitter.kt
8
4618
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.testframework.sm.runner import com.intellij.execution.impl.ConsoleBuffer import com.intellij.execution.process.ProcessOutputType import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.util.Key import com.intellij.smRunner.OutputEventSplitterBase import jetbrains.buildServer.messages.serviceMessages.ServiceMessage /** * External test runner sends plain text along with service messages ([ServiceMessage]) to [process]. * Test runner sends data as stream and flushes it periodically. On each flush [process] is called. * That means [ServiceMessage] may be [process]ed in the middle. * * This class handles such cases by buffering service messages. * It then calls [onTextAvailable] for text or message. It is guaranteed that each call of [onTextAvailable] either contains * plain text or begins with [ServiceMessage] and ends with "\n". * * Current implementation supports only [ServiceMessage]s that end with new line. * * After process ends, call [flush] to process remain. * * Class is not thread safe in that matter that you can't call [process] for same stream (i.e. stderr) from different threads, * but [flush] could be called from any thread. * * If [bufferTextUntilNewLine] is set, any output/err (including service messages) is buffered until newline arrives. * Otherwise, this is done only for service messages. * It is recommended not to enable [bufferTextUntilNewLine] because it gives user ability to see text as fast as possible. * In some cases like when there is a separate protocol exists on top of text message that does not support messages * flushed in random places, this option must be enabled. * * If [cutNewLineBeforeServiceMessage] is set, each service message must have "\n" prefix which is cut. * */ abstract class OutputEventSplitter(private val bufferTextUntilNewLine: Boolean = false, private val cutNewLineBeforeServiceMessage: Boolean = false) : OutputEventSplitterBase<ProcessOutputType>(ServiceMessage.SERVICE_MESSAGE_START, bufferTextUntilNewLine, cutNewLineBeforeServiceMessage) { companion object { private val USE_CYCLE_BUFFER = ConsoleBuffer.useCycleBuffer() private val stdout = OutputType(ProcessOutputType.STDOUT, OutputStreamType.STDOUT) private val stderr = OutputType(ProcessOutputType.STDERR, OutputStreamType.STDERR) private val system = OutputType(ProcessOutputType.SYSTEM, OutputStreamType.SYSTEM) } /** * [processOutputType] could be one of [ProcessOutputTypes] or any other [ProcessOutputType]. * Only stdout ([ProcessOutputType.isStdout]) accepts Teamcity Messages ([ServiceMessage]). * * Stderr and System are flushed automatically unless [bufferTextUntilNewLine], * Stdout may be buffered until the end of the message. * Make sure you do not process same type from different threads. */ fun process(text: String, processOutputType: Key<*>) { val outputType = (processOutputType as? ProcessOutputType)?.toOutputType() if (outputType != null) { process(text, outputType) } else { onTextAvailableInternal(text, processOutputType) } } /** * For stderr and system [text] is provided as fast as possible unless [bufferTextUntilNewLine]. * For stdout [text] is either TC message that starts from [ServiceMessage.SERVICE_MESSAGE_START] and ends with new line * or chunk of process output * */ abstract fun onTextAvailable(text: String, outputType: Key<*>) final override fun onTextAvailable(text: String, outputType: OutputType<ProcessOutputType>) { onTextAvailableInternal(text, outputType.data) } private fun onTextAvailableInternal(text: String, processOutputType: Key<*>) { val textToAdd = if (USE_CYCLE_BUFFER) cutLineIfTooLong(text) else text onTextAvailable(textToAdd, processOutputType) } private fun ProcessOutputType.toOutputType(): OutputType<ProcessOutputType> { return when (this) { ProcessOutputType.STDOUT -> stdout ProcessOutputType.STDERR -> stderr ProcessOutputType.SYSTEM -> system else -> { val streamType = when (baseOutputType) { ProcessOutputType.STDOUT -> OutputStreamType.STDOUT ProcessOutputType.STDERR -> OutputStreamType.STDERR ProcessOutputType.SYSTEM -> OutputStreamType.SYSTEM else -> OutputStreamType.STDOUT } OutputType(this, streamType) } } } }
apache-2.0
3819665959693ef69dfb60851b13f834
46.132653
140
0.749026
4.731557
false
false
false
false
ACRA/acra
acra-http/src/main/java/org/acra/sender/HttpSender.kt
1
9162
/* * Copyright (c) 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.acra.sender import android.content.Context import android.net.Uri import org.acra.ACRA import org.acra.ReportField import org.acra.attachment.DefaultAttachmentProvider import org.acra.config.CoreConfiguration import org.acra.config.HttpSenderConfiguration import org.acra.config.getPluginConfiguration import org.acra.data.CrashReportData import org.acra.data.StringFormat import org.acra.http.BinaryHttpRequest import org.acra.http.DefaultHttpRequest import org.acra.http.MultipartHttpRequest import org.acra.log.debug import org.acra.sender.HttpSender.Method import org.acra.util.InstanceCreator import org.acra.util.UriUtils import java.io.FileNotFoundException import java.io.IOException import java.net.MalformedURLException import java.net.URL /** * The [ReportSender] used by ACRA for http sending * * Create a new HttpPostSender instance with a fixed destination provided as * a parameter. Configuration changes to the formUri are not applied. * * * @param config AcraConfig declaring the * @param method HTTP [Method] to be used to send data. Currently only [Method.POST] and [Method.PUT] are available. * If [Method.PUT] is used, the [ReportField.REPORT_ID] is appended to the formUri to be compliant with RESTful APIs. * @param type [StringFormat] of encoding used to send the report body. * [StringFormat.KEY_VALUE_LIST] is a simple Key/Value pairs list as defined by the application/x-www-form-urlencoded mime type. * @param formUri The URL of your server-side crash report collection script. */ /** * * * Create a new HttpSender instance with its destination taken from the supplied config. * * * @param config AcraConfig declaring the * @param method HTTP [Method] to be used to send data. Currently only [Method.POST] and [Method.PUT] are available. * If [Method.PUT] is used, the [ReportField.REPORT_ID] is appended to the formUri to be compliant with RESTful APIs. * @param type [StringFormat] of encoding used to send the report body. * [StringFormat.KEY_VALUE_LIST] is a simple Key/Value pairs list as defined by the application/x-www-form-urlencoded mime type. * @author F43nd1r &amp; Various */ @Suppress("unused") class HttpSender @JvmOverloads constructor(private val config: CoreConfiguration, method: Method?, type: StringFormat?, formUri: String? = null) : ReportSender { private val httpConfig: HttpSenderConfiguration = config.getPluginConfiguration() private val mFormUri: Uri = Uri.parse(formUri ?: httpConfig.uri) private val mMethod: Method = method ?: httpConfig.httpMethod private val mType: StringFormat = type ?: config.reportFormat private var mUsername: String? = null private var mPassword: String? = null /** * * * Set credentials for this HttpSender that override (if present) the ones set globally. * * * @param username The username to set for HTTP Basic Auth. * @param password The password to set for HTTP Basic Auth. */ fun setBasicAuth(username: String?, password: String?) { mUsername = username mPassword = password } @Throws(ReportSenderException::class) override fun send(context: Context, errorContent: CrashReportData) { try { val baseUrl = mFormUri.toString() debug { "Connect to $baseUrl" } val login: String? = when { mUsername != null -> mUsername !httpConfig.basicAuthLogin.isNullOrEmpty() -> httpConfig.basicAuthLogin else -> null } val password: String? = when { mPassword != null -> mPassword !httpConfig.basicAuthPassword.isNullOrEmpty() -> httpConfig.basicAuthPassword else -> null } val uris = InstanceCreator.create(config.attachmentUriProvider) { DefaultAttachmentProvider() }.getAttachments(context, config) // Generate report body depending on requested type val reportAsString = convertToString(errorContent, mType) // Adjust URL depending on method val reportUrl = mMethod.createURL(baseUrl, errorContent) sendHttpRequests( config, context, mMethod, mType.matchingHttpContentType, login, password, httpConfig.connectionTimeout, httpConfig.socketTimeout, httpConfig.httpHeaders, reportAsString, reportUrl, uris ) } catch (e: Exception) { throw ReportSenderException("Error while sending " + config.reportFormat.toString() + " report via Http " + mMethod.name, e) } } @Throws(IOException::class) protected fun sendHttpRequests( configuration: CoreConfiguration, context: Context, method: Method, contentType: String, login: String?, password: String?, connectionTimeOut: Int, socketTimeOut: Int, headers: Map<String, String>?, content: String, url: URL, attachments: List<Uri> ) { when (method) { Method.POST -> if (attachments.isEmpty()) { sendWithoutAttachments(configuration, context, method, contentType, login, password, connectionTimeOut, socketTimeOut, headers, content, url) } else { postMultipart(configuration, context, contentType, login, password, connectionTimeOut, socketTimeOut, headers, content, url, attachments) } Method.PUT -> { sendWithoutAttachments(configuration, context, method, contentType, login, password, connectionTimeOut, socketTimeOut, headers, content, url) for (uri in attachments) { putAttachment(configuration, context, login, password, connectionTimeOut, socketTimeOut, headers, url, uri) } } } } @Throws(IOException::class) protected fun sendWithoutAttachments( configuration: CoreConfiguration, context: Context, method: Method, contentType: String, login: String?, password: String?, connectionTimeOut: Int, socketTimeOut: Int, headers: Map<String, String>?, content: String, url: URL ) { DefaultHttpRequest(configuration, context, method, contentType, login, password, connectionTimeOut, socketTimeOut, headers).send(url, content) } @Throws(IOException::class) protected fun postMultipart( configuration: CoreConfiguration, context: Context, contentType: String, login: String?, password: String?, connectionTimeOut: Int, socketTimeOut: Int, headers: Map<String, String>?, content: String, url: URL, attachments: List<Uri> ) { MultipartHttpRequest(configuration, context, contentType, login, password, connectionTimeOut, socketTimeOut, headers).send(url, content to attachments) } @Throws(IOException::class) protected fun putAttachment( configuration: CoreConfiguration, context: Context, login: String?, password: String?, connectionTimeOut: Int, socketTimeOut: Int, headers: Map<String, String>?, url: URL, attachment: Uri ) { try { val attachmentUrl = URL(url.toString() + "-" + UriUtils.getFileNameFromUri(context, attachment)) BinaryHttpRequest(configuration, context, login, password, connectionTimeOut, socketTimeOut, headers).send(attachmentUrl, attachment) } catch (e: FileNotFoundException) { ACRA.log.w("Not sending attachment", e) } } /** * Convert a report to string * * @param report the report to convert * @param format the format to convert to * @return a string representation of the report * @throws Exception if conversion failed */ @Throws(Exception::class) protected fun convertToString(report: CrashReportData?, format: StringFormat): String { return format.toFormattedString(report!!, config.reportContent, "&", "\n", true) } /** * Available HTTP methods to send data. Only POST and PUT are currently * supported. */ enum class Method { POST { @Throws(MalformedURLException::class) override fun createURL(baseUrl: String, report: CrashReportData): URL = URL(baseUrl) }, PUT { @Throws(MalformedURLException::class) override fun createURL(baseUrl: String, report: CrashReportData): URL = URL(baseUrl + '/' + report.getString(ReportField.REPORT_ID)) }; @Throws(MalformedURLException::class) abstract fun createURL(baseUrl: String, report: CrashReportData): URL } }
apache-2.0
9b06c065465374e6d1d03d0f324bdcf2
43.480583
159
0.689587
4.544643
false
true
false
false
icela/FriceEngine
src/org/frice/util/time/FTimer.kt
1
479
package org.frice.util.time /** * @param times if the value is -1, it will loop. * * Created by ice1000 on 2016/8/13. * @author ice1000 * @since v0.1 */ open class FTimer @JvmOverloads constructor(var time: Int, var times: Int = -1) { private var start = FClock.current private val isEnded: Boolean get() = FClock.current - start >= time && times != 0 fun ended(): Boolean = isEnded.apply { if (this) { start = FClock.current if (times > 0) times-- } } }
agpl-3.0
76373e33ec1f119a946278dc9b0c778a
19.826087
54
0.645094
2.920732
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/flv/FlvFlameType.kt
1
246
package com.haishinkit.flv @Suppress("unused") object FlvFlameType { const val KEY: Byte = 0x01 const val INTER: Byte = 0x02 const val DISPOSABLE: Byte = 0x03 const val GENERATED: Byte = 0x04 const val COMMAND: Byte = 0x05 }
bsd-3-clause
800787394a0430f3164796cbca3ee8a6
23.6
37
0.686992
3.28
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/DestructuringInLoop.kt
9
786
// WITH_STDLIB fun part1(input: List<String>): Int { var hp = 0 var d = 0 for (command in input) { val (op, x) = split(command) val xi = x.toInt() when (op) { "a" -> hp += xi "b" -> d += xi "c" -> d -= xi } } return hp * d } fun part2functional(input: List<String>): Int { var horizontalPosition = 0 var depth = 0 input .map { split(it) } .forEach { (direction, amount) -> when (direction) { "forward" -> horizontalPosition += amount.toInt() "up" -> depth -= amount.toInt() "down" -> depth += amount.toInt() } } return horizontalPosition * depth } fun split(x: String) = arrayOf(x, x)
apache-2.0
beb1b76d4f839aecf58c7ca2a7d357c5
23.59375
65
0.464377
3.725118
false
false
false
false
GunoH/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/deprecationInspectionQuickFixes.kt
5
4462
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.deprecation import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtilBase import com.intellij.util.ObjectUtils import com.siyeh.InspectionGadgetsBundle import org.jetbrains.annotations.Nls private fun generateQualifierText(expr: PsiReferenceExpression, replacementMethod: PsiMember): String { val qualifierExpression = expr.qualifierExpression val isReplacementStatic = replacementMethod.hasModifierProperty(PsiModifier.STATIC) return if (qualifierExpression != null && !isReplacementStatic) { qualifierExpression.text + "." } else if (isReplacementStatic) { replacementMethod.containingClass!!.qualifiedName!! + "." } else { "" } } internal class ReplaceMethodCallFix(expr: PsiMethodCallExpression, replacementMethod: PsiMethod) : LocalQuickFixOnPsiElement(expr) { @SafeFieldForPreview private val myReplacementMethodPointer = SmartPointerManager.getInstance(replacementMethod.project).createSmartPsiElementPointer(replacementMethod) private val myReplacementText = PsiFormatUtil.formatMethod(replacementMethod, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME, 0) override fun getText(): String { return InspectionGadgetsBundle.message("replace.method.call.fix.text", myReplacementText) } @Nls override fun getFamilyName(): String { return InspectionGadgetsBundle.message("replace.method.call.fix.family.name") } override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { val expr = ObjectUtils.tryCast(startElement, PsiMethodCallExpression::class.java) ?: return val replacementMethod = myReplacementMethodPointer.element ?: return val qualifierText = generateQualifierText(expr.methodExpression, replacementMethod) val elementFactory = JavaPsiFacade.getElementFactory(project) val newMethodCall = elementFactory.createExpressionFromText(qualifierText + replacementMethod.name + expr.argumentList.text, expr) val replaced = expr.replace(newMethodCall) as PsiMethodCallExpression JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced.methodExpression) } } internal class ReplaceFieldReferenceFix(expr: PsiReferenceExpression, replacementField: PsiField) : LocalQuickFixOnPsiElement(expr) { @SafeFieldForPreview private val myReplacementMethodPointer = SmartPointerManager.getInstance(replacementField.project).createSmartPsiElementPointer(replacementField) private val myReplacementText = PsiFormatUtil.formatVariable(replacementField, PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME, PsiSubstitutor.EMPTY) override fun getFamilyName(): String { return InspectionGadgetsBundle.message("replace.field.reference.fix.family.name") } override fun getText(): String { return InspectionGadgetsBundle.message("replace.field.reference.fix.text", myReplacementText) } override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { val expr = ObjectUtils.tryCast(startElement, PsiReferenceExpression::class.java) ?: return val replacementField = myReplacementMethodPointer.element ?: return val qualifierText = generateQualifierText(expr, replacementField) val replaced = expr.replace(JavaPsiFacade.getElementFactory(project).createExpressionFromText(qualifierText + replacementField.name, expr)) JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced) } }
apache-2.0
37c990a75d424d1d9aae3c453ca3ff14
45.010309
146
0.798521
5.064699
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/assignmentExpression/inExpressionAssignmentsChain.kt
13
472
internal object Test { @JvmStatic fun main(args: Array<String>) { var a = true var b = true var c = true var d = true val e = true if (e.let { d = d and it; d }.also { c = it }.let { b = b or it; b }.also { a = it }); while (b.also { a = it }); do { } while (b.let { a = a xor it; a }) println(c.also { b = it }.let { a = a and it; a }) println(b != c.also { a = it }) } }
apache-2.0
4952319773ae12c8b64c15ab77f0949b
28.5625
94
0.425847
3.189189
false
true
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/receipts/list/DonationReceiptListPageFragment.kt
2
3558
package org.thoughtcrime.securesms.components.settings.app.subscription.receipts.list import android.os.Bundle import android.view.View import androidx.constraintlayout.widget.Group import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.RecyclerView import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.TextPreference import org.thoughtcrime.securesms.database.model.DonationReceiptRecord import org.thoughtcrime.securesms.util.StickyHeaderDecoration import org.thoughtcrime.securesms.util.livedata.LiveDataUtil import org.thoughtcrime.securesms.util.navigation.safeNavigate import org.thoughtcrime.securesms.util.visible class DonationReceiptListPageFragment : Fragment(R.layout.donation_receipt_list_page_fragment) { private val viewModel: DonationReceiptListPageViewModel by viewModels(factoryProducer = { DonationReceiptListPageViewModel.Factory(type, DonationReceiptListPageRepository()) }) private val sharedViewModel: DonationReceiptListViewModel by viewModels( ownerProducer = { requireParentFragment() }, factoryProducer = { DonationReceiptListViewModel.Factory(DonationReceiptListRepository()) } ) private val type: DonationReceiptRecord.Type? get() = requireArguments().getString(ARG_TYPE)?.let { DonationReceiptRecord.Type.fromCode(it) } private lateinit var emptyStateGroup: Group override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val adapter = DonationReceiptListAdapter { model -> findNavController().safeNavigate(DonationReceiptListFragmentDirections.actionDonationReceiptListFragmentToDonationReceiptDetailFragment(model.record.id)) } view.findViewById<RecyclerView>(R.id.recycler).apply { this.adapter = adapter addItemDecoration(StickyHeaderDecoration(adapter, false, true, 0)) } emptyStateGroup = view.findViewById(R.id.empty_state) LiveDataUtil.combineLatest( viewModel.state, sharedViewModel.state ) { state, badges -> state.isLoaded to state.records.map { DonationReceiptListItem.Model(it, getBadgeForRecord(it, badges)) } }.observe(viewLifecycleOwner) { (isLoaded, records) -> if (records.isNotEmpty()) { emptyStateGroup.visible = false adapter.submitList( records + TextPreference( title = null, summary = DSLSettingsText.from( R.string.DonationReceiptListFragment__if_you_have, DSLSettingsText.TextAppearanceModifier(R.style.TextAppearance_Signal_Subtitle) ) ) ) } else { emptyStateGroup.visible = isLoaded } } } private fun getBadgeForRecord(record: DonationReceiptRecord, badges: List<DonationReceiptBadge>): Badge? { return when (record.type) { DonationReceiptRecord.Type.BOOST -> badges.firstOrNull { it.type == DonationReceiptRecord.Type.BOOST }?.badge else -> badges.firstOrNull { it.level == record.subscriptionLevel }?.badge } } companion object { private const val ARG_TYPE = "arg_type" fun create(type: DonationReceiptRecord.Type?): Fragment { return DonationReceiptListPageFragment().apply { arguments = Bundle().apply { putString(ARG_TYPE, type?.code) } } } } }
gpl-3.0
8f34a0759c9ac5edb7435f41865d05ee
37.258065
159
0.745082
4.756684
false
false
false
false
neverwoodsS/MagicPen
app/src/main/java/com/lab/zhangll/magicpen/ArcActivity.kt
1
3249
package com.lab.zhangll.magicpen import android.graphics.Color import android.graphics.Matrix import android.graphics.Paint import android.graphics.PointF import android.os.Bundle import android.os.CountDownTimer import android.support.v7.app.AppCompatActivity import com.lab.zhangll.magicpen.lib.ShapeGravity import com.lab.zhangll.magicpen.lib.arc import com.lab.zhangll.magicpen.lib.magicPen import com.lab.zhangll.magicpen.lib.paint.paint import com.lab.zhangll.magicpen.lib.paint.shader.sweepGradient import com.lab.zhangll.magicpen.lib.shapes.MagicArc class ArcActivity : AppCompatActivity() { lateinit var progress: MagicArc override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView( magicPen { setBackgroundColor(Color.BLACK) arc { shapeGravity = ShapeGravity.END or ShapeGravity.BOTTOM center = PointF(500f, 500f) radius = 400f startAngle = -210f sweepAngle = 240f paint = paint { strokeWidth = 30f style = Paint.Style.STROKE strokeCap = Paint.Cap.ROUND shader = sweepGradient { centerX = 500f centerY = 500f color = arrayOf(Color.parseColor("#11ffffff"), Color.parseColor("#55ffffff"), Color.parseColor("#11ffffff")) percent = arrayOf(0f, 0.33f, 0.66f) matrix = Matrix().apply { setRotate(-220f, 500f, 500f) } } } } progress = arc { center = PointF(500f, 500f) radius = 400f startAngle = -210f sweepAngle = 0f paint = paint { strokeWidth = 30f style = Paint.Style.STROKE strokeCap = Paint.Cap.ROUND shader = sweepGradient { centerX = 500f centerY = 500f color = arrayOf(Color.parseColor("#00ffffff"), Color.parseColor("#D9B262")) percent = arrayOf(0f, 240 / 360f) matrix = Matrix().apply { setRotate(-220f, 500f, 500f) } } } } } ) object: CountDownTimer(5000, 25) { override fun onFinish() { } override fun onTick(millisUntilFinished: Long) { progressing() } }.start() } private fun progressing() = with(progress) { sweepAngle += (240f / 200) invalidate() } }
mit
c7321ebd2ff759a652109f281042a07d
34.326087
140
0.45337
5.572899
false
false
false
false
google/accompanist
permissions-lint/src/main/java/com/google/accompanist/permissions/lint/PermissionsIssueRegistry.kt
1
1400
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.permissions.lint import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.client.api.Vendor import com.android.tools.lint.detector.api.CURRENT_API import com.android.tools.lint.detector.api.Issue @Suppress("UnstableApiUsage") public class PermissionsIssueRegistry : IssueRegistry() { override val issues: List<Issue> = listOf( PermissionsLaunchDetector.PermissionLaunchedDuringComposition ) override val api: Int = 10 override val minApi: Int = CURRENT_API override val vendor: Vendor = Vendor( vendorName = "Accompanist Permissions", identifier = "com.google.accompanist.permissions", feedbackUrl = "https://github.com/google/accompanist/issues/new/choose" ) }
apache-2.0
4efb1c5f4584b89a823d9b0bf0afa91b
34.897436
79
0.746429
4.229607
false
false
false
false
chaojimiaomiao/colorful_wechat
src/main/kotlin/com/rarnu/tophighlight/xposed/HookTabView.kt
1
1054
package com.rarnu.tophighlight.xposed import android.view.View import android.view.ViewGroup import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedHelpers /** * Created by zhaibingjie on 17/2/10. */ object HookTabView { //LauncherUIBottomTabView.java //钩在ohu上 fun hookTabView(classLoader: ClassLoader?, ver: Versions) { XposedHelpers.findAndHookMethod(ver.bottomTabView, classLoader, ver.bottomMethod, Integer.TYPE, ViewGroup::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(param: XC_MethodHook.MethodHookParam?) { var aVar = param?.result var ohU = XposedHelpers.getObjectField(aVar, ver.bottomField) as View ohU.setBackgroundColor(XpConfig.bottomBarColor) /*var backBitmap = BitmapFactory.decodeFile(XpConfig.bottomBarPath) val drawable = BitmapDrawable(backBitmap) ohU.background = drawable*/ } }) } }
gpl-3.0
4dadea1e858e9110550a0f758f57ae84
36.464286
153
0.676527
4.225806
false
true
false
false
cdietze/klay
src/main/kotlin/klay/core/Log.kt
1
2316
package klay.core /** * Simple logging interface. */ abstract class Log { private var collector: Collector? = null private var minLevel = Level.DEBUG /** Tags a log message with a level. */ enum class Level { DEBUG, INFO, WARN, ERROR } /** Allows for collection of log messages (in addition to standard logging). * See [.setCollector]. */ interface Collector { /** * Called when a message is logged. * @param level the level at which the message was logged. * * * @param msg the message that was logged. * * * @param e the exception logged with the message, or null. */ fun logged(level: Level, msg: String, e: Throwable?) } /** * Configures a log message collector. This allows games to intercept (and record and submit with * bug reports, for example) all messages logged via the Klay logging system. This will include * errors logged internally by Klay code. */ fun setCollector(collector: Collector) { this.collector = collector } /** * Configures the minimum log level that will be logged. Messages at a level lower than * `level` will be suppressed. Note that all messages are still passed to any registered * [Collector], but suppressed messages are not sent to the platform logging system. */ fun setMinLevel(level: Level) { minLevel = level } /** Logs `msg` and `e` at the debug level. */ fun debug(msg: String, e: Throwable? = null) { log(Level.DEBUG, msg, e) } /** Logs `msg` and `e` at the info level. */ fun info(msg: String, e: Throwable? = null) { log(Level.INFO, msg, e) } /** Logs `msg` and `e` at the warn level. */ fun warn(msg: String, e: Throwable? = null) { log(Level.WARN, msg, e) } /** Logs `msg` and `e` at the error level. */ fun error(msg: String, e: Throwable? = null) { log(Level.ERROR, msg, e) } protected fun log(level: Level, msg: String, e: Throwable?) { if (collector != null) collector!!.logged(level, msg, e) if (level.ordinal >= minLevel.ordinal) logImpl(level, msg, e) } protected abstract fun logImpl(level: Level, msg: String, e: Throwable?) }
apache-2.0
0706a6019d16d8f93aac4c37f6aabdc9
29.893333
101
0.604491
4.013865
false
false
false
false
martijn-heil/wac-core
src/main/kotlin/tk/martijn_heil/wac_core/craft/util/BlockPos.kt
1
1114
/* * wac-core * Copyright (C) 2016 Martijn Heil * * 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 tk.martijn_heil.wac_core.craft.util data class BlockPos(var x: Int, var y: Int, var z: Int) { override fun equals(other: Any?) = other is BlockPos && other.x == x && other.y == y && other.z == z override fun hashCode(): Int { var result = x result = 31 * result + y result = 31 * result + z return result } }
gpl-3.0
323489ab5c329ccca1d95c4f53b63089
36.166667
104
0.652603
3.922535
false
false
false
false
dahlstrom-g/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt
1
20936
// 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.intellij.build.impl import com.intellij.diagnostic.telemetry.createTask import com.intellij.diagnostic.telemetry.use import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.SystemProperties import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.trace.Span import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData import org.jetbrains.intellij.build.impl.productInfo.checkInArchive import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.copyFile import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders import org.jetbrains.intellij.build.io.writeNewFile import org.jetbrains.intellij.build.tasks.NoDuplicateZipArchiveOutputStream import org.jetbrains.intellij.build.tasks.dir import org.jetbrains.intellij.build.tasks.entry import org.jetbrains.intellij.build.tasks.executableFileUnixMode import java.io.File import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFilePermission import java.time.LocalDate import java.util.concurrent.ForkJoinTask import java.util.function.BiConsumer import java.util.zip.Deflater class MacDistributionBuilder(private val context: BuildContext, private val customizer: MacDistributionCustomizer, private val ideaProperties: Path?) : OsSpecificDistributionBuilder { private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns" override val targetOs: OsFamily get() = OsFamily.MACOS private fun getDocTypes(): String { val associations = mutableListOf<String>() if (customizer.associateIpr) { val association = """<dict> <key>CFBundleTypeExtensions</key> <array> <string>ipr</string> </array> <key>CFBundleTypeIconFile</key> <string>${targetIcnsFileName}</string> <key>CFBundleTypeName</key> <string>${context.applicationInfo.productName} Project File</string> <key>CFBundleTypeRole</key> <string>Editor</string> </dict>""" associations.add(association) } for (fileAssociation in customizer.fileAssociations) { val iconPath = fileAssociation.iconPath val association = """<dict> <key>CFBundleTypeExtensions</key> <array> <string>${fileAssociation.extension}</string> </array> <key>CFBundleTypeIconFile</key> <string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string> <key>CFBundleTypeRole</key> <string>Editor</string> </dict>""" associations.add(association) } return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes } override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) { doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true) } private fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture?, copyDistFiles: Boolean) { @Suppress("SpellCheckingInspection") val platformProperties = mutableListOf( "\n#---------------------------------------------------------------------", "# macOS-specific system properties", "#---------------------------------------------------------------------", "com.apple.mrj.application.live-resize=false", "apple.laf.useScreenMenuBar=true", "jbScreenMenuBar.enabled=true", "apple.awt.fileDialogForDirectories=true", "apple.awt.graphics.UseQuartz=true", "apple.awt.fullscreencapturealldisplays=false" ) customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") }) layoutMacApp(ideaProperties!!, platformProperties, getDocTypes(), macDistDir, context) unpackPty4jNative(context, macDistDir, "darwin") generateBuildTxt(context, macDistDir.resolve("Resources")) if (copyDistFiles) { copyDistFiles(context, macDistDir) } customizer.copyAdditionalFiles(context, macDistDir.toString()) if (arch != null) { customizer.copyAdditionalFiles(context, macDistDir, arch) } generateUnixScripts(context, emptyList(), macDistDir.resolve("bin"), OsFamily.MACOS) } override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) { doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false) context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) { val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber) val publishArchive = !SystemInfoRt.isMac && context.proprietaryBuildTools.macHostProperties?.host == null val binariesToSign = customizer.getBinariesToSign(context, arch) if (!binariesToSign.isEmpty()) { context.executeStep(spanBuilder("sign binaries for macOS distribution") .setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) { context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), mapOf( "mac_codesign_options" to "runtime", "mac_codesign_force" to "true", "mac_codesign_deep" to "true", )) } } val macZip = (if (publishArchive || customizer.publishArchive) context.paths.artifactDir else context.paths.tempDir) .resolve("$baseName.mac.${arch.name}.zip") val zipRoot = getMacZipRoot(customizer, context) buildMacZip( targetFile = macZip, zipRoot = zipRoot, productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = null), allDist = context.paths.distAllDir, macDist = osAndArchSpecificDistPath, extraFiles = context.getDistFiles(), executableFilePatterns = getExecutableFilePatterns(customizer), compressionLevel = if (publishArchive) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED, errorsConsumer = context.messages::warning ) checkInArchive(archiveFile = macZip, pathInArchive = "$zipRoot/Resources", context = context) if (publishArchive) { Span.current().addEvent("skip DMG artifact producing because a macOS build agent isn't configured") context.notifyArtifactBuilt(macZip) } else { buildAndSignDmgFromZip(macZip, arch, context.builtinModule).invoke() } } } fun buildAndSignDmgFromZip(macZip: Path, arch: JvmArchitecture, builtinModule: BuiltinModulesFileData?): ForkJoinTask<*> { return createBuildForArchTask(builtinModule, arch, macZip, customizer, context) } private fun layoutMacApp(ideaPropertiesFile: Path, platformProperties: List<String>, docTypes: String?, macDistDir: Path, context: BuildContext) { val macCustomizer = customizer copyDirWithFileFilter(context.paths.communityHomeDir.communityRoot.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter) copyDir(context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir) val executable = context.productProperties.baseFileName Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable")) //noinspection SpellCheckingInspection val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath) val resourcesDistDir = macDistDir.resolve("Resources") copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName)) for (fileAssociation in customizer.fileAssociations) { if (!fileAssociation.iconPath.isEmpty()) { val source = Path.of(fileAssociation.iconPath) val dest = resourcesDistDir.resolve(source.fileName) Files.deleteIfExists(dest) copyFile(source, dest) } } val fullName = context.applicationInfo.productName //todo[nik] improve val minor = context.applicationInfo.minorVersion val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta") val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}" val isEap = if (isNotRelease) "-EAP" else "" val properties = Files.readAllLines(ideaPropertiesFile) properties.addAll(platformProperties) Files.write(macDistDir.resolve("bin/idea.properties"), properties) val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" } val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" } val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList() val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS).toMutableList() if (!bootClassPath.isEmpty()) { //noinspection SpellCheckingInspection additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath") } val predicate: (String) -> Boolean = { it.startsWith("-D") } val launcherProperties = additionalJvmArgs.filter(predicate) val launcherVmOptions = additionalJvmArgs.filterNot(predicate) fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log") fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof") VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n") val urlSchemes = macCustomizer.urlSchemes val urlSchemesString = if (urlSchemes.isEmpty()) { "" } else { """ <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>Stacktrace</string> <key>CFBundleURLSchemes</key> <array> ${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }} </array> </dict> </array> """ } val todayYear = LocalDate.now().year.toString() //noinspection SpellCheckingInspection substituteTemplatePlaceholders( inputFile = macDistDir.resolve("Info.plist"), outputFile = macDistDir.resolve("Info.plist"), placeholder = "@@", values = listOf( Pair("build", context.fullBuildNumber), Pair("doc_types", docTypes ?: ""), Pair("executable", executable), Pair("icns", targetIcnsFileName), Pair("bundle_name", fullName), Pair("product_state", isEap), Pair("bundle_identifier", macCustomizer.bundleIdentifier), Pair("year", todayYear), Pair("version", version), Pair("vm_options", optionsToXml(launcherVmOptions)), Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))), Pair("class_path", classPath), Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')), Pair("url_schemes", urlSchemesString), Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" + macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } + " </array>"), Pair("min_osx", macCustomizer.minOSXVersion), ) ) val distBinDir = macDistDir.resolve("bin") Files.createDirectories(distBinDir) val sourceScriptDir = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/scripts") Files.newDirectoryStream(sourceScriptDir).use { stream -> val inspectCommandName = context.productProperties.inspectCommandName for (file in stream) { if (file.toString().endsWith(".sh")) { var fileName = file.fileName.toString() if (fileName == "inspect.sh" && inspectCommandName != "inspect") { fileName = "${inspectCommandName}.sh" } val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "") try { // Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts // https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri Files.writeString(sourceFileLf, Files.readString(file).replace("\r", "")) val target = distBinDir.resolve(fileName) substituteTemplatePlaceholders( sourceFileLf, target, "@@", listOf( Pair("product_full", fullName), Pair("script_name", executable), Pair("inspectCommandName", inspectCommandName), ), false, ) } finally { Files.delete(sourceFileLf) } } } } } override fun generateExecutableFilesPatterns(includeJre: Boolean): List<String> = getExecutableFilePatterns(customizer) } private fun createBuildForArchTask(builtinModule: BuiltinModulesFileData?, arch: JvmArchitecture, macZip: Path, customizer: MacDistributionCustomizer, context: BuildContext): ForkJoinTask<*> { return createTask(spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name)) { val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true) ForkJoinTask.invokeAll(buildForArch(builtinModule, arch, context.bundledRuntime, macZip, notarize, customizer, context)) Files.deleteIfExists(macZip) } } private fun buildForArch(builtinModule: BuiltinModulesFileData?, arch: JvmArchitecture, jreManager: BundledRuntime, macZip: Path, notarize: Boolean, customizer: MacDistributionCustomizer, context: BuildContext): List<ForkJoinTask<*>> { val tasks = mutableListOf<ForkJoinTask<*>?>() val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}" val archStr = arch.name // with JRE if (context.options.buildDmgWithBundledJre) { tasks.add(createSkippableTask( spanBuilder("build DMG with JRE").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr", context ) { val jreArchive = jreManager.findArchive(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch) signAndBuildDmg(builtinModule = builtinModule, context = context, customizer = customizer, macHostProperties = context.proprietaryBuildTools.macHostProperties, macZip = macZip, jreArchivePath = jreArchive, suffix = suffix, notarize = notarize) }) } // without JRE if (context.options.buildDmgWithoutBundledJre) { tasks.add(createSkippableTask( spanBuilder("build DMG without JRE").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr", context ) { signAndBuildDmg(builtinModule = builtinModule, context = context, customizer = customizer, macHostProperties = context.proprietaryBuildTools.macHostProperties, macZip = macZip, jreArchivePath = null, suffix = "-no-jdk$suffix", notarize = notarize) }) } return tasks.filterNotNull() } private fun optionsToXml(options: List<String>): String { val buff = StringBuilder() for (it in options) { buff.append(" <string>").append(it).append("</string>\n") } return buff.toString().trim() } private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String { val buff = StringBuilder() for (it in properties) { val p = it.indexOf('=') buff.append(" <key>").append(it.substring(2, p)).append("</key>\n") buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n") } moreProperties.forEach { (key, value) -> buff.append(" <key>").append(key).append("</key>\n") buff.append(" <string>").append(value).append("</string>\n") } return buff.toString().trim() } private fun getExecutableFilePatterns(customizer: MacDistributionCustomizer): List<String> = listOf( "bin/*.sh", "bin/*.py", "bin/fsnotifier", "bin/printenv", "bin/restarter", "bin/repair", "MacOS/*" ) + customizer.extraExecutables internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String = "${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents" internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?, context: BuildContext, javaExecutablePath: String?): String { val executable = context.productProperties.baseFileName return generateMultiPlatformProductJson( relativePathToBin = "../bin", builtinModules = builtinModule, launch = listOf( ProductInfoLaunchData( os = OsFamily.MACOS.osName, launcherPath = "../MacOS/${executable}", javaExecutablePath = javaExecutablePath, vmOptionsFilePath = "../bin/${executable}.vmoptions", startupWmClass = null, ) ), context = context ) } private fun buildMacZip(targetFile: Path, zipRoot: String, productJson: String, allDist: Path, macDist: Path, extraFiles: Collection<Map.Entry<Path, String>>, executableFilePatterns: List<String>, compressionLevel: Int, errorsConsumer: (String) -> Unit) { spanBuilder("build zip archive for macOS") .setAttribute("file", targetFile.toString()) .setAttribute("zipRoot", zipRoot) .setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns) .use { val fs = targetFile.fileSystem val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") } val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, relativePath -> when { patterns.any { it.matches(Path.of(relativePath)) } -> entry.unixMode = executableFileUnixMode SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions (file) -> { errorsConsumer("Executable permissions of $relativePath won't be set in $targetFile. " + "Please make sure that executable file patterns are updated.") } } } writeNewFile(targetFile) { targetFileChannel -> NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream -> zipOutStream.setLevel(compressionLevel) zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray()) val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath -> if (relativePath.endsWith(".txt") && !relativePath.contains('/')) { zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile) false } else { true } } zipOutStream.dir(allDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer) zipOutStream.dir(macDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer) for ((file, relativePath) in extraFiles) { zipOutStream.entry("$zipRoot/${FileUtilRt.toSystemIndependentName(relativePath)}${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file) } } } } }
apache-2.0
2e02e8b686f00bfca966ca7180388643
43.355932
158
0.661206
4.941232
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/drawable/PollPlotDrawable.kt
1
1180
package jp.juggler.subwaytooter.drawable import android.graphics.* import android.graphics.drawable.Drawable class PollPlotDrawable( private val color: Int, private val startWidth: Int, // pixel width for minimum gauge private val ratio: Float, // gauge ratio in 0..1 private val isRtl: Boolean = false, // false for LTR, true for RTL layout ) : Drawable() { override fun setAlpha(alpha: Int) { } override fun getOpacity(): Int = PixelFormat.TRANSLUCENT override fun setColorFilter(colorFilter: ColorFilter?) { } private val rect = Rect() private val paint = Paint() override fun draw(canvas: Canvas) { val bounds = bounds val w = bounds.width() val ratioWidth = ((w - startWidth) * ratio + 0.5f).toInt() val remainWidth = w - ratioWidth - startWidth if (isRtl) { rect.set(bounds.left + remainWidth, bounds.top, bounds.right, bounds.bottom) } else { rect.set(bounds.left, bounds.top, bounds.right - remainWidth, bounds.bottom) } paint.color = color canvas.drawRect(rect, paint) } }
apache-2.0
d1cf6a98addc81ec1f1092303c8833a7
27.5
88
0.621186
4.338235
false
false
false
false
paplorinc/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewCommitPanel.kt
4
1992
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.ui.IdeBorderFactory.createBorder import com.intellij.ui.JBColor import com.intellij.ui.SideBorder import com.intellij.util.ui.JBUI.Borders.emptyLeft import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.UIUtil.addBorder import com.intellij.util.ui.UIUtil.getTreeBackground import com.intellij.util.ui.components.BorderLayoutPanel import javax.swing.JButton class ChangesViewCommitPanel(val project: Project) : BorderLayoutPanel(), DataProvider { val actions = ActionManager.getInstance().getAction("ChangesView.CommitToolbar") as ActionGroup val toolbar = ActionManager.getInstance().createActionToolbar("ChangesView.CommitToolbar", actions, false).apply { setTargetComponent(this@ChangesViewCommitPanel) addBorder(component, createBorder(JBColor.border(), SideBorder.RIGHT)) } val commitMessage = CommitMessage(project, false, false, true).apply { editorField.addSettingsProvider { it.setBorder(emptyLeft(3)) } editorField.setPlaceholder("Commit Message") } init { val commitButton = object : JButton("Commit") { override fun isDefaultButton() = true } val buttonPanel = simplePanel() .addToLeft(commitButton) .withBackground(getTreeBackground()) val centerPanel = simplePanel(commitMessage).addToBottom(buttonPanel) addToCenter(centerPanel).addToLeft(toolbar.component).withBorder(createBorder(JBColor.border(), SideBorder.TOP)) withPreferredHeight(85) } override fun getData(dataId: String) = commitMessage.getData(dataId) }
apache-2.0
e1461444ef517a9ab83dcd85d7c163b0
44.295455
140
0.795683
4.446429
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddMemberToSupertypeFix.kt
1
13010
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.IconManager import com.intellij.util.PlatformIcons import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.AddMemberToSupertypeFix.MemberData import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.modalityModifier import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.Icon abstract class AddMemberToSupertypeFix(element: KtCallableDeclaration, private val candidateMembers: List<MemberData>) : KotlinQuickFixAction<KtCallableDeclaration>(element), LowPriorityAction { class MemberData(val signaturePreview: String, val sourceCode: String, val targetClass: KtClass) init { assert(candidateMembers.isNotEmpty()) } abstract val kind: String abstract val icon: Icon override fun getText(): String = candidateMembers.singleOrNull()?.let { actionName(it) } ?: KotlinBundle.message("fix.add.member.supertype.text", kind) override fun getFamilyName() = KotlinBundle.message("fix.add.member.supertype.family", kind) override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor?, file: KtFile) { CommandProcessor.getInstance().runUndoTransparentAction { if (candidateMembers.size == 1 || editor == null || !editor.component.isShowing) { addMember(candidateMembers.first(), project) } else { JBPopupFactory.getInstance().createListPopup(createMemberPopup(project)).showInBestPositionFor(editor) } } } private fun addMember(memberData: MemberData, project: Project) { project.executeWriteCommand(KotlinBundle.message("fix.add.member.supertype.progress", kind)) { element?.removeDefaultParameterValues() val classBody = memberData.targetClass.getOrCreateBody() val memberElement: KtCallableDeclaration = KtPsiFactory(project).createDeclaration(memberData.sourceCode) memberElement.copyAnnotationEntriesFrom(element) val insertedMemberElement = classBody.addBefore(memberElement, classBody.rBrace) as KtCallableDeclaration ShortenReferences.DEFAULT.process(insertedMemberElement) val modifierToken = insertedMemberElement.modalityModifier()?.node?.elementType as? KtModifierKeywordToken ?: return@executeWriteCommand if (insertedMemberElement.implicitModality() == modifierToken) { RemoveModifierFixBase(insertedMemberElement, modifierToken, true).invoke() } } } private fun KtCallableDeclaration.removeDefaultParameterValues() { valueParameters.forEach { it.defaultValue?.delete() it.equalsToken?.delete() } } private fun KtCallableDeclaration.copyAnnotationEntriesFrom(member: KtCallableDeclaration?) { member?.annotationEntries?.reversed()?.forEach { addAnnotationEntry(it) } } private fun createMemberPopup(project: Project): ListPopupStep<*> { return object : BaseListPopupStep<MemberData>(KotlinBundle.message("fix.add.member.supertype.choose.type"), candidateMembers) { override fun isAutoSelectionEnabled() = false override fun onChosen(selectedValue: MemberData, finalChoice: Boolean): PopupStep<*>? { if (finalChoice) { addMember(selectedValue, project) } return PopupStep.FINAL_CHOICE } override fun getIconFor(value: MemberData) = icon override fun getTextFor(value: MemberData) = actionName(value) } } @Nls private fun actionName(memberData: MemberData): String = KotlinBundle.message( "fix.add.member.supertype.add.to", memberData.signaturePreview, memberData.targetClass.name.toString() ) } abstract class AddMemberToSupertypeFactory : KotlinSingleIntentionActionFactory() { protected fun getCandidateMembers(memberElement: KtCallableDeclaration): List<MemberData> { val descriptors = generateCandidateMembers(memberElement) return descriptors.mapNotNull { createMemberData(it, memberElement) } } abstract fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? private fun generateCandidateMembers(memberElement: KtCallableDeclaration): List<CallableMemberDescriptor> { val memberDescriptor = memberElement.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableMemberDescriptor ?: return emptyList() val containingClass = memberDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList() // TODO: filter out impossible supertypes (for example when argument's type isn't visible in a superclass). return getSuperClasses(containingClass) .asSequence() .filterNot { KotlinBuiltIns.isAnyOrNullableAny(it.defaultType) } .map { generateMemberSignatureForType(memberDescriptor, it) } .toList() } private fun getSuperClasses(classDescriptor: ClassDescriptor): List<ClassDescriptor> { val supertypes = classDescriptor.defaultType.supertypes().toMutableList().sortSubtypesFirst() return supertypes.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor } } private fun MutableList<KotlinType>.sortSubtypesFirst(): List<KotlinType> { val typeChecker = KotlinTypeChecker.DEFAULT for (i in 1 until size) { val currentType = this[i] for (j in 0 until i) { if (typeChecker.isSubtypeOf(currentType, this[j])) { this.removeAt(i) this.add(j, currentType) break } } } return this } private fun generateMemberSignatureForType( memberDescriptor: CallableMemberDescriptor, typeDescriptor: ClassDescriptor ): CallableMemberDescriptor { // TODO: support for generics. val modality = if (typeDescriptor.kind == ClassKind.INTERFACE || typeDescriptor.modality == Modality.SEALED) { Modality.ABSTRACT } else { typeDescriptor.modality } return memberDescriptor.copy( typeDescriptor, modality, memberDescriptor.visibility, CallableMemberDescriptor.Kind.DECLARATION, /* copyOverrides = */ false ) } } class AddFunctionToSupertypeFix private constructor(element: KtNamedFunction, functions: List<MemberData>) : AddMemberToSupertypeFix(element, functions) { override val kind: String = "function" override val icon: Icon = IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Function) companion object : AddMemberToSupertypeFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val functionElement = diagnostic.psiElement as? KtNamedFunction ?: return null val candidateFunctions = getCandidateMembers(functionElement) return if (candidateFunctions.isNotEmpty()) AddFunctionToSupertypeFix(functionElement, candidateFunctions) else null } override fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? { val classDescriptor = memberDescriptor.containingDeclaration as ClassDescriptor val project = memberElement.project var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.withNoAnnotations().withDefaultValueOption(project).render(memberDescriptor) if (classDescriptor.kind != ClassKind.INTERFACE && memberDescriptor.modality != Modality.ABSTRACT) { val returnType = memberDescriptor.returnType sourceCode += if (returnType == null || !KotlinBuiltIns.isUnit(returnType)) { val bodyText = getFunctionBodyTextFromTemplate( project, TemplateKind.FUNCTION, memberDescriptor.name.asString(), memberDescriptor.returnType?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } ?: "Unit", classDescriptor.importableFqName ) "{\n$bodyText\n}" } else { "{}" } } val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor) as? KtClass ?: return null return MemberData( IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withDefaultValueOption(project).render(memberDescriptor), sourceCode, targetClass ) } } } class AddPropertyToSupertypeFix private constructor(element: KtProperty, properties: List<MemberData>) : AddMemberToSupertypeFix(element, properties) { override val kind: String = "property" override val icon: Icon = PlatformIcons.PROPERTY_ICON companion object : AddMemberToSupertypeFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val propertyElement = diagnostic.psiElement as? KtProperty ?: return null val candidateProperties = getCandidateMembers(propertyElement) return if (candidateProperties.isNotEmpty()) AddPropertyToSupertypeFix(propertyElement, candidateProperties) else null } override fun createMemberData(memberDescriptor: CallableMemberDescriptor, memberElement: KtCallableDeclaration): MemberData? { val classDescriptor = memberDescriptor.containingDeclaration as ClassDescriptor val signaturePreview = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(memberDescriptor) var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.withNoAnnotations().render(memberDescriptor) val initializer = memberElement.safeAs<KtProperty>()?.initializer if (classDescriptor.kind == ClassKind.CLASS && classDescriptor.modality == Modality.OPEN && initializer != null) { sourceCode += " = ${initializer.text}" } val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(memberElement.project, classDescriptor) as? KtClass ?: return null return MemberData(signaturePreview, sourceCode, targetClass) } } } private fun DescriptorRenderer.withNoAnnotations(): DescriptorRenderer { return withOptions { modifiers -= DescriptorRendererModifier.ANNOTATIONS } } private fun DescriptorRenderer.withDefaultValueOption(project: Project): DescriptorRenderer { return withOptions { this.defaultParameterValueRenderer = { OptionalParametersHelper.defaultParameterValueExpression(it, project)?.text ?: error("value parameter renderer shouldn't be called when there is no value to render") } } }
apache-2.0
0e1e40c6c03cccb602b929ccea6390b3
47.36803
141
0.71422
5.519728
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/MiniMenuOption.kt
1
10168
package org.runestar.client.api.game import org.runestar.client.api.game.MiniMenuOpcode.* import org.runestar.client.api.game.live.Components import org.runestar.client.raw.CLIENT import java.awt.Point interface MiniMenuOption { val opcode: Int val argument0: Int val argument1: Int val argument2: Int val targetName: String val action: String val shiftClick: Boolean private data class Base( override val opcode: Int, override val argument0: Int, override val argument1: Int, override val argument2: Int, override val targetName: String, override val action: String, override val shiftClick: Boolean ) : MiniMenuOption companion object { fun of(opcode: Int, argument0: Int, argument1: Int, argument2: Int, targetName: String, action: String, shiftClick: Boolean): MiniMenuOption { val base = MiniMenuOption.Base(opcode, argument0, argument1, argument2, targetName, action, shiftClick) return when(opcode) { // todo: subclasses OP_LOC1, OP_LOC2, OP_LOC3, OP_LOC4, OP_LOC5 -> MiniMenuOption.OnObjectIndexed(base) CANCEL -> MiniMenuOption.Cancel(base) WALK -> MiniMenuOption.WalkHere(base) OP_NPC1, OP_NPC2, OP_NPC3, OP_NPC4, OP_NPC5 -> MiniMenuOption.OnNpcIndexed(base) OP_PLAYER1, OP_PLAYER2, OP_PLAYER3, OP_PLAYER4, OP_PLAYER5, OP_PLAYER6, OP_PLAYER7, OP_PLAYER8 -> MiniMenuOption.OnPlayerIndexed(base) OP_PLAYER1_LOWPRIORITY, OP_PLAYER2_LOWPRIORITY, OP_PLAYER3_LOWPRIORITY, OP_PLAYER4_LOWPRIORITY, OP_PLAYER5_LOWPRIORITY, OP_PLAYER6_LOWPRIORITY, OP_PLAYER7_LOWPRIORITY, OP_PLAYER8_LOWPRIORITY -> MiniMenuOption.OnPlayerIndexedLowPriority(base) OP_NPCT, OP_NPCU, OP_NPC6 -> MiniMenuOption.OnNpcSimple(base) OP_PLAYERT, OP_PLAYERU -> MiniMenuOption.OnPlayerSimple(base) OP_LOCT, OP_LOC6, OP_LOCU -> MiniMenuOption.OnObjectSimple(base) OP_OBJ1, OP_OBJ2, OP_OBJ3, OP_OBJ4, OP_OBJ5 -> MiniMenuOption.OnGroundItemIndexed(base) OP_OBJU, OP_OBJ6, OP_OBJT -> MiniMenuOption.OnGroundItemSimple(base) OP_HELD1, OP_HELD2, OP_HELD3, OP_HELD4, OP_HELD5 -> MiniMenuOption.OnItemIndexed(base) IF1_BUTTON6, OP_HELDT, OP_HELDU, TGT_HELD -> MiniMenuOption.OnItemSimple(base) IF_BUTTONX1, IF_BUTTONX2, TGT_BUTTON -> MiniMenuOption.OnComponentSimple(base) PAUSE_BUTTON -> MiniMenuOption.ButtonDialog(base) else -> base } } } interface AtLocation : MiniMenuOption { val plane: Int val location: SceneTile get() = SceneTile(argument1, argument2, plane) } interface Indexed : MiniMenuOption { val index: Int } interface OnScreen : MiniMenuOption { val screenLocation get() = Point(argument1, argument2) } interface OnObject: MiniMenuOption { val id: Int get() = argument0 } interface OnGroundItem: MiniMenuOption { val id get() = argument0 } interface OnItem: MiniMenuOption, InComponent { val id get() = argument0 val slot get() = argument1 } interface InComponent: MiniMenuOption { val componentId get() = ComponentId(argument2) val component: Component get() = checkNotNull(Components[componentId]) } interface OnComponent: MiniMenuOption, InComponent { val componentChildId: Int? get() = argument1.let { if (it == -1) null else it } val componentChild: Component? get() = component.let { p -> componentChildId?.let { c -> p.dynamicChildren[c] } ?: p } } data class OnComponentSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnComponent { override fun toString(): String { return "OnComponentSimple(opcode=$opcode, componentId=$componentId, componentChildId=$componentChildId, targetName=$targetName, action=$action)" } } data class ButtonDialog internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, InComponent, Indexed { override val index get() = argument1 override fun toString(): String { return "ButtonDialog(opcode=$opcode, index=$index, componentId=$componentId, targetName=$targetName, action=$action)" } } data class OnItemIndexed internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, Indexed, OnItem { override val index get() = opcode - OP_HELD1 override fun toString(): String { return "OnItemIndexed(opcode=$opcode, index=$index, id=$id, slot=$slot, componentId=$componentId, targetName=$targetName, action=$action)" } } data class OnItemSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnItem { override fun toString(): String { return "OnItemSimple(opcode=$opcode, id=$id, slot=$slot, componentId=$componentId, targetName=$targetName, action=$action)" } } data class OnGroundItemIndexed internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, Indexed, OnGroundItem, AtLocation { override val plane: Int = CLIENT.plane override val index: Int get() = opcode - OP_OBJ1 override fun toString(): String { return "OnGroundItemIndexed(opcode=$opcode, index=$index, id=$id, location=$location, targetName=$targetName, action=$action)" } } data class OnGroundItemSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnGroundItem, AtLocation { override val plane: Int = CLIENT.plane override fun toString(): String { return "OnGroundItemSimple(opcode=$opcode, id=$id, location=$location, targetName=$targetName, action=$action)" } } data class Cancel internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption { override fun toString(): String { return "Cancel(opcode=$opcode, action=$action)" } } data class WalkHere internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnScreen { override fun toString(): String { return "WalkHere(opcode=$opcode, screenLocation=$screenLocation, action=$action)" } } data class OnObjectIndexed internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, AtLocation, Indexed, OnObject { override val plane: Int = CLIENT.plane override val index: Int get() = opcode - OP_LOC1 override fun toString(): String { return "OnObjectIndexed(opcode=$opcode, index=$index, id=$id, targetName=$targetName, action=$action)" } } interface OnNpc : MiniMenuOption, ActorTargeting { override val playerTargetIndex: Int get() = -1 override val npcTargetIndex: Int get() = argument0 override val target: Npc? get() = super.target as Npc? } interface OnPlayer : MiniMenuOption, ActorTargeting { override val playerTargetIndex: Int get() = argument0 override val npcTargetIndex: Int get() = -1 override val target: Player? get() = super.target as Player? } data class OnNpcIndexed internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, Indexed, OnNpc { override val index: Int get() = opcode - OP_NPC1 override fun toString(): String { return "OnNpcIndexed(opcode=$opcode, index=$index, npcTargetIndex=$npcTargetIndex, targetName=$targetName, action=$action)" } } data class OnPlayerIndexed internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, Indexed, OnPlayer { override val index: Int get() = opcode - OP_PLAYER1 override fun toString(): String { return "OnPlayerIndexed(opcode=$opcode, index=$index, playerTargetIndex=$playerTargetIndex, targetName=$targetName, action=$action)" } } data class OnPlayerIndexedLowPriority internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, Indexed, OnPlayer { override val index: Int get() = opcode - OP_PLAYER1_LOWPRIORITY override fun toString(): String { return "OnPlayerIndexedLowPriority(opcode=$opcode, index=$index, playerTargetIndex=$playerTargetIndex, targetName=$targetName, action=$action)" } } data class OnNpcSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnNpc { override fun toString(): String { return "OnNpcSimple(opcode=$opcode, npcTargetIndex=$npcTargetIndex, targetName=$targetName, action=$action)" } } data class OnPlayerSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnPlayer { override fun toString(): String { return "OnPlayerSimple(opcode=$opcode, playerTargetIndex=$playerTargetIndex, targetName=$targetName, action=$action)" } } data class OnObjectSimple internal constructor(private val menuOption: MiniMenuOption) : MiniMenuOption by menuOption, OnObject, AtLocation { override val plane: Int = CLIENT.plane override fun toString(): String { return "OnObjectSimple(opcode=$opcode, id=$id, location=$location, targetName=$targetName, action=$action)" } } }
mit
078c22c544a5ba7d19c501a1039a04a7
37.369811
163
0.651652
4.535236
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/to/TObjectTest.kt
2
4437
/* * 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 org.apache.causeway.client.kroviz.to import org.apache.causeway.client.kroviz.handler.TObjectHandler import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.ACTIONS_STRINGS_INVOKE import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.ACTIONS_TEXT_INVOKE import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.CAUSEWAY_SECURITY_ME_SERVICE import org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0.SO_0 import org.apache.causeway.client.kroviz.utils.StringUtils import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class TObjectTest { @Test fun testCausewaySecurityMe() { //given val jsonStr = CAUSEWAY_SECURITY_ME_SERVICE.str // when val tObject = TObjectHandler().parse(jsonStr) as TObject val members = tObject.members // then assertEquals(27, members.size) } @Test fun testPropertiesChanged() { //given val jsonStr = SO_0.str // when val tObject = TObjectHandler().parse(jsonStr) as TObject val properties = tObject.getProperties() // then val mutable = properties.filter { it.isReadWrite() } assertEquals(1, mutable.size) //when mutable.first().value!!.content = "l on the hill" //then val putBody = StringUtils.propertiesAsBody(tObject) assertTrue(putBody.contains("notes")) assertTrue(putBody.contains("value")) assertTrue(putBody.contains("l on the hill")) } @Test fun testLinksMembersProperties() { //given val jsonStr = SO_0.str // when val to = TObjectHandler().parse(jsonStr) as TObject val members = to.members val properties = to.getProperties() // then assertNotNull(to.links) assertEquals("Object: Foo", to.links[0].title) assertEquals(10, members.size) assertEquals(4, properties.size) val namedMembers = properties.filter { it.id == "name" } assertEquals(1, namedMembers.size) val nameMember = namedMembers.first() val content = nameMember.value!!.content as String assertEquals("Foo", content) } @Test fun testTextDemo() { //given val jsonStr = ACTIONS_TEXT_INVOKE.str // when val to = TObjectHandler().parse(jsonStr) as TObject val members = to.members val properties = to.getProperties() // then assertNotNull(to.links) assertEquals("TextDemo", to.links[0].title) assertEquals(6, members.size) assertEquals(5, properties.size) val filteredProperties = properties.filter { it.id == "description" } assertEquals(1, filteredProperties.size) val description = filteredProperties.first() val content = description.value!!.content as String assertTrue(content.startsWith("<div") && content.endsWith("div>")) } @Test fun testActionsStringsInvoke() { //given val jsonStr = ACTIONS_STRINGS_INVOKE.str // when val to = TObjectHandler().parse(jsonStr) as TObject // then assertEquals("String data type", to.links[0].title) assertEquals(9, to.members.size) assertEquals(1, to.getCollections().size) assertEquals(8, to.getActions().size) assertEquals(0, to.getProperties().size) val filteredProperties = to.getProperties().filter { it.id == "description" } assertEquals(0, filteredProperties.size) } }
apache-2.0
6d132ce00c39e1f63991dd33fc4ceabf
34.214286
89
0.664413
4.221694
false
true
false
false
StephaneBg/ScoreIt
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/widget/LineChart.kt
1
5314
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.app.ui.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import androidx.annotation.ColorInt import com.sbgapps.scoreit.app.R import com.sbgapps.scoreit.core.ext.colorAttr import com.sbgapps.scoreit.core.ext.dip class LineChart @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { @Suppress("MemberVisibilityCanBePrivate") var lines = emptyList<LineSet>() set(value) { maxY = value.map { it.getMaxY() }.max() ?: 0f minY = value.map { it.getMinY() }.min() ?: 0f maxX = value.map { it.getMaxX() }.max() ?: 0f minX = value.map { it.getMinX() }.min() ?: 0f field = value postInvalidate() } private val axisColor = context.colorAttr(R.attr.colorOnBackground) private val paint = Paint() private val keySize = context.dip(2).toFloat() private val padding = context.dip(32).toFloat() private var maxY = 0f private var minY = 0f private var maxX = 0f private var minX = 0f init { showEditMode() } public override fun onDraw(canvas: Canvas) { val usableHeight = height - 2 * padding val usableWidth = width - 2 * padding // Draw x-axis line updatePaint(axisColor, keySize / 2) val height: Float height = if (minY < 0) { getHeight().toFloat() - padding - usableHeight * (-minY / (maxY - minY)) } else { getHeight() - padding } canvas.drawLine( padding, height, width - padding, height, paint ) // Draw lines lines.forEach { line -> var index = 0 var lastXPixels = 0f var newYPixels: Float var lastYPixels = 0f var newXPixels: Float updatePaint(line.color, keySize) line.points.forEach { point -> val yPercent = (point.y - minY) / (maxY - minY) val xPercent = (point.x - minX) / (maxX - minX) if (index == 0) { lastXPixels = padding + xPercent * usableWidth lastYPixels = getHeight().toFloat() - padding - usableHeight * yPercent } else { newXPixels = padding + xPercent * usableWidth newYPixels = getHeight().toFloat() - padding - usableHeight * yPercent canvas.drawLine(lastXPixels, lastYPixels, newXPixels, newYPixels, paint) lastXPixels = newXPixels lastYPixels = newYPixels } index++ } } // Draw points lines.forEach { line -> updatePaint(line.color, keySize) if (line.arePointsDisplayed) { line.points.forEach { point -> val yPercent = (point.y - minY) / (maxY - minY) val xPercent = (point.x - minX) / (maxX - minX) val xPixels = padding + xPercent * usableWidth val yPixels = getHeight().toFloat() - padding - usableHeight * yPercent canvas.drawCircle(xPixels, yPixels, 2 * keySize, paint) } } } } private fun updatePaint(color: Int, strokeWidth: Float) { paint.reset() paint.isAntiAlias = true paint.strokeWidth = strokeWidth paint.color = color } private fun showEditMode() { if (isInEditMode) lines = listOf( LineSet( listOf( LinePoint(), LinePoint(1, 2), LinePoint(2, -1) ) ) ) } } data class LinePoint @JvmOverloads constructor(var x: Float = 0f, var y: Float = 0f) { constructor(x: Double, y: Double) : this(x.toFloat(), y.toFloat()) constructor(x: Int, y: Int) : this(x.toFloat(), y.toFloat()) override fun toString(): String = "x=$x, y=$y" } data class LineSet( val points: List<LinePoint>, @ColorInt val color: Int = Color.BLACK, val arePointsDisplayed: Boolean = true ) { val size: Int get() = points.size fun getMinX(): Float = points.map { it.x }.min() ?: 0f fun getMinY(): Float = points.map { it.y }.min() ?: 0f fun getMaxX(): Float = points.map { it.x }.max() ?: 0f fun getMaxY(): Float = points.map { it.y }.max() ?: 0f }
apache-2.0
5d518b78883610ad989d95f7ec4209ae
30.43787
92
0.5671
4.330073
false
false
false
false
allotria/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginModelTest.kt
2
21900
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonGenerator import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.JDOMUtil import com.intellij.project.IntelliJProjectConfiguration import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.throwIfNotEmpty import org.jdom.Element import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil import org.junit.Test import java.io.StringWriter import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path private data class ModuleInfo(val descriptorFile: Path, val isPlugin: Boolean) { val dependencies = mutableListOf<Reference>() val content = mutableListOf<Reference>() } private data class Reference(val moduleName: String, val packageName: String) private val homePath by lazy { Path.of(PathManager.getHomePath()) } private data class PluginTask(val pluginId: String, val moduleName: String, val descriptor: Element, val pluginXml: Path) { val moduleReferences = mutableListOf<Reference>() } private class ModuleDescriptorPath { var pluginDescriptorFile: Path? = null var moduleDescriptorFile: Path? = null var pluginDescriptor: Element? = null var moduleDescriptor: Element? = null } class PluginModelTest { @Test fun check() { val modules = IntelliJProjectConfiguration.loadIntelliJProject(homePath).modules val checker = PluginModelChecker(modules) // we cannot check everything in one pass - before checking we have to compute map of plugin to plugin modules // to be able to correctly check `<depends>Docker</depends>` that in a new plugin model specified as // <module name="intellij.clouds.docker.compose" package="com.intellij.docker.composeFile"/> val moduleNameToFileInfo = computeModuleSet(modules, checker) l@ for ((moduleName, moduleMetaInfo) in moduleNameToFileInfo) { val descriptor = moduleMetaInfo.pluginDescriptor ?: continue val pluginXml = moduleMetaInfo.pluginDescriptorFile ?: continue val id = descriptor.getChild("id")?.text ?: descriptor.getChild("name")?.text if (id == null) { checker.errors.add(PluginValidationError("Plugin id is not specified in ${homePath.relativize(pluginXml)}")) continue } val task = PluginTask(pluginId = id, moduleName = moduleName, descriptor = descriptor, pluginXml = pluginXml) checker.pluginIdToModules.put(id, task) val content = descriptor.getChild("content") if (content != null) { for (item in content.getChildren("module")) { // ignore missed attributes - will be validated on second pass val packageName = item.getAttributeValue("package") ?: continue task.moduleReferences.add(Reference(moduleName = item.getAttributeValue("name") ?: continue, packageName = packageName)) val old = checker.packageToPlugin.put(packageName, task) if (old != null) { checker.errors.add(PluginValidationError("Duplicated package $packageName (old=$old, new=$task)")) continue@l } } } } for (task in checker.pluginIdToModules.values) { checkModule(task, checker) } throwIfNotEmpty(checker.errors) printGraph(checker) } private fun checkModule(info: PluginTask, checker: PluginModelChecker) { val descriptor = info.descriptor val dependencies = descriptor.getChild("dependencies") if (dependencies != null) { val pluginInfo = checker.graph.computeIfAbsent(info.moduleName) { ModuleInfo(info.pluginXml, isPlugin = true) } try { checker.checkDependencies(dependencies, descriptor, info.pluginXml, pluginInfo) } catch (e: PluginValidationError) { checker.errors.add(e) } } val content = descriptor.getChild("content") if (content != null) { val pluginInfo = checker.graph.computeIfAbsent(info.moduleName) { ModuleInfo(info.pluginXml, isPlugin = true) } try { checker.checkContent(content, descriptor, info.pluginXml, pluginInfo) } catch (e: PluginValidationError) { checker.errors.add(e) } } val aPackage = descriptor.getAttributeValue("package") if (aPackage == null && checker.graph.containsKey(info.moduleName) /* something was added */) { // some plugins cannot be yet fully migrated System.err.println("Package is not specified for ${info.moduleName} " + "(pluginId=${info.pluginId}, descriptor=${homePath.relativize(info.pluginXml)})") } } } private fun computeModuleSet(modules: List<JpsModule>, checker: PluginModelChecker): LinkedHashMap<String, ModuleDescriptorPath> { val moduleNameToFileInfo = LinkedHashMap<String, ModuleDescriptorPath>() for (module in modules) { // platform/cwm-plugin/resources/META-INF/plugin.xml doesn't have id - ignore for now if (module.name.startsWith("fleet.") || module.name == "fleet" || module.name == "intellij.idea.ultimate.resources" || module.name == "intellij.lightEdit" || module.name == "intellij.webstorm" || module.name == "intellij.cwm.plugin") { continue } for (sourceRoot in module.sourceRoots) { if (sourceRoot.rootType.isForTests) { continue } val root = Path.of(JpsPathUtil.urlToPath(sourceRoot.url)) val metaInf = root.resolve("META-INF") val pluginDescriptorFile = metaInf.resolve("plugin.xml") val pluginDescriptor = try { JDOMUtil.load(pluginDescriptorFile) } catch (ignore: NoSuchFileException) { null } val moduleDescriptorFile = root.resolve("${module.name}.xml") val moduleDescriptor = try { JDOMUtil.load(moduleDescriptorFile) } catch (ignore: NoSuchFileException) { null } if (Files.exists(metaInf.resolve("${module.name}.xml"))) { checker.errors.add(PluginValidationError("Module descriptor must be in the root of module root", mapOf( "module" to module.name, "moduleDescriptor" to metaInf.resolve("${module.name}.xml"), ))) continue } if (pluginDescriptor == null && moduleDescriptor == null) { continue } val item = moduleNameToFileInfo.computeIfAbsent(module.name) { ModuleDescriptorPath() } if (item.pluginDescriptorFile != null && pluginDescriptor != null) { checker.errors.add(PluginValidationError("Duplicated plugin.xml", mapOf( "module" to module.name, "firstPluginDescriptor" to item.pluginDescriptorFile, "secondPluginDescriptor" to pluginDescriptorFile, ))) continue } if (item.pluginDescriptorFile != null && moduleDescriptor != null) { checker.errors.add(PluginValidationError("Module cannot have both plugin.xml and module descriptor", mapOf( "module" to module.name, "pluginDescriptor" to item.pluginDescriptorFile, "moduleDescriptor" to moduleDescriptorFile, ))) continue } if (item.moduleDescriptorFile != null && pluginDescriptor != null) { checker.errors.add(PluginValidationError("Module cannot have both plugin.xml and module descriptor", mapOf( "module" to module.name, "pluginDescriptor" to pluginDescriptorFile, "moduleDescriptor" to item.moduleDescriptorFile, ))) continue } if (pluginDescriptor == null) { item.moduleDescriptorFile = moduleDescriptorFile item.moduleDescriptor = moduleDescriptor } else { item.pluginDescriptorFile = pluginDescriptorFile item.pluginDescriptor = pluginDescriptor } } } return moduleNameToFileInfo } private fun printGraph(checker: PluginModelChecker) { val stringWriter = StringWriter() val writer = JsonFactory().createGenerator(stringWriter) writer.useDefaultPrettyPrinter() val graph = checker.graph writer.use { writer.obj { val names = graph.keys.toTypedArray() names.sort() for (name in names) { writer.obj(name) { val item = graph.get(name)!! writer.writeStringField("descriptor", homePath.relativize(item.descriptorFile).toString()) writeEntries(item.dependencies, "dependencies", writer) writeEntries(item.content, "content", writer) } } } } println(stringWriter.buffer) Files.writeString(Path.of("/tmp/plugin-report.json"), stringWriter.buffer) } private fun writeEntries(items: List<Reference>, jsonName: String, writer: JsonGenerator) { if (items.isNotEmpty()) { writer.array(jsonName) { for (entry in items) { writer.obj { writer.writeStringField("module", entry.moduleName) writer.writeStringField("modulePackage", entry.packageName) } } } } } private class PluginModelChecker(modules: List<JpsModule>) { val pluginIdToModules = LinkedHashMap<String, PluginTask>() val packageToPlugin = HashMap<String, PluginTask>() val graph = HashMap<String, ModuleInfo>() val errors = mutableListOf<Throwable>() private val nameToModule = modules.associateBy { it.name } fun checkDependencies(element: Element, referencingDescriptor: Element, referencingDescriptorFile: Path, pluginInfo: ModuleInfo) { for (child in element.children) { if (child.name != "module") { if (child.name == "plugin") { if (pluginInfo.isPlugin) { throw PluginValidationError("Plugin cannot depend on plugin: ${JDOMUtil.write(child)}", mapOf( "entry" to child, "descriptorFile" to referencingDescriptorFile, )) } // todo check that the referenced plugin exists continue } if (pluginInfo.isPlugin) { throw PluginValidationError("Unsupported dependency type: ${child.name}", mapOf( "entry" to child, "descriptorFile" to referencingDescriptorFile, )) } } val moduleName = child.getAttributeValue("name") ?: throw PluginValidationError("Module name is not specified") val module = nameToModule.get(moduleName) ?: throw PluginValidationError("Cannot find module $moduleName") if (moduleName == "intellij.platform.commercial.verifier") { continue } val (descriptor, referencedDescriptorFile) = loadFileInModule(module, referencingDescriptorFile = referencingDescriptorFile, child.getAttributeValue("package")!!) val aPackage = checkPackage(descriptor, referencedDescriptorFile, child) pluginInfo.dependencies.add(Reference(moduleName, aPackage)) // check that also specified using depends tag var pluginDependency: String? = null for (dependsElement in referencingDescriptor.getChildren("depends")) { if (dependsElement.getAttributeValue("config-file") == "${module.name}.xml") { pluginDependency = dependsElement.text break } } if (pluginDependency == null) { //<dependencies> // <!-- <depends>Docker</depends> --> // <module name="intellij.clouds.docker.compose" package="com.intellij.docker.composeFile"/> //</dependencies> val task = packageToPlugin.get(aPackage) if (task != null) { for (dependsElement in referencingDescriptor.getChildren("depends")) { if (dependsElement.text == task.pluginId) { pluginDependency = task.pluginId break } } } } if (pluginDependency == null) { throw PluginValidationError("Module, that used as dependency, must be also specified in `depends` (during transition period)." + "\nPlease check that you use correct naming (not arbitrary file name, but exactly as module name plus `.xml` extension).", mapOf( "entry" to child, "referencingDescriptorFile" to referencingDescriptorFile, "referencedDescriptorFile" to referencedDescriptorFile )) } var isPluginDependencySpecified = false for (entryElement in descriptor.getChild("dependencies")?.getChildren("plugin") ?: emptyList()) { if (entryElement.getAttributeValue("id") == pluginDependency) { isPluginDependencySpecified = true break } } if (!isPluginDependencySpecified) { throw PluginValidationError("Module, that used as dependency, must specify dependency on some plugin (`dependencies.plugin`)" + "\n\nProposed fix (add to ${homePath.relativize(referencedDescriptorFile)}):\n\n" + """ <dependencies> <plugin id="$pluginDependency"/> </dependencies> """.trimIndent() + "\n\n", mapOf( "entry" to child, "referencingDescriptorFile" to referencingDescriptorFile, "referencedDescriptorFile" to referencedDescriptorFile )) } descriptor.getChild("dependencies")?.let { try { checkDependencies(it, descriptor, referencedDescriptorFile, graph.computeIfAbsent(moduleName) { ModuleInfo(referencedDescriptorFile, isPlugin = false) }) } catch (e: PluginValidationError) { errors.add(e) } } } } // for plugin two variants: // 1) depends + dependency on plugin in a referenced descriptor = optional descriptor. In old format: depends tag // 2) no depends + no dependency on plugin in a referenced descriptor = directly injected into plugin (separate classloader is not created // during transition period). In old format: xi:include (e.g. <xi:include href="dockerfile-language.xml"/>. fun checkContent(content: Element, referencingDescriptor: Element, referencingDescriptorFile: Path, pluginInfo: ModuleInfo) { for (child in content.children) { if (child.name != "module") { throw PluginValidationError("Unexpected element: ${JDOMUtil.write(child)}") } val moduleName = child.getAttributeValue("name") ?: throw PluginValidationError("Module name is not specified") val module = nameToModule.get(moduleName) ?: throw PluginValidationError("Cannot find module $moduleName") if (moduleName == "intellij.platform.commercial.verifier") { errors.add(PluginValidationError("intellij.platform.commercial.verifier is not supposed to be used as content of plugin", mapOf( "entry" to child, "referencingDescriptorFile" to referencingDescriptorFile, ))) return } val (descriptor, referencedDescriptorFile) = loadFileInModule(module, referencingDescriptorFile, child.getAttributeValue("package")!!) val aPackage = checkPackage(descriptor, referencedDescriptorFile, child) pluginInfo.content.add(Reference(moduleName, aPackage)) // check that also specified using depends tag var oldPluginDependencyId: String? = null for (dependsElement in referencingDescriptor.getChildren("depends")) { if (dependsElement.getAttributeValue("config-file") == "${module.name}.xml") { oldPluginDependencyId = dependsElement.text break } } var isPluginDependencyDeclared = false for (entryElement in descriptor.getChild("dependencies")?.getChildren("plugin") ?: emptyList()) { if (entryElement.getAttributeValue("id") == oldPluginDependencyId) { isPluginDependencyDeclared = true break } } // if dependency specified in a new format in the referenced descriptor, then must be also specified using old depends tag if (oldPluginDependencyId == null && isPluginDependencyDeclared) { throw PluginValidationError("Module, that used as plugin content and depends on a plugin, must be also specified in `depends` (during transition period)." + "\nPlease check that you use correct naming (not arbitrary file name, but exactly as module name plus `.xml` extension).", mapOf( "entry" to child, "referencingDescriptorFile" to referencingDescriptorFile, "referencedDescriptorFile" to referencedDescriptorFile )) } // if there is old depends tag, then dependency in a new format in the referenced descriptor must be also declared if (oldPluginDependencyId != null && !isPluginDependencyDeclared) { throw PluginValidationError("Module, that used as plugin content and depends on a plugin, must specify dependency on the plugin (`dependencies.plugin`)" + "\n\nProposed fix (add to ${homePath.relativize(referencedDescriptorFile)}):\n\n" + """ <dependencies> <plugin id="$oldPluginDependencyId"/> </dependencies> """.trimIndent() + "\n\n", mapOf( "entry" to child, "referencingDescriptorFile" to referencingDescriptorFile, "referencedDescriptorFile" to referencedDescriptorFile )) } descriptor.getChild("content")?.let { try { checkContent(it, descriptor, referencedDescriptorFile, graph.computeIfAbsent(moduleName) { ModuleInfo(referencedDescriptorFile, isPlugin = false) }) } catch (e: PluginValidationError) { errors.add(e) } } } } } private fun checkPackage(descriptor: Element, descriptorFile: Path, child: Element): String { val aPackage = descriptor.getAttributeValue("package") ?: throw PluginValidationError("package attribute is not specified", mapOf("descriptorFile" to descriptorFile)) if (aPackage != child.getAttributeValue("package")) { throw PluginValidationError("package doesn't match", mapOf( "entry" to child, "referencedDescriptorFile" to descriptorFile, "packageInDescriptor" to aPackage )) } return aPackage } private class PluginValidationError(message: String) : RuntimeException(message) { constructor(message: String, params: Map<String, Any?>) : this(message + " (\n ${params.entries.joinToString(separator = ",\n ") { "${it.key}=${paramValueToString(it.value)}" }}\n)") constructor(message: String, params: Map<String, Any?>, fix: String) : this( message + " (\n ${params.entries.joinToString(separator = ",\n ") { "${it.key}=${paramValueToString(it.value)}" }}\n)" + "\n\nProposed fix:\n\n" + fix.trimIndent() + "\n\n" ) } private fun paramValueToString(value: Any?): String { return when (value) { // reformat according to IJ XMl code style is Element -> JDOMUtil.write(value).replace("\" />", "\"/>") is Path -> homePath.relativize(value).toString() else -> value.toString() } } private fun loadFileInModule(module: JpsModule, referencingDescriptorFile: Path, aPackage: String): Pair<Element, Path> { val fileName = "${module.name}.xml" val roots = module.getSourceRoots(JavaResourceRootType.RESOURCE) + module.getSourceRoots(JavaSourceRootType.SOURCE) for (sourceRoot in roots) { try { val file = Path.of(JpsPathUtil.urlToPath(sourceRoot.url), fileName) return Pair(JDOMUtil.load(file), file) } catch (ignore: NoSuchFileException) { } } throw PluginValidationError("Module ${module.name} doesn't have descriptor file", mapOf( "expectedFile" to fileName, "referencingDescriptorFile" to referencingDescriptorFile, ), """ Create file $fileName in ${homePath.relativize(Path.of(JpsPathUtil.urlToPath(roots.first().url)))} with content: <idea-plugin package="$aPackage"> </idea-plugin> """) }
apache-2.0
b5fb044b333a26e3e60591bb43473b66
41.277992
186
0.618219
5.133615
false
false
false
false
langerhans/discord-github-webhooks
src/main/kotlin/de/langerhans/discord/gitbot/discord/EventHandler.kt
1
1568
@file:Suppress("unused") package de.langerhans.discord.gitbot.discord import org.slf4j.LoggerFactory import org.springframework.beans.factory.DisposableBean import org.springframework.stereotype.Component import sx.blah.discord.api.events.EventSubscriber import sx.blah.discord.handle.impl.events.DiscordDisconnectedEvent import sx.blah.discord.handle.impl.events.ReadyEvent import sx.blah.discord.handle.obj.Status /** * Created by maxke on 07.08.2016. * Discord event handler */ @Component open class EventHandler: DisposableBean { private val log = LoggerFactory.getLogger(EventHandler::class.java) fun setup() { // stub for now until we have commands } @EventSubscriber fun onReadyEvent(e: ReadyEvent) { log.info("Bot is ready") /*if (reconnectTimer != null) { (reconnectTimer as Timer).cancel() }*/ e.client.changePresence(false) e.client.changeStatus(Status.game("Pokemon GO")) } /*private val RECONNECT_DELAY = TimeUnit.SECONDS.toMillis(15) private var reconnectTimer: Timer? = null*/ @EventSubscriber fun onDiscordDisconnectedEvent(e: DiscordDisconnectedEvent) { log.info("Got disconnected with reason ${e.reason.name}") /*reconnectTimer = timer("reconnect", false, RECONNECT_DELAY, RECONNECT_DELAY, { if (!e.client.isReady) { e.client.login() } else { reconnectTimer?.cancel() } })*/ } override fun destroy() { //reconnectTimer?.cancel() } }
mit
28c70a5cbc08f88aa07cfe2125540ca3
28.055556
88
0.670918
4.115486
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/task/transfer/TransferParams.kt
1
1450
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.task.transfer import androidx.documentfile.provider.DocumentFile import kotlinx.coroutines.Job import org.monora.uprotocol.client.android.database.model.Transfer import org.monora.uprotocol.core.protocol.Client import org.monora.uprotocol.core.transfer.TransferItem data class TransferParams( val transfer: Transfer, val client: Client, var bytesTotal: Long, var bytesSessionTotal: Long = 0L ) { var averageSpeed = 0L var bytesOngoing = 0L var count = 0 var job: Job? = null var lastFile: DocumentFile? = null var ongoing: TransferItem? = null val startTime = System.currentTimeMillis() }
gpl-2.0
01e64565a2f6c8d0da3e274830d8733c
30.5
82
0.746032
4.175793
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/flow/operators/Delay.kt
1
9941
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("FlowKt") package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.flow.internal.* import kotlinx.coroutines.selects.* import kotlin.jvm.* import kotlin.time.* /* Scaffolding for Knit code examples <!--- TEST_NAME FlowDelayTest --> <!--- PREFIX .*-duration-.* ----- INCLUDE .*-duration-.* import kotlin.time.* ----- INCLUDE .* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlin.time.Duration.Companion.milliseconds fun main() = runBlocking { ----- SUFFIX .* .toList().joinToString().let { println(it) } } --> */ /** * Returns a flow that mirrors the original flow, but filters out values * that are followed by the newer values within the given [timeout][timeoutMillis]. * The latest value is always emitted. * * Example: * * ```kotlin * flow { * emit(1) * delay(90) * emit(2) * delay(90) * emit(3) * delay(1010) * emit(4) * delay(1010) * emit(5) * }.debounce(1000) * ``` * <!--- KNIT example-delay-01.kt --> * * produces the following emissions * * ```text * 3, 4, 5 * ``` * <!--- TEST --> * * Note that the resulting flow does not emit anything as long as the original flow emits * items faster than every [timeoutMillis] milliseconds. */ @FlowPreview public fun <T> Flow<T>.debounce(timeoutMillis: Long): Flow<T> { require(timeoutMillis >= 0L) { "Debounce timeout should not be negative" } if (timeoutMillis == 0L) return this return debounceInternal { timeoutMillis } } /** * Returns a flow that mirrors the original flow, but filters out values * that are followed by the newer values within the given [timeout][timeoutMillis]. * The latest value is always emitted. * * A variation of [debounce] that allows specifying the timeout value dynamically. * * Example: * * ```kotlin * flow { * emit(1) * delay(90) * emit(2) * delay(90) * emit(3) * delay(1010) * emit(4) * delay(1010) * emit(5) * }.debounce { * if (it == 1) { * 0L * } else { * 1000L * } * } * ``` * <!--- KNIT example-delay-02.kt --> * * produces the following emissions * * ```text * 1, 3, 4, 5 * ``` * <!--- TEST --> * * Note that the resulting flow does not emit anything as long as the original flow emits * items faster than every [timeoutMillis] milliseconds. * * @param timeoutMillis [T] is the emitted value and the return value is timeout in milliseconds. */ @FlowPreview @OptIn(kotlin.experimental.ExperimentalTypeInference::class) @OverloadResolutionByLambdaReturnType public fun <T> Flow<T>.debounce(timeoutMillis: (T) -> Long): Flow<T> = debounceInternal(timeoutMillis) /** * Returns a flow that mirrors the original flow, but filters out values * that are followed by the newer values within the given [timeout]. * The latest value is always emitted. * * Example: * * ```kotlin * flow { * emit(1) * delay(90.milliseconds) * emit(2) * delay(90.milliseconds) * emit(3) * delay(1010.milliseconds) * emit(4) * delay(1010.milliseconds) * emit(5) * }.debounce(1000.milliseconds) * ``` * <!--- KNIT example-delay-duration-01.kt --> * * produces the following emissions * * ```text * 3, 4, 5 * ``` * <!--- TEST --> * * Note that the resulting flow does not emit anything as long as the original flow emits * items faster than every [timeout] milliseconds. */ @FlowPreview public fun <T> Flow<T>.debounce(timeout: Duration): Flow<T> = debounce(timeout.toDelayMillis()) /** * Returns a flow that mirrors the original flow, but filters out values * that are followed by the newer values within the given [timeout]. * The latest value is always emitted. * * A variation of [debounce] that allows specifying the timeout value dynamically. * * Example: * * ```kotlin * flow { * emit(1) * delay(90.milliseconds) * emit(2) * delay(90.milliseconds) * emit(3) * delay(1010.milliseconds) * emit(4) * delay(1010.milliseconds) * emit(5) * }.debounce { * if (it == 1) { * 0.milliseconds * } else { * 1000.milliseconds * } * } * ``` * <!--- KNIT example-delay-duration-02.kt --> * * produces the following emissions * * ```text * 1, 3, 4, 5 * ``` * <!--- TEST --> * * Note that the resulting flow does not emit anything as long as the original flow emits * items faster than every [timeout] unit. * * @param timeout [T] is the emitted value and the return value is timeout in [Duration]. */ @FlowPreview @JvmName("debounceDuration") @OptIn(kotlin.experimental.ExperimentalTypeInference::class) @OverloadResolutionByLambdaReturnType public fun <T> Flow<T>.debounce(timeout: (T) -> Duration): Flow<T> = debounceInternal { emittedItem -> timeout(emittedItem).toDelayMillis() } private fun <T> Flow<T>.debounceInternal(timeoutMillisSelector: (T) -> Long) : Flow<T> = scopedFlow { downstream -> // Produce the values using the default (rendezvous) channel val values = produce { collect { value -> send(value ?: NULL) } } // Now consume the values var lastValue: Any? = null while (lastValue !== DONE) { var timeoutMillis = 0L // will be always computed when lastValue != null // Compute timeout for this value if (lastValue != null) { timeoutMillis = timeoutMillisSelector(NULL.unbox(lastValue)) require(timeoutMillis >= 0L) { "Debounce timeout should not be negative" } if (timeoutMillis == 0L) { downstream.emit(NULL.unbox(lastValue)) lastValue = null // Consume the value } } // assert invariant: lastValue != null implies timeoutMillis > 0 assert { lastValue == null || timeoutMillis > 0 } // wait for the next value with timeout select<Unit> { // Set timeout when lastValue exists and is not consumed yet if (lastValue != null) { onTimeout(timeoutMillis) { downstream.emit(NULL.unbox(lastValue)) lastValue = null // Consume the value } } values.onReceiveCatching { value -> value .onSuccess { lastValue = it } .onFailure { it?.let { throw it } // If closed normally, emit the latest value if (lastValue != null) downstream.emit(NULL.unbox(lastValue)) lastValue = DONE } } } } } /** * Returns a flow that emits only the latest value emitted by the original flow during the given sampling [period][periodMillis]. * * Example: * * ```kotlin * flow { * repeat(10) { * emit(it) * delay(110) * } * }.sample(200) * ``` * <!--- KNIT example-delay-03.kt --> * * produces the following emissions * * ```text * 1, 3, 5, 7, 9 * ``` * <!--- TEST --> * * Note that the latest element is not emitted if it does not fit into the sampling window. */ @FlowPreview public fun <T> Flow<T>.sample(periodMillis: Long): Flow<T> { require(periodMillis > 0) { "Sample period should be positive" } return scopedFlow { downstream -> val values = produce(capacity = Channel.CONFLATED) { collect { value -> send(value ?: NULL) } } var lastValue: Any? = null val ticker = fixedPeriodTicker(periodMillis) while (lastValue !== DONE) { select<Unit> { values.onReceiveCatching { result -> result .onSuccess { lastValue = it } .onFailure { it?.let { throw it } ticker.cancel(ChildCancelledException()) lastValue = DONE } } // todo: shall be start sampling only when an element arrives or sample aways as here? ticker.onReceive { val value = lastValue ?: return@onReceive lastValue = null // Consume the value downstream.emit(NULL.unbox(value)) } } } } } /* * TODO this design (and design of the corresponding operator) depends on #540 */ internal fun CoroutineScope.fixedPeriodTicker(delayMillis: Long, initialDelayMillis: Long = delayMillis): ReceiveChannel<Unit> { require(delayMillis >= 0) { "Expected non-negative delay, but has $delayMillis ms" } require(initialDelayMillis >= 0) { "Expected non-negative initial delay, but has $initialDelayMillis ms" } return produce(capacity = 0) { delay(initialDelayMillis) while (true) { channel.send(Unit) delay(delayMillis) } } } /** * Returns a flow that emits only the latest value emitted by the original flow during the given sampling [period]. * * Example: * * ```kotlin * flow { * repeat(10) { * emit(it) * delay(110.milliseconds) * } * }.sample(200.milliseconds) * ``` * <!--- KNIT example-delay-duration-03.kt --> * * produces the following emissions * * ```text * 1, 3, 5, 7, 9 * ``` * <!--- TEST --> * * Note that the latest element is not emitted if it does not fit into the sampling window. */ @FlowPreview public fun <T> Flow<T>.sample(period: Duration): Flow<T> = sample(period.toDelayMillis())
apache-2.0
9fcdeb5f701a7a6381df62509a5b4361
27.648415
129
0.586661
4.016566
false
false
false
false
bitsydarel/DBWeather
app/src/main/java/com/dbeginc/dbweather/base/BaseFragment.kt
1
2454
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweather.base import android.Manifest.permission import android.arch.lifecycle.ViewModelProvider import android.content.pm.PackageManager import android.support.v4.app.ActivityCompat import android.support.v4.content.PermissionChecker import com.dbeginc.dbweather.utils.preferences.ApplicationPreferences import com.dbeginc.dbweather.utils.utility.MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION import dagger.android.support.DaggerFragment import javax.inject.Inject /** * Created by darel on 29.05.17. * * Base Fragment */ open class BaseFragment : DaggerFragment() { @Inject lateinit var preferences: dagger.Lazy<ApplicationPreferences> @Inject lateinit var factory: dagger.Lazy<ViewModelProvider.Factory> protected fun askLocationPermIfNeeded(): Boolean { activity?.let { val isGranted = PermissionChecker.checkSelfPermission(it, permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED if (isGranted) preferences.get().changeGpsPermissionStatus(true) else ActivityCompat.requestPermissions( it, arrayOf(permission.ACCESS_FINE_LOCATION), MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION ) } return preferences.get().isGpsPermissionOn() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) { preferences.get().changeGpsPermissionStatus( grantResults.isNotEmpty() && grantResults.first() == PackageManager.PERMISSION_GRANTED ) } } }
gpl-3.0
205291d24d0a19c190c4de10b1618f61
36.753846
115
0.708231
4.792969
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/editor/optimizeImports/jvm/Operators.dependency.kt
13
284
package p1 operator fun Runnable.plus(p: Int): Runnable = TODO() operator fun Runnable.minus(p: Int): Runnable = TODO() operator fun Runnable.timesAssign(p: Int): Unit = TODO() operator fun Runnable.div(p: Int): Runnable = TODO() operator fun Runnable.unaryMinus(): Runnable = TODO()
apache-2.0
d7f5c6134beaca2b0287129a2f21a5dc
39.714286
56
0.735915
3.786667
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/gradle/GroovyDslPlugin.kt
6
1593
// 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.plugins.buildSystem.gradle import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.PluginSettingsOwner import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildFileData import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemData import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.addBuildSystemData import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter class GroovyDslPlugin(context: Context) : GradlePlugin(context) { override val path = pluginPath companion object : PluginSettingsOwner() { override val pluginPath = "buildSystem.gradle.groovyDsl" val addBuildSystemData by addBuildSystemData( BuildSystemData( type = BuildSystemType.GradleGroovyDsl, buildFileData = BuildFileData( createPrinter = { GradlePrinter(GradlePrinter.GradleDsl.GROOVY) }, buildFileName = "build.gradle" ) ) ) } override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf( addBuildSystemData, ) }
apache-2.0
31570ebb36e9cd58e6f52dd6036ae210
45.882353
158
0.738858
4.886503
false
false
false
false
vanniktech/lint-rules
lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/LayoutFileNameMatchesClassDetector.kt
1
2811
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector.UastScanner import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope.JAVA_FILE import com.android.tools.lint.detector.api.Severity.WARNING import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.getContainingUClass import org.jetbrains.uast.tryResolveNamed import java.util.EnumSet val ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS = Issue.create( "LayoutFileNameMatchesClass", "Checks that the layout file matches the class name.", "Layout file names should always match the name of the class. FooActivity should have a layout file named activity_foo hence.", CORRECTNESS, PRIORITY, WARNING, Implementation(LayoutFileNameMatchesClassDetector::class.java, EnumSet.of(JAVA_FILE)), ) class LayoutFileNameMatchesClassDetector : Detector(), UastScanner { override fun getApplicableMethodNames() = listOf("setContentView") override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { super.visitMethodCall(context, node, method) val resourcePrefix = context.project.resourcePrefix() val firstParameter = node.valueArguments.getOrNull(0) val rLayoutString = firstParameter?.asSourceString() ?.split(".") ?.joinToString(separator = ".") { it.trim() } .orEmpty() val isNoLayoutReference = !rLayoutString.startsWith("R.layout") && !rLayoutString.contains(".R.layout") val layoutFileName = firstParameter ?.tryResolveNamed() ?.name val className = node.getContainingUClass() ?.name if (isNoLayoutReference || layoutFileName == null || className == null) { return } val expectedLayoutFileName = className.toSnakeCase() .replace(resourcePrefix, "") .run { val array = split("_") resourcePrefix + array.last() + "_" + array.subList(0, array.size - 1).joinToString(separator = "_") } val isExactMatch = layoutFileName + "_" == expectedLayoutFileName if (layoutFileName != expectedLayoutFileName && !isExactMatch) { val fix = fix() .replace() .text(layoutFileName) .with(expectedLayoutFileName) .autoFix() .build() context.report(ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS, node, context.getLocation(node.valueArguments.first()), "Parameter should be named R.layout.$expectedLayoutFileName", fix) } } }
apache-2.0
afc679b34fe6a65204c92f50a46a1dd0
37.506849
181
0.73497
4.272036
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogContent.kt
1
2193
package com.habitrpg.android.habitica.ui.views.shops import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout import android.widget.TextView import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.drawee.view.SimpleDraweeView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.dpToPx import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.bindView abstract class PurchaseDialogContent : LinearLayout { private val imageView: SimpleDraweeView by bindView(R.id.imageView) private val titleTextView: TextView by bindView(R.id.titleTextView) protected abstract val viewId: Int constructor(context: Context) : super(context) { setupView() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { setupView() } private fun setupView() { orientation = VERTICAL gravity = Gravity.CENTER inflate(context, viewId, this) } open fun setItem(item: ShopItem) { if (item.path?.contains("timeTravelBackgrounds") == true) { val controller = Fresco.newDraweeControllerBuilder() .setUri("https://habitica-assets.s3.amazonaws.com/mobileApp/images/${item.imageName?.replace("icon_", "")}.gif") .setAutoPlayAnimations(true) .build() imageView.controller = controller val params = imageView.layoutParams params.height = 147.dpToPx(context) params.width = 140.dpToPx(context) imageView.layoutParams = params } else { DataBindingUtils.loadImage(imageView, item.imageName) } titleTextView.text = item.text } open fun setQuestContentItem(questContent: QuestContent) { DataBindingUtils.loadImage(imageView, "inventory_quest_scroll_" + questContent.key) titleTextView.text = questContent.text } }
gpl-3.0
3fc5e8dc8f26932e2ccf3b25e55e3b49
34.370968
132
0.705426
4.646186
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/Video.kt
1
1775
package com.kickstarter.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize class Video private constructor( private val base: String?, private val frame: String?, private val high: String?, private val hls: String?, private val webm: String? ) : Parcelable { fun base() = this.base fun frame() = this.frame fun high() = this.high fun hls() = this.hls fun webm() = this.webm @Parcelize data class Builder( private var base: String? = null, private var frame: String? = null, private var high: String? = null, private var hls: String? = null, private var webm: String? = null, ) : Parcelable { fun base(base: String?) = apply { this.base = base } fun frame(frame: String?) = apply { this.frame = frame } fun high(high: String?) = apply { this.high = high } fun hls(hls: String?) = apply { this.hls = hls } fun webm(webm: String?) = apply { this.webm = webm } fun build() = Video( base = base, frame = frame, high = high, hls = hls, webm = webm ) } fun toBuilder() = Builder( base = base, frame = frame, high = high, hls = hls, webm = webm ) override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is Video) { equals = base() == obj.base() && frame() == obj.frame() && high() == obj.high() && hls() == obj.hls() && webm() == obj.webm() } return equals } companion object { @JvmStatic fun builder() = Builder() } }
apache-2.0
7fc9769541f20db7941af6e1ff0984b0
25.102941
64
0.518873
3.962054
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/ChatMessageDeserializer.kt
1
3123
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.habitrpg.android.habitica.models.social.ChatMessage import com.habitrpg.android.habitica.models.social.ChatMessageLike import com.habitrpg.android.habitica.models.social.UserStyles import com.habitrpg.android.habitica.models.user.Backer import com.habitrpg.android.habitica.models.user.ContributorInfo import io.realm.RealmList import java.lang.reflect.Type import java.util.* class ChatMessageDeserializer : JsonDeserializer<ChatMessage> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ChatMessage { val message = ChatMessage() val obj = json.asJsonObject if (obj.has("text") && !obj.get("text").isJsonNull && obj.get("text").isJsonPrimitive) { message.text = obj.get("text").asString } if (obj.has("timestamp")) { message.timestamp = context.deserialize<Date>(obj.get("timestamp"), Date::class.java).time } if (obj.has("likes")) { message.likes = RealmList() for ((key, value) in obj.getAsJsonObject("likes").entrySet()) { if (value.asBoolean) { message.likes?.add(ChatMessageLike(key, message.id)) } } } if (obj.has("flagCount")) { message.flagCount = obj.get("flagCount").asInt } if (obj.has("uuid")) { message.uuid = obj.get("uuid").asString } if (obj.has("contributor")) { if (!obj.get("contributor").isJsonNull) { if (obj.get("contributor").isJsonObject) { message.contributor = context.deserialize<ContributorInfo>(obj.get("contributor"), ContributorInfo::class.java) } else { val contributor = ContributorInfo() contributor.text = obj.get("contributor").asString message.contributor = contributor } message.contributor?.userId = message.id } } if (obj.has("backer")) { message.backer = context.deserialize<Backer>(obj.get("backer"), Backer::class.java) } if (obj.has("user")) { message.user = obj.get("user").asString } if (obj.has("username") && obj.get("username").isJsonPrimitive) { message.username = obj.get("username").asString } if (obj.has("sent")) { message.sent = obj.get("sent").asBoolean } if (obj.has("userStyles")) { message.userStyles = context.deserialize<UserStyles>(obj.get("userStyles"), UserStyles::class.java) } if (obj.has("id")) { message.id = obj.get("id").asString } return message } }
gpl-3.0
3015de6cf342882e82a5133c8137631b
36.555556
131
0.587896
4.487069
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/codeInsight/mlcompletion/PythonMLRankingProvider.kt
1
1027
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.mlcompletion import com.completion.ranker.model.python.MLCompletionModel import com.intellij.internal.ml.DecisionFunction import com.intellij.internal.ml.ModelMetadata import com.intellij.internal.ml.completion.CompletionRankingModelBase import com.intellij.internal.ml.completion.JarCompletionModelProvider import com.intellij.lang.Language class PythonMLRankingProvider : JarCompletionModelProvider("Python", "python_features") { override fun createModel(metadata: ModelMetadata): DecisionFunction { return object : CompletionRankingModelBase(metadata) { override fun predict(features: DoubleArray?): Double = MLCompletionModel.makePredict(features) } } override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("python", ignoreCase = true) == 0 override fun isEnabledByDefault() = false }
apache-2.0
1a3f7e154e6a398863acc66028d236be
47.952381
140
0.810127
4.668182
false
false
false
false
jwren/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/SurroundAndUnwrapLesson.kt
5
4260
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson.general import training.dsl.* import training.dsl.LessonUtil.checkExpectedStateOfEditor import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import training.util.toNullableString abstract class SurroundAndUnwrapLesson : KLesson("Surround and unwrap", LessonsBundle.message("surround.and.unwrap.lesson.name")) { protected abstract val sample: LessonSample protected abstract val surroundItems: Array<String> protected abstract val lineShiftBeforeUnwrap: Int protected abstract val unwrapTryText: String protected open val surroundItemName: String get() = surroundItems.joinToString(separator = "/") override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(sample) task("SurroundWith") { proposeIfModified { editor.caretModel.currentCaret.selectionStart != sample.selection?.first || editor.caretModel.currentCaret.selectionEnd != sample.selection?.second } text(LessonsBundle.message("surround.and.unwrap.invoke.surround", action(it))) triggerAndBorderHighlight().listItem { item -> surroundItems.all { need -> wordIsPresent(item.toNullableString(), need) } } test { actions(it) } } task { text(LessonsBundle.message("surround.and.unwrap.choose.surround.item", strong(surroundItemName))) stateCheck { editor.document.charsSequence.let { sequence -> surroundItems.all { sequence.contains(it) } } } restoreByUi() test { type("${surroundItems.joinToString(separator = " ")}\n") } } prepareRuntimeTask { editor.caretModel.currentCaret.moveCaretRelatively(0, lineShiftBeforeUnwrap, false, true) } prepareRuntimeTask { // restore point setSample(previous.sample) } task("Unwrap") { proposeIfModified { editor.caretModel.currentCaret.logicalPosition.line != previous.position.line } text(LessonsBundle.message("surround.and.unwrap.invoke.unwrap", action(it))) triggerAndBorderHighlight().listItem { item -> item.toNullableString() == unwrapTryText } test { actions(it) } } task { restoreAfterStateBecomeFalse { previous.ui?.isShowing != true } text(LessonsBundle.message("surround.and.unwrap.choose.unwrap.item", strong(LearnBundle.message("surround.and.unwrap.item", surroundItems[0])))) stateCheck { editor.document.charsSequence.let { sequence -> !surroundItems.any { sequence.contains(it) } } } test { type("${surroundItems[0]}\n") } } } private fun wordIsPresent(text: String?, word: String): Boolean { if (text == null) return false var index = 0 while (index != -1 && index < text.length) { index = text.indexOf(word, startIndex = index) if (index != -1) { if ((index == 0 || !text[index - 1].isLetterOrDigit()) && (index + word.length == text.length || !text[index + word.length].isLetterOrDigit())) return true index += word.length } } return false } private fun TaskContext.proposeIfModified(checkCaret: TaskRuntimeContext.() -> Boolean) { proposeRestore { checkExpectedStateOfEditor(previous.sample, false) ?: if (checkCaret()) TaskContext.RestoreNotification(TaskContext.CaretRestoreProposal, callback = restorePreviousTaskCallback) else null } } override val suitableTips = listOf("SurroundWith") override val helpLinks: Map<String, String> = mapOf( Pair(LessonsBundle.message("surround.and.unwrap.help.surround.code.fragments"), LessonUtil.getHelpLink("surrounding-blocks-of-code-with-language-constructs.html")), Pair(LessonsBundle.message("surround.and.unwrap.help.unwrapping.and.removing.statements"), LessonUtil.getHelpLink("working-with-source-code.html#unwrap_remove_statement")), ) }
apache-2.0
65048012b06b3e0ba6960f47561406eb
36.707965
140
0.667606
4.733333
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/LegacyDescriptorUtils.kt
1
6096
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.descriptors import org.jetbrains.kotlin.backend.common.atMostOne import org.jetbrains.kotlin.backend.konan.RuntimeNames import org.jetbrains.kotlin.builtins.konan.KonanBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isUnit /** * Implementation of given method. * * TODO: this method is actually a part of resolve and probably duplicates another one */ internal fun <T : CallableMemberDescriptor> T.resolveFakeOverride(allowAbstract: Boolean = false): T { if (this.kind.isReal) { return this } else { val overridden = OverridingUtil.getOverriddenDeclarations(this) val filtered = OverridingUtil.filterOutOverridden(overridden) // TODO: is it correct to take first? @Suppress("UNCHECKED_CAST") return filtered.first { allowAbstract || it.modality != Modality.ABSTRACT } as T } } internal val ClassDescriptor.isArray: Boolean get() = this.fqNameSafe.asString() in arrayTypes internal val ClassDescriptor.isInterface: Boolean get() = (this.kind == ClassKind.INTERFACE) /** * @return `konan.internal` member scope */ internal val KonanBuiltIns.kotlinNativeInternal: MemberScope get() = this.builtInsModule.getPackage(RuntimeNames.kotlinNativeInternalPackageName).memberScope internal fun ClassDescriptor.isUnit() = this.defaultType.isUnit() internal fun ClassDescriptor.isNothing() = this.defaultType.isNothing() internal val <T : CallableMemberDescriptor> T.allOverriddenDescriptors: List<T> get() { val result = mutableListOf<T>() fun traverse(descriptor: T) { result.add(descriptor) @Suppress("UNCHECKED_CAST") descriptor.overriddenDescriptors.forEach { traverse(it as T) } } traverse(this) return result } internal val ClassDescriptor.contributedMethods: List<FunctionDescriptor> get () = unsubstitutedMemberScope.contributedMethods internal val MemberScope.contributedMethods: List<FunctionDescriptor> get () { val contributedDescriptors = this.getContributedDescriptors() val functions = contributedDescriptors.filterIsInstance<FunctionDescriptor>() val properties = contributedDescriptors.filterIsInstance<PropertyDescriptor>() val getters = properties.mapNotNull { it.getter } val setters = properties.mapNotNull { it.setter } return functions + getters + setters } fun ClassDescriptor.isAbstract() = this.modality == Modality.SEALED || this.modality == Modality.ABSTRACT internal val FunctionDescriptor.target: FunctionDescriptor get() = (if (modality == Modality.ABSTRACT) this else resolveFakeOverride()).original tailrec internal fun DeclarationDescriptor.findPackage(): PackageFragmentDescriptor { return if (this is PackageFragmentDescriptor) this else this.containingDeclaration!!.findPackage() } internal fun DeclarationDescriptor.findPackageView(): PackageViewDescriptor { val packageFragment = this.findPackage() return packageFragment.module.getPackage(packageFragment.fqName) } internal fun DeclarationDescriptor.allContainingDeclarations(): List<DeclarationDescriptor> { var list = mutableListOf<DeclarationDescriptor>() var current = this.containingDeclaration while (current != null) { list.add(current) current = current.containingDeclaration } return list } fun AnnotationDescriptor.getStringValueOrNull(name: String): String? { val constantValue = this.allValueArguments.entries.atMostOne { it.key.asString() == name }?.value return constantValue?.value as String? } inline fun <reified T> AnnotationDescriptor.getArgumentValueOrNull(name: String): T? { val constantValue = this.allValueArguments.entries.atMostOne { it.key.asString() == name }?.value return constantValue?.value as T? } fun AnnotationDescriptor.getStringValue(name: String): String = this.getStringValueOrNull(name)!! private fun getPackagesFqNames(module: ModuleDescriptor): Set<FqName> { val result = mutableSetOf<FqName>() val packageFragmentProvider = (module as? ModuleDescriptorImpl)?.packageFragmentProviderForModuleContentWithoutDependencies fun getSubPackages(fqName: FqName) { result.add(fqName) val subPackages = packageFragmentProvider?.getSubPackagesOf(fqName) { true } ?: module.getSubPackagesOf(fqName) { true } subPackages.forEach { getSubPackages(it) } } getSubPackages(FqName.ROOT) return result } fun ModuleDescriptor.getPackageFragments(): List<PackageFragmentDescriptor> = getPackagesFqNames(this).flatMap { getPackage(it).fragments.filter { it.module == this }.toSet() } val ClassDescriptor.enumEntries: List<ClassDescriptor> get() { assert(this.kind == ClassKind.ENUM_CLASS) return this.unsubstitutedMemberScope.getContributedDescriptors() .filterIsInstance<ClassDescriptor>() .filter { it.kind == ClassKind.ENUM_ENTRY } } internal val DeclarationDescriptor.isExpectMember: Boolean get() = this is MemberDescriptor && this.isExpect internal val DeclarationDescriptor.isSerializableExpectClass: Boolean get() = this is ClassDescriptor && ExpectedActualDeclarationChecker.shouldGenerateExpectClass(this)
apache-2.0
003b7a5f5bf82eaa62508097cd4aaf1e
37.1
127
0.749508
4.853503
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/verifier/DatabaseVerifier.kt
3
7958
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.verifier import androidx.room.compiler.processing.XElement import androidx.room.processor.Context import androidx.room.vo.DatabaseView import androidx.room.vo.Entity import androidx.room.vo.EntityOrView import androidx.room.vo.FtsEntity import androidx.room.vo.FtsOptions import androidx.room.vo.Warning import java.io.File import java.sql.Connection import java.sql.Driver import java.sql.DriverManager import java.sql.SQLException import java.util.regex.Pattern import org.sqlite.JDBC import org.sqlite.SQLiteJDBCLoader /** * Builds an in-memory version of the database and verifies the queries against it. * This class is also used to resolve the return types. */ class DatabaseVerifier private constructor( val connection: Connection, val context: Context, entities: List<Entity>, views: List<DatabaseView> ) { val entitiesAndViews: List<EntityOrView> = entities + views companion object { private const val CONNECTION_URL = "jdbc:sqlite::memory:" /** * Taken from: * https://github.com/robolectric/robolectric/blob/master/shadows/framework/ * src/main/java/org/robolectric/shadows/ShadowSQLiteConnection.java#L94 * * This is actually not accurate because it might swap anything since it does not parse * SQL. That being said, for the verification purposes, it does not matter and clearly * much easier than parsing and rebuilding the query. */ private val COLLATE_LOCALIZED_UNICODE_PATTERN = Pattern.compile( "\\s+COLLATE\\s+(LOCALIZED|UNICODE)", Pattern.CASE_INSENSITIVE ) /** * Keep a reference to the SQLite JDBC driver so we can re-register it in the case that Room * finishes processing, cleans up and unregisters the driver but is started again within the * same class loader such that JDBC's static block and driver registration does not occur. */ private val DRIVER: Driver init { verifyTempDir() // Synchronize on a bootstrap loaded class so that parallel runs of Room in the same JVM // with isolated class loaders (such as the Gradle daemon) don't conflict with each // other when extracting the native library. SQLiteJDBCLoader already handles // multiple library versions, process isolation and multiple class loaders by using // UUID named library files. synchronized(System::class.java) { SQLiteJDBCLoader.initialize() // extract and loads native library JDBC.isValidURL(CONNECTION_URL) // call to register driver DRIVER = DriverManager.getDriver("jdbc:sqlite:") // get registered driver check(DRIVER is JDBC) { "Expected driver to be a '${JDBC::class.java}' but was '${DRIVER::class.java}'" } } } private fun verifyTempDir() { val defaultTempDir = System.getProperty("java.io.tmpdir") val tempDir = System.getProperty("org.sqlite.tmpdir", defaultTempDir) checkNotNull(tempDir) { "Room needs the java.io.tmpdir or org.sqlite.tmpdir system property to be set to " + "setup SQLite." } File(tempDir).also { check( it.isDirectory && (it.exists() || it.mkdirs()) && it.canRead() && it.canWrite() ) { "The temp dir [$tempDir] needs to be a directory, must be readable, writable " + "and allow executables. Please, provide a temporary directory that " + "fits the requirements via the 'org.sqlite.tmpdir' property." } } } /** * Tries to create a verifier but returns null if it cannot find the driver. */ fun create( context: Context, element: XElement, entities: List<Entity>, views: List<DatabaseView> ): DatabaseVerifier? { try { // Re-register driver in case it was unregistered, this is a no-op is already there. DriverManager.registerDriver(DRIVER) val connection = JDBC.createConnection(CONNECTION_URL, java.util.Properties()) return DatabaseVerifier(connection, context, entities, views) } catch (ex: Exception) { context.logger.w( Warning.CANNOT_CREATE_VERIFICATION_DATABASE, element, DatabaseVerificationErrors.cannotCreateConnection(ex) ) return null } } /** * Unregisters the SQLite JDBC driver used by the verifier. * * This is necessary since the driver is statically registered and never unregistered and * can cause class loader leaks. See https://github.com/google/ksp/issues/1063. */ fun cleanup() { try { DriverManager.deregisterDriver(DRIVER) } catch (ignored: SQLException) { // Driver was not found } } } init { entities.forEach { entity -> val stmt = connection.createStatement() val createTableQuery = if (entity is FtsEntity && !FtsOptions.defaultTokenizers.contains(entity.ftsOptions.tokenizer) ) { // Custom FTS tokenizer used, use create statement without custom tokenizer // since the DB used for verification probably doesn't have the tokenizer. entity.getCreateTableQueryWithoutTokenizer() } else { entity.createTableQuery } try { stmt.executeUpdate(stripLocalizeCollations(createTableQuery)) } catch (e: SQLException) { context.logger.e(entity.element, "${e.message}") } entity.indices.forEach { stmt.executeUpdate(it.createQuery(entity.tableName)) } } views.forEach { view -> val stmt = connection.createStatement() try { stmt.executeUpdate(stripLocalizeCollations(view.createViewQuery)) } catch (e: SQLException) { context.logger.e(view.element, "${e.message}") } } } fun analyze(sql: String): QueryResultInfo { return try { val stmt = connection.prepareStatement(stripLocalizeCollations(sql)) QueryResultInfo(stmt.columnInfo()) } catch (ex: SQLException) { QueryResultInfo(emptyList(), ex) } } private fun stripLocalizeCollations(sql: String) = COLLATE_LOCALIZED_UNICODE_PATTERN.matcher(sql).replaceAll(" COLLATE NOCASE") fun closeConnection(context: Context) { if (!connection.isClosed) { try { connection.close() } catch (t: Throwable) { // ignore. context.logger.d("failed to close the database connection ${t.message}") } } } }
apache-2.0
f5b10c8f3990f13c80eb8666b8420b33
38.79
100
0.603292
4.964442
false
false
false
false
androidx/androidx
constraintlayout/constraintlayout-compose/src/androidMain/kotlin/androidx/constraintlayout/compose/ConstraintLayoutTag.kt
5
3119
/* * 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.constraintlayout.compose import androidx.compose.runtime.Immutable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.ParentDataModifier import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Density /** * Alternative to [androidx.compose.ui.layout.layoutId] that enables the use of [tag]. * * @param layoutId The unique Id string assigned to the Composable * @param tag A string to represent a group of Composables that may be affected by a * ConstraintLayout function. Eg: The `Variables` block in a JSON5 based [ConstraintSet] */ fun Modifier.layoutId(layoutId: String, tag: String? = null): Modifier { if (tag == null) { // Fallback to androidx.compose.ui.layout.layoutId return this.layoutId(layoutId) } else { return this.then( ConstraintLayoutTag( constraintLayoutId = layoutId, constraintLayoutTag = tag, inspectorInfo = debugInspectorInfo { name = "constraintLayoutId" value = layoutId } ) ) } } @Immutable private class ConstraintLayoutTag( override val constraintLayoutTag: String, override val constraintLayoutId: String, inspectorInfo: InspectorInfo.() -> Unit ) : ParentDataModifier, ConstraintLayoutTagParentData, InspectorValueInfo(inspectorInfo) { override fun Density.modifyParentData(parentData: Any?): Any? { return this@ConstraintLayoutTag } override fun hashCode(): Int = constraintLayoutTag.hashCode() override fun equals(other: Any?): Boolean { if (this === other) return true val otherModifier = other as? ConstraintLayoutTag ?: return false return constraintLayoutTag == otherModifier.constraintLayoutTag } override fun toString(): String = "ConstraintLayoutTag(id=$constraintLayoutTag)" } interface ConstraintLayoutTagParentData { val constraintLayoutId: String val constraintLayoutTag: String } val Measurable.constraintLayoutTag: Any? get() = (parentData as? ConstraintLayoutTagParentData)?.constraintLayoutTag val Measurable.constraintLayoutId: Any? get() = (parentData as? ConstraintLayoutTagParentData)?.constraintLayoutId
apache-2.0
852cb42e51461b8307d994dd6a2a9fb3
35.27907
90
0.723629
4.732929
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/statistics/src/org/jetbrains/kotlin/idea/statistics/J2KFusCollector.kt
4
2060
// 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.statistics import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoById import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin class J2KFusCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { private val GROUP = EventLogGroup("kotlin.ide.j2k", 2) private val sourceType = EventFields.String("source_type", ConversionType.values().map { it.text }) private val isNewJ2K = EventFields.Boolean("is_new_j2k") private val conversionTime = EventFields.Long("conversion_time") private val linesCount = EventFields.Int("lines_count") private val filesCount = EventFields.Int("files_count") private val pluginInfo = EventFields.PluginInfo private val event = GROUP.registerVarargEvent( "Conversion", sourceType, isNewJ2K, conversionTime, linesCount, filesCount, pluginInfo, ) fun log( type: ConversionType, isNewJ2k: Boolean, conversionTime: Long, linesCount: Int, filesCount: Int ) = event.log( this.sourceType.with(type.text), this.isNewJ2K.with(isNewJ2k), this.conversionTime.with(conversionTime), this.linesCount.with(linesCount), this.filesCount.with(filesCount), this.pluginInfo.with(getPluginInfoById(KotlinIdePlugin.id)), ) } } enum class ConversionType(val text: String) { FILES("Files"), PSI_EXPRESSION("PSI_expression"), TEXT_EXPRESSION("Text_expression"); }
apache-2.0
cc9e4631da9e1ab39ec0796347982878
38.634615
158
0.682039
4.577778
false
false
false
false
GunoH/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleModuleData.kt
8
2540
// 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.plugins.gradle.util import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil @ApiStatus.Experimental class GradleModuleData(private val dataNode: DataNode<out ModuleData>) { val moduleData = dataNode.data init { val systemId = moduleData.owner require(systemId == GradleConstants.SYSTEM_ID) { "Gradle module expected but '$systemId' module has been got." } } val moduleName = moduleData.moduleName val gradleProjectDir = moduleData.linkedExternalProjectPath val directoryToRunTask: String get() = moduleData.getDirectoryToRunTask() val gradlePath: String get() = moduleData.getGradlePath() val compositeBuildGradlePath: String get() = moduleData.getCompositeBuildGradlePath() val fullGradlePath: String get() = compositeBuildGradlePath + gradlePath val isBuildSrcModule: Boolean get() = moduleData.isBuildSrcModule() fun getTaskPath(simpleTaskName: String, prependCompositeBuildPath: Boolean = true): String { val path = if (prependCompositeBuildPath) fullGradlePath else gradlePath return "${path.trimEnd(':')}:$simpleTaskName" } fun <T> findAll(key: Key<T>): Collection<T> { return ExternalSystemApiUtil.findAll(dataNode, key).mapNotNull { it.data } } fun <T> find(key: Key<T>): T? { return ExternalSystemApiUtil.find(dataNode, key)?.data } } fun ModuleData.getDirectoryToRunTask() = getProperty("directoryToRunTask") ?: linkedExternalProjectPath fun ModuleData.setDirectoryToRunTask(directoryToRunTask: String) = setProperty("directoryToRunTask", directoryToRunTask) fun ModuleData.getGradlePath() = GradleProjectResolverUtil.getGradlePath(this) fun ModuleData.getCompositeBuildGradlePath() = getProperty("compositeBuildGradlePath") ?: "" fun ModuleData.setCompositeBuildGradlePath(compositeBuildGradlePath: String) = setProperty("compositeBuildGradlePath", compositeBuildGradlePath) fun ModuleData.isBuildSrcModule() = getProperty("buildSrcModule")?.toBoolean() ?: false fun ModuleData.setBuildSrcModule() = setProperty("buildSrcModule", true.toString())
apache-2.0
e91ba2b3c132eae5569e998fe9e2aaf2
44.375
158
0.791339
4.6098
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Identifier.kt
4
1863
// 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.j2k.ast import com.intellij.psi.PsiNameIdentifierOwner import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.lexer.KtKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName fun PsiNameIdentifierOwner.declarationIdentifier(): Identifier { val name = name return if (name != null) Identifier(name, false).assignPrototype(nameIdentifier) else Identifier.Empty } class Identifier( val name: String, override val isNullable: Boolean = true, private val quotingNeeded: Boolean = true, private val imports: Collection<FqName> = emptyList() ) : Expression() { override val isEmpty: Boolean get() = name.isEmpty() private fun toKotlin(): String { if (quotingNeeded && KEYWORDS.contains(name) || name.contains("$")) { return quote(name) } return name } override fun generateCode(builder: CodeBuilder) { builder.append(toKotlin()) imports.forEach { builder.addImport(it) } } private fun quote(str: String): String = "`$str`" override fun toString() = if (isNullable) "$name?" else name companion object { val Empty = Identifier("") private val KEYWORDS = KtTokens.KEYWORDS.types.map { (it as KtKeywordToken).value }.toSet() fun toKotlin(name: String): String = Identifier(name).toKotlin() fun withNoPrototype(name: String, isNullable: Boolean = true, quotingNeeded: Boolean = true, imports: Collection<FqName> = emptyList()): Identifier { return Identifier(name, isNullable, quotingNeeded, imports).assignNoPrototype() } } }
apache-2.0
1fa1433e2d7a87198226cc4238940e29
32.872727
158
0.688674
4.446301
false
false
false
false
lsmaira/gradle
buildSrc/subprojects/plugins/src/main/kotlin/org/gradle/build/ClasspathManifest.kt
1
2840
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.build import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.ExternalDependency import org.gradle.api.artifacts.FileCollectionDependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import accessors.base import gradlebuildJava import org.gradle.kotlin.dsl.* import java.io.File import java.util.Properties @CacheableTask @Suppress("unused") open class ClasspathManifest : DefaultTask() { @get:Internal val input: Configuration = project.configurations["runtimeClasspath"] @get:Input var optionalProjects: List<String> = emptyList() @get:Internal var additionalProjects: List<Project> = emptyList() @get:OutputFile val manifestFile: File get() { return File(project.gradlebuildJava.generatedResourcesDir, "${project.base.archivesBaseName}-classpath.properties") } @get:Input val runtime: String get() = input .fileCollection { it is ExternalDependency || it is FileCollectionDependency } .joinForProperties { it.name } @get:Input val projects: String get() = (input.allDependencies.withType<ProjectDependency>().filter { it.dependencyProject.plugins.hasPlugin("java-base") }.map { it.dependencyProject.base.archivesBaseName } + additionalProjects.map { it.base.archivesBaseName }) .joinForProperties() @TaskAction fun generate() { ReproduciblePropertiesWriter.store(createProperties(), manifestFile) } private fun createProperties() = Properties().also { properties -> properties["runtime"] = runtime properties["projects"] = projects if (optionalProjects.isNotEmpty()) { properties["optional"] = optionalProjects.joinForProperties() } } private fun <T : Any> Iterable<T>.joinForProperties(transform: ((T) -> CharSequence)? = null) = joinToString(",", transform = transform) }
apache-2.0
b1273d27326f405feaa1d30a7fe47aa3
32.023256
182
0.71831
4.444444
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/tests/test/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionHandlerTestBase.kt
8
5951
// 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.completion.test.handlers import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.* import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.openapi.project.Project import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import org.jetbrains.kotlin.idea.completion.test.ExpectedCompletionUtils import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase abstract class CompletionHandlerTestBase : KotlinLightCodeInsightFixtureTestCase() { protected val fixture: JavaCodeInsightTestFixture get() = myFixture companion object { fun doTestWithTextLoaded( fixture: JavaCodeInsightTestFixture, completionType: CompletionType, time: Int, lookupString: String?, itemText: String?, tailText: String?, completionChars: String, afterFilePath: String, actions: List<String>? = emptyList(), afterTypingBlock: () -> Unit = {} ) { for (idx in 0 until completionChars.length - 1) { fixture.type(completionChars[idx]) afterTypingBlock() } if (!actions.isNullOrEmpty()) { for (action in actions) { fixture.performEditorAction(action) } } fixture.complete(completionType, time) if (lookupString != null || itemText != null || tailText != null) { val item = getExistentLookupElement(fixture.project, lookupString, itemText, tailText) if (item != null) { selectItem(fixture, item, completionChars.last()) } } afterTypingBlock() fixture.checkResultByFile(afterFilePath) } fun completionChars(text: String): String { val char: String? = InTextDirectivesUtils.findStringWithPrefixes(text, AbstractCompletionHandlerTest.COMPLETION_CHAR_PREFIX) val chars: String? = InTextDirectivesUtils.findStringWithPrefixes(text, AbstractCompletionHandlerTest.COMPLETION_CHARS_PREFIX) return when (char) { null -> when (chars) { null -> "\n" else -> chars.replace("\\n", "\n").replace("\\t", "\t") } "\\n" -> "\n" "\\t" -> "\t" else -> char.single().toString() } } fun getExistentLookupElement(project: Project, lookupString: String?, itemText: String?, tailText: String?): LookupElement? { val lookup = LookupManager.getInstance(project)?.activeLookup as LookupImpl? ?: return null val items = lookup.items if (lookupString == "*") { assert(itemText == null) assert(tailText == null) return items.firstOrNull() } var foundElement: LookupElement? = null val presentation = LookupElementPresentation() for (lookupElement in items) { val lookupOk = if (lookupString != null) lookupElement.lookupString == lookupString else true if (lookupOk) { lookupElement.renderElement(presentation) val textOk = if (itemText != null) { val itemItemText = presentation.itemText itemItemText != null && itemItemText == itemText } else { true } if (textOk) { val tailOk = if (tailText != null) { val itemTailText = presentation.tailText tailText.isEmpty() && itemTailText == null || itemTailText != null && itemTailText == tailText } else { true } if (tailOk) { if (foundElement != null) { val dump = ExpectedCompletionUtils.listToString( ExpectedCompletionUtils.getItemsInformation( arrayOf( foundElement, lookupElement ) ) ) fail("Several elements satisfy to completion restrictions:\n$dump") } foundElement = lookupElement } } } } if (foundElement == null) { val dump = ExpectedCompletionUtils.listToString(ExpectedCompletionUtils.getItemsInformation(items.toTypedArray())) error("No element satisfy completion restrictions in:\n$dump") } return foundElement } fun selectItem(fixture: JavaCodeInsightTestFixture, item: LookupElement?, completionChar: Char) { val lookup = (fixture.lookup as LookupImpl) if (lookup.currentItem != item) { // do not touch selection if not changed - important for char filter tests lookup.currentItem = item } lookup.lookupFocusDegree = LookupFocusDegree.FOCUSED if (LookupEvent.isSpecialCompletionChar(completionChar)) { lookup.finishLookup(completionChar) } else { fixture.type(completionChar) } } } }
apache-2.0
c0cbcbf25b27838e0a0ef0b8ecb67691
41.205674
138
0.535876
6.060081
false
true
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/VFUEntity2Impl.kt
2
10342
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class VFUEntity2Impl(val dataSource: VFUEntity2Data) : VFUEntity2, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val filePath: VirtualFileUrl? get() = dataSource.filePath override val directoryPath: VirtualFileUrl get() = dataSource.directoryPath override val notNullRoots: List<VirtualFileUrl> get() = dataSource.notNullRoots override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: VFUEntity2Data?) : ModifiableWorkspaceEntityBase<VFUEntity2, VFUEntity2Data>(result), VFUEntity2.Builder { constructor() : this(VFUEntity2Data()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity VFUEntity2 is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null index(this, "filePath", this.filePath) index(this, "directoryPath", this.directoryPath) index(this, "notNullRoots", this.notNullRoots.toHashSet()) // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field VFUEntity2#data should be initialized") } if (!getEntityData().isDirectoryPathInitialized()) { error("Field VFUEntity2#directoryPath should be initialized") } if (!getEntityData().isNotNullRootsInitialized()) { error("Field VFUEntity2#notNullRoots should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_notNullRoots = getEntityData().notNullRoots if (collection_notNullRoots is MutableWorkspaceList<*>) { collection_notNullRoots.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as VFUEntity2 if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (this.filePath != dataSource?.filePath) this.filePath = dataSource.filePath if (this.directoryPath != dataSource.directoryPath) this.directoryPath = dataSource.directoryPath if (this.notNullRoots != dataSource.notNullRoots) this.notNullRoots = dataSource.notNullRoots.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override var filePath: VirtualFileUrl? get() = getEntityData().filePath set(value) { checkModificationAllowed() getEntityData(true).filePath = value changedProperty.add("filePath") val _diff = diff if (_diff != null) index(this, "filePath", value) } override var directoryPath: VirtualFileUrl get() = getEntityData().directoryPath set(value) { checkModificationAllowed() getEntityData(true).directoryPath = value changedProperty.add("directoryPath") val _diff = diff if (_diff != null) index(this, "directoryPath", value) } private val notNullRootsUpdater: (value: List<VirtualFileUrl>) -> Unit = { value -> val _diff = diff if (_diff != null) index(this, "notNullRoots", value.toHashSet()) changedProperty.add("notNullRoots") } override var notNullRoots: MutableList<VirtualFileUrl> get() { val collection_notNullRoots = getEntityData().notNullRoots if (collection_notNullRoots !is MutableWorkspaceList) return collection_notNullRoots if (diff == null || modifiable.get()) { collection_notNullRoots.setModificationUpdateAction(notNullRootsUpdater) } else { collection_notNullRoots.cleanModificationUpdateAction() } return collection_notNullRoots } set(value) { checkModificationAllowed() getEntityData(true).notNullRoots = value notNullRootsUpdater.invoke(value) } override fun getEntityClass(): Class<VFUEntity2> = VFUEntity2::class.java } } class VFUEntity2Data : WorkspaceEntityData<VFUEntity2>() { lateinit var data: String var filePath: VirtualFileUrl? = null lateinit var directoryPath: VirtualFileUrl lateinit var notNullRoots: MutableList<VirtualFileUrl> fun isDataInitialized(): Boolean = ::data.isInitialized fun isDirectoryPathInitialized(): Boolean = ::directoryPath.isInitialized fun isNotNullRootsInitialized(): Boolean = ::notNullRoots.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<VFUEntity2> { val modifiable = VFUEntity2Impl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): VFUEntity2 { return getCached(snapshot) { val entity = VFUEntity2Impl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): VFUEntity2Data { val clonedEntity = super.clone() clonedEntity as VFUEntity2Data clonedEntity.notNullRoots = clonedEntity.notNullRoots.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return VFUEntity2::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return VFUEntity2(data, directoryPath, notNullRoots, entitySource) { this.filePath = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as VFUEntity2Data if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false if (this.filePath != other.filePath) return false if (this.directoryPath != other.directoryPath) return false if (this.notNullRoots != other.notNullRoots) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as VFUEntity2Data if (this.data != other.data) return false if (this.filePath != other.filePath) return false if (this.directoryPath != other.directoryPath) return false if (this.notNullRoots != other.notNullRoots) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + directoryPath.hashCode() result = 31 * result + notNullRoots.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() result = 31 * result + filePath.hashCode() result = 31 * result + directoryPath.hashCode() result = 31 * result + notNullRoots.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.notNullRoots?.let { collector.add(it::class.java) } this.filePath?.let { collector.add(it::class.java) } this.directoryPath?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
3b3cad93656acc220cbbefc71cfec120
34.417808
130
0.715336
5.067124
false
false
false
false
knes1/kotao
src/main/kotlin/io/github/knes1/kotao/brew/services/Configuration.kt
1
2293
package io.github.knes1.kotao.brew.services import io.github.knes1.kotao.brew.repositories.impl.FileRepositoryConfiguration import io.github.knes1.kotao.brew.repositories.impl.MongoRepositoryConfiguration import io.github.knes1.kotao.brew.repositories.impl.RepositoryConfiguration /** * @author knesek * Created on: 5/15/16 */ data class Configuration ( val collections: List<PageCollection> = emptyList(), val pages: List<SimplePage> = emptyList(), val vars: Map<String, Any> = emptyMap(), val repositories: List<RepositoryConfiguration> = listOf( FileRepositoryConfiguration(), MongoRepositoryConfiguration() ), val structure: ProjectStructure = ProjectStructure(), val site: String? = null ) data class ProjectStructure( val baseDir: String = "", val assets: String = "assets", val templates: String = "templates", val output: String = "output" ) { fun pathToAssets() = pathRelativeToBaseDir(assets) fun pathToTemplates() = pathRelativeToBaseDir(templates) fun pathToOutput() = pathRelativeToBaseDir(output) private fun pathRelativeToBaseDir(relative: String) = if (baseDir.isNullOrBlank()) relative else baseDir + "/" + relative } data class PageCollection ( val name: String = throw InvalidConfigurationException("Configuration section 'collections' - every collection needs to have non empty 'name' parameter."), val slug: String = "slug", val pathProperty: String? = null, val basePath: String = name, val contentProperty: String = "content", val contentType: String = "html", val template: String = name, val repository: String? = null ) data class SimplePage ( val name: String = throw InvalidConfigurationException("Configuration section 'pages' - every simple page needs to have non empty 'name' parameter."), val template: String = name?.split("/")?.last(), val paginate: Paginate? = null, val sitemap: Boolean = true ) data class Paginate ( val collection: String = throw InvalidConfigurationException("Configuration section 'paginate' - every paginate section needs to have a 'collection' parameter that refers to collection name that is going to be paginated."), val pageSize: Int = 10 )
mit
a93353ea8e4d4cc4d0e5391373029181
36.590164
227
0.711295
4.496078
false
true
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/lists/MarkdownListIndentProvider.kt
1
3084
package org.intellij.plugins.markdown.editor.lists import com.intellij.codeInsight.editorActions.AutoHardWrapHandler import com.intellij.lang.Language import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.impl.source.codeStyle.lineIndent.FormatterBasedLineIndentProvider import com.intellij.psi.util.PsiEditorUtil import com.intellij.psi.util.parentOfTypes import com.intellij.refactoring.suggested.startOffset import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentRange import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLineSafely import com.intellij.util.text.CharArrayUtil import org.intellij.plugins.markdown.lang.MarkdownLanguage import org.intellij.plugins.markdown.lang.psi.impl.MarkdownBlockQuote import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.settings.MarkdownSettings /** * This is a helper class for the [MarkdownListEnterHandlerDelegate] to provide correct indentation for new lines, created on Enter. * * [FormatterBasedLineIndentProvider] is extended to be able to fallback to the default behaviour */ internal class MarkdownListIndentProvider : FormatterBasedLineIndentProvider() { override fun getLineIndent(project: Project, editor: Editor, language: Language?, offset: Int): String? { if (!MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) { return null } val file = PsiEditorUtil.getPsiFile(editor) as? MarkdownFile ?: return null return doGetLineIndent(editor, file, offset) ?: super.getLineIndent(project, editor, language, offset) } private fun doGetLineIndent(editor: Editor, file: MarkdownFile, offset: Int): String? { if (isInBlockQuoteOrCodeFence(editor, file)) return null if (editor.getUserData(AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY) == true) return null val document = editor.document val prevLine = document.getLineNumber(offset) - 1 val listItem = file.getListItemAtLineSafely(prevLine, document) ?: file.getListItemAtLineSafely(prevLine - 1, document) ?: return null val firstLine = document.getLineNumber(listItem.startOffset) val indentRange = document.getLineIndentRange(firstLine) return document.getText(indentRange) } private fun isInBlockQuoteOrCodeFence(editor: Editor, file: MarkdownFile): Boolean { val document = editor.document val prevLine = document.getLineNumber(editor.caretModel.offset) - 1 if (prevLine == -1) return false val prevLineEnd = document.getLineEndOffset(prevLine) val beforeWhitespaceOffset = CharArrayUtil.shiftBackward(document.text, prevLineEnd - 1, " \t") if (beforeWhitespaceOffset == -1) return false return file.findElementAt(beforeWhitespaceOffset) ?.parentOfTypes(MarkdownBlockQuote::class, MarkdownCodeFence::class) != null } override fun isSuitableFor(language: Language?) = language is MarkdownLanguage }
apache-2.0
9bb9d89ae5565119af2063f34f33c0a2
45.727273
132
0.787938
4.495627
false
false
false
false
smmribeiro/intellij-community
python/ide/impl/src/com/jetbrains/python/sdk/configuration/PySdkConfigurationCollector.kt
12
3731
// 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 com.jetbrains.python.sdk.configuration import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project class PySdkConfigurationCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { internal enum class Source { CONFIGURATOR, INSPECTION } internal enum class InputData { NOT_FILLED, SPECIFIED } internal enum class VirtualEnvResult { CREATION_FAILURE, DEPS_NOT_FOUND, INSTALLATION_FAILURE, CREATED } internal enum class CondaEnvResult { LISTING_FAILURE, CREATION_FAILURE, NO_LISTING_DIFFERENCE, AMBIGUOUS_LISTING_DIFFERENCE, NO_BINARY, AMBIGUOUS_BINARIES, CREATED } internal enum class PipEnvResult { CREATION_FAILURE, NO_EXECUTABLE, NO_EXECUTABLE_FILE, CREATED } internal fun logVirtualEnvDialog(project: Project, permitted: Boolean, source: Source, baseSdk: InputData) { venvDialogEvent.log(project, permitted.asDialogResult, source, baseSdk) } internal fun logVirtualEnv(project: Project, result: VirtualEnvResult): Unit = venvEvent.log(project, result) internal fun logCondaEnvDialog(project: Project, permitted: Boolean, source: Source, condaPath: InputData) { condaEnvDialogEvent.log(project, permitted.asDialogResult, source, condaPath) } internal fun logCondaEnvDialogSkipped(project: Project, source: Source, condaPath: InputData) { condaEnvDialogEvent.log(project, DialogResult.SKIPPED, source, condaPath) } internal fun logCondaEnv(project: Project, result: CondaEnvResult): Unit = condaEnvEvent.log(project, result) internal fun logPipEnvDialog(project: Project, permitted: Boolean, source: Source, pipenvPath: InputData) { pipenvDialogEvent.log(project, permitted.asDialogResult, source, pipenvPath) } internal fun logPipEnv(project: Project, result: PipEnvResult): Unit = pipenvEvent.log(project, result) private val GROUP = EventLogGroup("python.sdk.configuration", 1) private enum class DialogResult { OK, CANCELLED, SKIPPED } private val Boolean.asDialogResult: DialogResult get() = if (this) DialogResult.OK else DialogResult.CANCELLED private val venvDialogEvent = GROUP.registerEvent( "venv.dialog.closed", EventFields.Enum("dialog_result", DialogResult::class.java), EventFields.Enum("source", Source::class.java), EventFields.Enum("baseSdk", InputData::class.java) ) private val venvEvent = GROUP.registerEvent("venv.created", EventFields.Enum("env_result", VirtualEnvResult::class.java)) private val condaEnvDialogEvent = GROUP.registerEvent( "condaEnv.dialog.closed", EventFields.Enum("dialog_result", DialogResult::class.java), EventFields.Enum("source", Source::class.java), EventFields.Enum("conda_path", InputData::class.java) ) private val condaEnvEvent = GROUP.registerEvent("condaEnv.created", EventFields.Enum("env_result", CondaEnvResult::class.java)) private val pipenvDialogEvent = GROUP.registerEvent( "pipenv.dialog.closed", EventFields.Enum("dialog_result", DialogResult::class.java), EventFields.Enum("source", Source::class.java), EventFields.Enum("pipenv_path", InputData::class.java) ) private val pipenvEvent = GROUP.registerEvent("pipenv.created", EventFields.Enum("env_result", PipEnvResult::class.java)) } }
apache-2.0
755178666fa5dcbac07a0dd8cbd2a738
43.428571
140
0.746449
4.154788
false
false
false
false
android/sunflower
app/src/main/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModel.kt
1
2341
/* * Copyright 2018 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.samples.apps.sunflower.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.google.samples.apps.sunflower.BuildConfig import com.google.samples.apps.sunflower.PlantDetailFragment import com.google.samples.apps.sunflower.data.GardenPlantingRepository import com.google.samples.apps.sunflower.data.PlantRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.text.Typography.dagger /** * The ViewModel used in [PlantDetailFragment]. */ @HiltViewModel class PlantDetailViewModel @Inject constructor( savedStateHandle: SavedStateHandle, plantRepository: PlantRepository, private val gardenPlantingRepository: GardenPlantingRepository, ) : ViewModel() { val plantId: String = savedStateHandle.get<String>(PLANT_ID_SAVED_STATE_KEY)!! val isPlanted = gardenPlantingRepository.isPlanted(plantId).asLiveData() val plant = plantRepository.getPlant(plantId).asLiveData() private val _showSnackbar = MutableLiveData(false) val showSnackbar: LiveData<Boolean> get() = _showSnackbar fun addPlantToGarden() { viewModelScope.launch { gardenPlantingRepository.createGardenPlanting(plantId) _showSnackbar.value = true } } fun dismissSnackbar() { _showSnackbar.value = false } fun hasValidUnsplashKey() = (BuildConfig.UNSPLASH_ACCESS_KEY != "null") companion object { private const val PLANT_ID_SAVED_STATE_KEY = "plantId" } }
apache-2.0
ddb1a873044f5a7f7126f123b76bd0b8
32.927536
82
0.761213
4.519305
false
false
false
false
AlexKrupa/kotlin-koans
src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt
1
763
package i_introduction._1_Java_To_Kotlin_Converter import util.TODO fun todoTask1(collection: Collection<Int>): Nothing = TODO( """ Task 1. Rewrite JavaCode1.task1 in Kotlin. In IntelliJ IDEA, you can just copy-paste the code and agree tail automatically convert it tail Kotlin, but only for this task! """, references = { JavaCode1().task1(collection) }) fun task1(collection: Collection<Int>): String { val sb = StringBuilder() sb.append("{") val iterator = collection.iterator() while (iterator.hasNext()) { val element = iterator.next() sb.append(element) if (iterator.hasNext()) { sb.append(", ") } } sb.append("}") return sb.toString() }
mit
3f002408ad49cbb60ca31f09317476d7
26.285714
111
0.61599
4.169399
false
false
false
false
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/file/IgnoreTemplatesFactory.kt
1
1983
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package mobi.hsz.idea.gitignore.file import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.util.IncorrectOperationException import mobi.hsz.idea.gitignore.IgnoreBundle import mobi.hsz.idea.gitignore.file.type.IgnoreFileType import mobi.hsz.idea.gitignore.util.Constants /** * Templates factory that generates Gitignore file and its content. */ class IgnoreTemplatesFactory(private val fileType: IgnoreFileType) : FileTemplateGroupDescriptorFactory { override fun getFileTemplatesDescriptor() = FileTemplateGroupDescriptor( fileType.ignoreLanguage.id, fileType.icon ).apply { addTemplate(fileType.ignoreLanguage.filename) } /** * Creates new Gitignore file or uses an existing one. * * @param directory working directory * @return file */ @Throws(IncorrectOperationException::class) fun createFromTemplate(directory: PsiDirectory): PsiFile { val filename = fileType.ignoreLanguage.filename directory.findFile(filename)?.let { return it } val language = fileType.ignoreLanguage val content = when { language.isSyntaxSupported && IgnoreBundle.Syntax.GLOB != language.defaultSyntax -> StringUtil.join( IgnoreBundle.Syntax.GLOB.presentation, Constants.NEWLINE, Constants.NEWLINE ) else -> "" } val file = PsiFileFactory.getInstance(directory.project).createFileFromText(filename, fileType, content) return directory.add(file) as PsiFile } }
mit
68ed3c9cfc2d74e8c07be7db8c97e84e
37.134615
140
0.722642
4.872236
false
false
false
false
team4186/season-2017
src/main/kotlin/org/usfirst/frc/team4186/di/modules/states.kt
1
1182
package org.usfirst.frc.team4186.di.modules import com.github.salomonbrys.kodein.* import org.usfirst.frc.team4186.extensions.DSState import org.usfirst.frc.team4186.routines.Autonomous import org.usfirst.frc.team4186.robot.State import org.usfirst.frc.team4186.routines.Teleop val states_module = Kodein.Module { bind<State>(DSState.kStateAutonomous) with provider { Autonomous( scheduler = instance(), turn = factory(Commands.TURN), move = factory(Commands.MOVE) ) } bind<State>(DSState.kStateTeleop) with provider { Teleop( drive = instance(), climber = instance(Hardware.Motor.CLIMBER), joystickAdapter = instance(), sonar = instance(Hardware.Sonar.FRONT), ahrs = instance(), startCamera = factory() ) } bind<State>(DSState.kStateTest) with provider { instance<State>() } bind<State>(DSState.kStateDisabled) with provider { instance<State>() } bind<State>(DSState.kStateEnabled) with provider { instance<State>() } bind<State>() with singleton { object : State { override fun init() {} override fun tick() {} override fun cleanUp() {} } } }
mit
ee98eb2f4fb3658a2f81af1b4488e426
27.853659
73
0.675973
3.705329
false
false
false
false
sksamuel/ktest
kotest-extensions/src/jvmMain/kotlin/io/kotest/extensions/system/SystemEnvironmentExtensions.kt
1
12360
package io.kotest.extensions.system import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.core.listeners.ProjectListener import io.kotest.core.listeners.TestListener import io.kotest.extensions.system.OverrideMode.SetOrError import java.lang.reflect.Field import java.util.Locale /** * Modifies System Environment with chosen key and value * * This is a helper function for code that uses Environment Variables. It changes the specific [key] from [System.getenv] * with the specified [value], only during the execution of [block]. * * To do this, this function uses a trick that makes the System Environment editable, and changes [key]. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of [block], the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ inline fun <T> withEnvironment(key: String, value: String?, mode: OverrideMode = SetOrError, block: () -> T): T { return withEnvironment(key to value, mode, block) } /** * Modifies System Environment with chosen key and value * * This is a helper function for code that uses Environment Variables. It changes the specific key from [System.getenv] * with the specified value, only during the execution of [block]. * * To do this, this function uses a trick that makes the System Environment editable, and changes key. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of [block], the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ inline fun <T> withEnvironment(environment: Pair<String, String?>, mode: OverrideMode = SetOrError, block: () -> T): T { return withEnvironment(mapOf(environment), mode, block) } /** * Modifies System Environment with chosen keys and values * * This is a helper function for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, only during the execution of [block]. * * To do this, this function uses a trick that makes the System Environment editable, and changes key. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of [block], the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ inline fun <T> withEnvironment(environment: Map<String, String?>, mode: OverrideMode = SetOrError, block: () -> T): T { val isWindows = "windows" in System.getProperty("os.name").orEmpty().lowercase() val originalEnvironment = if (isWindows) { System.getenv().toSortedMap(String.CASE_INSENSITIVE_ORDER) } else { System.getenv() } setEnvironmentMap(mode.override(originalEnvironment, environment)) try { return block() } finally { setEnvironmentMap(originalEnvironment) } } @PublishedApi // Implementation inspired from https://github.com/stefanbirkner/system-rule internal fun setEnvironmentMap(map: Map<String, String?>) { val envMapOfVariables = getEditableMapOfVariables() val caseInsensitiveEnvironment = getCaseInsensitiveEnvironment() envMapOfVariables.clear() caseInsensitiveEnvironment?.clear() envMapOfVariables.putReplacingNulls(map) caseInsensitiveEnvironment?.putReplacingNulls(map) } @Suppress("UNCHECKED_CAST") private fun getEditableMapOfVariables(): MutableMap<String, String> { val systemEnv = System.getenv() val classOfMap = systemEnv::class.java return classOfMap.getDeclaredField("m").asAccessible().get(systemEnv) as MutableMap<String, String> } @Suppress("UNCHECKED_CAST") private fun getCaseInsensitiveEnvironment(): MutableMap<String, String>? { val processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment") return try { processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment").asAccessible().get(null) as MutableMap<String, String>? } catch (e: NoSuchFieldException) { // Only available in Windows, ok to return null if it's not found null } } private fun Field.asAccessible(): Field { return apply { isAccessible = true } } abstract class SystemEnvironmentListener(private val environment: Map<String, String>, private val mode: OverrideMode) { private val originalEnvironment = System.getenv().toMap() protected fun changeSystemEnvironment() { setEnvironmentMap(mode.override(originalEnvironment, environment)) } protected fun resetSystemEnvironment() { setEnvironmentMap(originalEnvironment) } } /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, only during the execution of a test. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the test, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ class SystemEnvironmentTestListener(environment: Map<String, String>, mode: OverrideMode = SetOrError) : SystemEnvironmentListener(environment, mode), TestListener { /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, only during the execution of a test. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the test, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ constructor(key: String, value: String, mode: OverrideMode = SetOrError) : this(key to value, mode) /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, only during the execution of a test. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the test, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ constructor(environment: Pair<String, String>, mode: OverrideMode = SetOrError) : this(mapOf(environment), mode) override suspend fun beforeAny(testCase: TestCase) { changeSystemEnvironment() } override suspend fun afterAny(testCase: TestCase, result: TestResult) { resetSystemEnvironment() } } /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, during the execution of the project. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the project, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ class SystemEnvironmentProjectListener(environment: Map<String, String>, mode: OverrideMode = SetOrError) : SystemEnvironmentListener(environment, mode), ProjectListener { /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, during the execution of the project. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the project, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ constructor(key: String, value: String, mode: OverrideMode = SetOrError) : this(key to value, mode) /** * Modifies System Environment with chosen keys and values * * This is a Listener for code that uses Environment Variables. It changes the specific keys from [System.getenv] * with the specified values, during the execution of the project. * * To do this, this listener uses a trick that makes the System Environment editable, and changes the keys. Any previous * environment (anything not overridden) will also be in the environment. If the chosen key is in the environment, * it will be changed according to [mode]. If the chosen key is not in the environment, it will be included. * * After the execution of the project, the environment is set to what it was before. * * **ATTENTION**: This code is susceptible to race conditions. If you attempt to change the environment while it was * already changed, the result is inconsistent, as the System Environment Map is a single map. */ constructor(environment: Pair<String, String>, mode: OverrideMode = SetOrError) : this(mapOf(environment), mode) override suspend fun beforeProject() { changeSystemEnvironment() } override suspend fun afterProject() { resetSystemEnvironment() } }
mit
4f1cd3befe30591ec0de0aef92aec613
47.661417
135
0.7411
4.501092
false
true
false
false
aosp-mirror/platform_frameworks_support
navigation/safe-args-gradle-plugin/src/main/kotlin/androidx/navigation/safeargs/gradle/ArgumentsGenerationTask.kt
1
4455
/* * 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.navigation.safeargs.gradle import androidx.navigation.safe.args.generator.ErrorMessage import androidx.navigation.safe.args.generator.generateSafeArgs import com.android.build.gradle.internal.tasks.IncrementalTask import com.android.ide.common.resources.FileStatus import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.gradle.api.GradleException import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.OutputDirectory import java.io.File private const val MAPPING_FILE = "file_mappings.json" open class ArgumentsGenerationTask : IncrementalTask() { @get:Input lateinit var rFilePackage: String @get:Input lateinit var applicationId: String @get:OutputDirectory lateinit var outputDir: File @get:InputFiles var navigationFiles: List<File> = emptyList() private fun generateArgs(navFiles: Collection<File>, out: File) = navFiles.map { file -> val output = generateSafeArgs(rFilePackage, applicationId, file, out) Mapping(file.relativeTo(project.projectDir).path, output.files) to output.errors }.unzip().let { (mappings, errorLists) -> mappings to errorLists.flatten() } private fun writeMappings(mappings: List<Mapping>) { File(incrementalFolder, MAPPING_FILE).writer().use { Gson().toJson(mappings, it) } } private fun readMappings(): List<Mapping> { val type = object : TypeToken<List<Mapping>>() {}.type val mappingsFile = File(incrementalFolder, MAPPING_FILE) if (mappingsFile.exists()) { return mappingsFile.reader().use { Gson().fromJson(it, type) } } else { return emptyList() } } override fun doFullTaskAction() { if (outputDir.exists() && !outputDir.deleteRecursively()) { project.logger.warn("Failed to clear directory for navigation arguments") } if (!outputDir.exists() && !outputDir.mkdirs()) { throw GradleException("Failed to create directory for navigation arguments") } val (mappings, errors) = generateArgs(navigationFiles, outputDir) writeMappings(mappings) failIfErrors(errors) } override fun doIncrementalTaskAction(changedInputs: MutableMap<File, FileStatus>) { super.doIncrementalTaskAction(changedInputs) val oldMapping = readMappings() val navFiles = changedInputs.filter { (_, status) -> status != FileStatus.REMOVED }.keys val (newMapping, errors) = generateArgs(navFiles, outputDir) val newJavaFiles = newMapping.flatMap { it.javaFiles }.toSet() val (modified, unmodified) = oldMapping.partition { File(project.projectDir, it.navFile) in changedInputs } modified.flatMap { it.javaFiles } .filter { name -> name !in newJavaFiles } .forEach { javaName -> val fileName = "${javaName.replace('.', File.separatorChar)}.java" val file = File(outputDir, fileName) if (file.exists()) { file.delete() } } writeMappings(unmodified + newMapping) failIfErrors(errors) } private fun failIfErrors(errors: List<ErrorMessage>) { if (errors.isNotEmpty()) { val errString = errors.joinToString("\n") { it.toClickableText() } throw GradleException( "androidx.navigation.safeargs plugin failed.\n " + "Following errors found: \n$errString") } } override fun isIncremental() = true } private fun ErrorMessage.toClickableText() = "$path:$line:$column: error: $message" private data class Mapping(val navFile: String, val javaFiles: List<String>)
apache-2.0
1a14c622ebe6a49c9374cb1f015656e9
38.424779
96
0.668911
4.532045
false
false
false
false
SDILogin/RouteTracker
app/src/main/java/me/sdidev/simpleroutetracker/snapshot/ExternalStorageSnapshotManager.kt
1
2026
package me.sdidev.simpleroutetracker.snapshot import android.content.Context import android.content.ContextWrapper import android.graphics.Bitmap import io.reactivex.Single import me.sdidev.simpleroutetracker.App import me.sdidev.simpleroutetracker.core.Route import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.io.FileOutputStream import javax.inject.Inject const val ROUTES_DIRECTORY_NAME = "routes" const val QUALITY = 65 class ExternalStorageSnapshotManager @Inject constructor(applicationContext: App): SnapshotManager { private val logger: Logger = LoggerFactory.getLogger(ExternalStorageSnapshotManager::class.java) private val routesDirectory: File = ContextWrapper(applicationContext).getDir(ROUTES_DIRECTORY_NAME, Context.MODE_PRIVATE) override fun store(storeRequest: StoreRequest): Single<Image> { return Single.fromCallable { val pathToSnapshot = fileForRoute(storeRequest.route) logger.debug("path to snapshot: {}", pathToSnapshot) val fileOutputStream = FileOutputStream(pathToSnapshot) storeRequest.mapSnapshot.compress(Bitmap.CompressFormat.PNG, QUALITY, fileOutputStream) fileOutputStream.close() logger.debug("saved: {}", pathToSnapshot) Image(pathToSnapshot.absolutePath) } } override fun restore(route: Route): Single<Image> { return Single.fromCallable { val snapshotFile = fileForRoute(route) if (snapshotFile.exists()) { logger.debug("restored shapshot: {}", snapshotFile.absolutePath) Image(snapshotFile.absolutePath) } else { logger.debug("failed to restore shapshot for: {}", route.id) throw RuntimeException("failed to restore shapshot for route with id: ${route.id}") } } } private fun fileForRoute(route: Route): File { return File(routesDirectory, "route_${route.id}.png") } }
mit
4bf73cc4b18a79100eca81341341961d
33.338983
126
0.700395
4.700696
false
false
false
false
seventhroot/elysium
bukkit/rpk-food-bukkit/src/main/kotlin/com/rpkit/food/bukkit/expiry/RPKExpiryProviderImpl.kt
1
2381
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.food.bukkit.expiry import com.rpkit.food.bukkit.RPKFoodBukkit import org.bukkit.inventory.ItemStack import java.text.SimpleDateFormat import java.util.* class RPKExpiryProviderImpl(private val plugin: RPKFoodBukkit): RPKExpiryProvider { val dateFormat = SimpleDateFormat(plugin.config.getString("date-format")) override fun setExpiry(item: ItemStack, expiryDate: Date) { if (!item.type.isEdible) return val itemMeta = item.itemMeta ?: plugin.server.itemFactory.getItemMeta(item.type) ?: return val lore = itemMeta.lore ?: mutableListOf<String>() lore.removeAll(lore.filter { it.startsWith("Expires: ") }) lore.add("Expires: ${dateFormat.format(expiryDate)}") itemMeta.lore = lore item.itemMeta = itemMeta } override fun setExpiry(item: ItemStack) { setExpiry(item, Date(System.currentTimeMillis() + (plugin.config.getLong("food-expiry.${item.type}", plugin.config.getLong("food-expiry.default")) * 1000))) } override fun getExpiry(item: ItemStack): Date? { if (!item.type.isEdible) return null val itemMeta = item.itemMeta ?: plugin.server.itemFactory.getItemMeta(item.type) ?: return null val lore = itemMeta.lore if (lore != null) { val expiryLore = lore.firstOrNull { it.startsWith("Expires: ") } if (expiryLore != null) { val expiryDateString = expiryLore.drop("Expires: ".length) return dateFormat.parse(expiryDateString) } } return null } override fun isExpired(item: ItemStack): Boolean { val expiryTimestamp = getExpiry(item) ?: return true return expiryTimestamp.time <= System.currentTimeMillis() } }
apache-2.0
ea9b5c6178c395f522746c9b5c725013
36.809524
108
0.679546
4.305606
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/GnTypedHandler.kt
1
1341
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile class GnTypedHandler : TypedHandlerDelegate() { override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result { if (GnLanguage != file.language) { return Result.CONTINUE } return if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) { Result.CONTINUE } else Result.CONTINUE } override fun checkAutoPopup(charTyped: Char, project: Project, editor: Editor, file: PsiFile): Result { if (GnLanguage != file.language) { return Result.CONTINUE } if (charTyped == '"' || charTyped == '/' || charTyped == ':') { AutoPopupController.getInstance(project).scheduleAutoPopup(editor) return Result.STOP } return Result.CONTINUE } }
bsd-3-clause
2f94e929dd24962d2461e752a9d5b628
36.25
80
0.708427
4.576792
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/算法/算法书籍/图/DepthFirstSearchUF.kt
1
1130
package 算法.算法书籍.图 import 算法.算法书籍.工具.IteratorNode import java.awt.Paint import java.util.* import kotlin.collections.HashMap /** * 连通分量。深度和广度搜索都是可以找到一段从某个点开始的连通分量的 * * 所以循环 所有的点 对这个点进行深度搜索。 * 如果这个点已经被以前的深度搜索标记过。那么跳过这个点。如果没有那么就是新的片段 count++ */ class DepthFirstSearchUF(g: Graph, s: Int) : DepthFirstSearch(g, s) { private val ids = arrayOfNulls<Int>(g.vertex) as Array<Int> private var count = 0 init { for (i in 0 until g.vertex) { if (!marked[i]) { dfs(g, i, node) count++ //:count 从0开始 } } } override fun initUseDfs(g: Graph) { // super.initUseDfs(g) } override fun dfs(g: Graph, v: Int, node: IteratorNode<Pair<Int, Boolean>>) { ids[v] = count super.dfs(g, v, node) } fun count() = count fun connect(v: Int, w: Int) = ids[v] == ids[w] fun id(v: Int) = ids[v] }
epl-1.0
4903782bc9c627ebc6610f28ee6d0fda
21.317073
80
0.582057
2.720238
false
false
false
false
solokot/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/Constants.kt
1
9973
package com.simplemobiletools.gallery.pro.helpers import com.simplemobiletools.commons.helpers.MONTH_SECONDS import com.simplemobiletools.commons.helpers.isQPlus // shared preferences const val DIRECTORY_SORT_ORDER = "directory_sort_order" const val GROUP_FOLDER_PREFIX = "group_folder_" const val VIEW_TYPE_PREFIX = "view_type_folder_" const val SHOW_HIDDEN_MEDIA = "show_hidden_media" const val TEMPORARILY_SHOW_HIDDEN = "temporarily_show_hidden" const val IS_THIRD_PARTY_INTENT = "is_third_party_intent" const val AUTOPLAY_VIDEOS = "autoplay_videos" const val REMEMBER_LAST_VIDEO_POSITION = "remember_last_video_position" const val LOOP_VIDEOS = "loop_videos" const val OPEN_VIDEOS_ON_SEPARATE_SCREEN = "open_videos_on_separate_screen" const val ANIMATE_GIFS = "animate_gifs" const val MAX_BRIGHTNESS = "max_brightness" const val CROP_THUMBNAILS = "crop_thumbnails" const val SHOW_THUMBNAIL_VIDEO_DURATION = "show_thumbnail_video_duration" const val SCREEN_ROTATION = "screen_rotation" const val DISPLAY_FILE_NAMES = "display_file_names" const val BLACK_BACKGROUND = "dark_background" const val PINNED_FOLDERS = "pinned_folders" const val FILTER_MEDIA = "filter_media" const val DEFAULT_FOLDER = "default_folder" const val DIR_COLUMN_CNT = "dir_column_cnt" const val DIR_LANDSCAPE_COLUMN_CNT = "dir_landscape_column_cnt" const val DIR_HORIZONTAL_COLUMN_CNT = "dir_horizontal_column_cnt" const val DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "dir_landscape_horizontal_column_cnt" const val MEDIA_COLUMN_CNT = "media_column_cnt" const val MEDIA_LANDSCAPE_COLUMN_CNT = "media_landscape_column_cnt" const val MEDIA_HORIZONTAL_COLUMN_CNT = "media_horizontal_column_cnt" const val MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "media_landscape_horizontal_column_cnt" const val SHOW_ALL = "show_all" // display images and videos from all folders together const val HIDE_FOLDER_TOOLTIP_SHOWN = "hide_folder_tooltip_shown" const val EXCLUDED_FOLDERS = "excluded_folders" const val INCLUDED_FOLDERS = "included_folders" const val ALBUM_COVERS = "album_covers" const val HIDE_SYSTEM_UI = "hide_system_ui" const val DELETE_EMPTY_FOLDERS = "delete_empty_folders" const val ALLOW_PHOTO_GESTURES = "allow_photo_gestures" const val ALLOW_VIDEO_GESTURES = "allow_video_gestures" const val TEMP_FOLDER_PATH = "temp_folder_path" const val VIEW_TYPE_FOLDERS = "view_type_folders" const val VIEW_TYPE_FILES = "view_type_files" const val SHOW_EXTENDED_DETAILS = "show_extended_details" const val EXTENDED_DETAILS = "extended_details" const val HIDE_EXTENDED_DETAILS = "hide_extended_details" const val ALLOW_INSTANT_CHANGE = "allow_instant_change" const val WAS_NEW_APP_SHOWN = "was_new_app_shown_clock" const val LAST_FILEPICKER_PATH = "last_filepicker_path" const val TEMP_SKIP_DELETE_CONFIRMATION = "temp_skip_delete_confirmation" const val BOTTOM_ACTIONS = "bottom_actions" const val LAST_VIDEO_POSITION_PREFIX = "last_video_position_" const val VISIBLE_BOTTOM_ACTIONS = "visible_bottom_actions" const val WERE_FAVORITES_PINNED = "were_favorites_pinned" const val WAS_RECYCLE_BIN_PINNED = "was_recycle_bin_pinned" const val USE_RECYCLE_BIN = "use_recycle_bin" const val GROUP_BY = "group_by" const val EVER_SHOWN_FOLDERS = "ever_shown_folders" const val SHOW_RECYCLE_BIN_AT_FOLDERS = "show_recycle_bin_at_folders" const val SHOW_RECYCLE_BIN_LAST = "show_recycle_bin_last" const val ALLOW_ZOOMING_IMAGES = "allow_zooming_images" const val WAS_SVG_SHOWING_HANDLED = "was_svg_showing_handled" const val LAST_BIN_CHECK = "last_bin_check" const val SHOW_HIGHEST_QUALITY = "show_highest_quality" const val ALLOW_DOWN_GESTURE = "allow_down_gesture" const val LAST_EDITOR_CROP_ASPECT_RATIO = "last_editor_crop_aspect_ratio" const val LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_X = "last_editor_crop_other_aspect_ratio_x_2" const val LAST_EDITOR_CROP_OTHER_ASPECT_RATIO_Y = "last_editor_crop_other_aspect_ratio_y_2" const val GROUP_DIRECT_SUBFOLDERS = "group_direct_subfolders" const val SHOW_WIDGET_FOLDER_NAME = "show_widget_folder_name" const val ALLOW_ONE_TO_ONE_ZOOM = "allow_one_to_one_zoom" const val ALLOW_ROTATING_WITH_GESTURES = "allow_rotating_with_gestures" const val LAST_EDITOR_DRAW_COLOR = "last_editor_draw_color" const val LAST_EDITOR_BRUSH_SIZE = "last_editor_brush_size" const val SHOW_NOTCH = "show_notch" const val FILE_LOADING_PRIORITY = "file_loading_priority" const val SPAM_FOLDERS_CHECKED = "spam_folders_checked" const val SHOW_THUMBNAIL_FILE_TYPES = "show_thumbnail_file_types" const val EDITOR_BRUSH_COLOR = "editor_brush_color" const val EDITOR_BRUSH_HARDNESS = "editor_brush_hardness" const val EDITOR_BRUSH_SIZE = "editor_brush_size" const val WERE_FAVORITES_MIGRATED = "were_favorites_migrated" const val FOLDER_THUMBNAIL_STYLE = "folder_thumbnail_style" const val FOLDER_MEDIA_COUNT = "folder_media_count" const val LIMIT_FOLDER_TITLE = "folder_limit_title" const val THUMBNAIL_SPACING = "thumbnail_spacing" const val FILE_ROUNDED_CORNERS = "file_rounded_corners" const val CUSTOM_FOLDERS_ORDER = "custom_folders_order" // slideshow const val SLIDESHOW_INTERVAL = "slideshow_interval" const val SLIDESHOW_INCLUDE_VIDEOS = "slideshow_include_videos" const val SLIDESHOW_INCLUDE_GIFS = "slideshow_include_gifs" const val SLIDESHOW_RANDOM_ORDER = "slideshow_random_order" const val SLIDESHOW_MOVE_BACKWARDS = "slideshow_move_backwards" const val SLIDESHOW_ANIMATION = "slideshow_animation" const val SLIDESHOW_LOOP = "loop_slideshow" const val SLIDESHOW_DEFAULT_INTERVAL = 5 const val SLIDESHOW_SLIDE_DURATION = 500L const val SLIDESHOW_FADE_DURATION = 1500L const val SLIDESHOW_START_ON_ENTER = "slideshow_start_on_enter" // slideshow animations const val SLIDESHOW_ANIMATION_NONE = 0 const val SLIDESHOW_ANIMATION_SLIDE = 1 const val SLIDESHOW_ANIMATION_FADE = 2 const val RECYCLE_BIN = "recycle_bin" const val SHOW_FAVORITES = "show_favorites" const val SHOW_RECYCLE_BIN = "show_recycle_bin" const val SHOW_NEXT_ITEM = "show_next_item" const val SHOW_PREV_ITEM = "show_prev_item" const val GO_TO_NEXT_ITEM = "go_to_next_item" const val GO_TO_PREV_ITEM = "go_to_prev_item" const val MAX_COLUMN_COUNT = 20 const val SHOW_TEMP_HIDDEN_DURATION = 300000L const val CLICK_MAX_DURATION = 150 const val CLICK_MAX_DISTANCE = 100 const val MAX_CLOSE_DOWN_GESTURE_DURATION = 300 const val DRAG_THRESHOLD = 8 const val MONTH_MILLISECONDS = MONTH_SECONDS * 1000L const val MIN_SKIP_LENGTH = 2000 const val HIDE_SYSTEM_UI_DELAY = 500L const val MAX_PRINT_SIDE_SIZE = 4096 const val FAST_FORWARD_VIDEO_MS = 10000 const val DIRECTORY = "directory" const val MEDIUM = "medium" const val PATH = "path" const val GET_IMAGE_INTENT = "get_image_intent" const val GET_VIDEO_INTENT = "get_video_intent" const val GET_ANY_INTENT = "get_any_intent" const val SET_WALLPAPER_INTENT = "set_wallpaper_intent" const val IS_VIEW_INTENT = "is_view_intent" const val PICKED_PATHS = "picked_paths" const val SHOULD_INIT_FRAGMENT = "should_init_fragment" const val PORTRAIT_PATH = "portrait_path" const val SKIP_AUTHENTICATION = "skip_authentication" // rotations const val ROTATE_BY_SYSTEM_SETTING = 0 const val ROTATE_BY_DEVICE_ROTATION = 1 const val ROTATE_BY_ASPECT_RATIO = 2 // file loading priority const val PRIORITY_SPEED = 0 const val PRIORITY_COMPROMISE = 1 const val PRIORITY_VALIDITY = 2 // extended details values const val EXT_NAME = 1 const val EXT_PATH = 2 const val EXT_SIZE = 4 const val EXT_RESOLUTION = 8 const val EXT_LAST_MODIFIED = 16 const val EXT_DATE_TAKEN = 32 const val EXT_CAMERA_MODEL = 64 const val EXT_EXIF_PROPERTIES = 128 const val EXT_DURATION = 256 const val EXT_ARTIST = 512 const val EXT_ALBUM = 1024 const val EXT_GPS = 2048 // media types const val TYPE_IMAGES = 1 const val TYPE_VIDEOS = 2 const val TYPE_GIFS = 4 const val TYPE_RAWS = 8 const val TYPE_SVGS = 16 const val TYPE_PORTRAITS = 32 fun getDefaultFileFilter() = TYPE_IMAGES or TYPE_VIDEOS or TYPE_GIFS or TYPE_RAWS or TYPE_SVGS const val LOCATION_INTERNAL = 1 const val LOCATION_SD = 2 const val LOCATION_OTG = 3 const val GROUP_BY_NONE = 1 const val GROUP_BY_LAST_MODIFIED_DAILY = 2 const val GROUP_BY_DATE_TAKEN_DAILY = 4 const val GROUP_BY_FILE_TYPE = 8 const val GROUP_BY_EXTENSION = 16 const val GROUP_BY_FOLDER = 32 const val GROUP_BY_LAST_MODIFIED_MONTHLY = 64 const val GROUP_BY_DATE_TAKEN_MONTHLY = 128 const val GROUP_DESCENDING = 1024 // bottom actions const val BOTTOM_ACTION_TOGGLE_FAVORITE = 1 const val BOTTOM_ACTION_EDIT = 2 const val BOTTOM_ACTION_SHARE = 4 const val BOTTOM_ACTION_DELETE = 8 const val BOTTOM_ACTION_ROTATE = 16 const val BOTTOM_ACTION_PROPERTIES = 32 const val BOTTOM_ACTION_CHANGE_ORIENTATION = 64 const val BOTTOM_ACTION_SLIDESHOW = 128 const val BOTTOM_ACTION_SHOW_ON_MAP = 256 const val BOTTOM_ACTION_TOGGLE_VISIBILITY = 512 const val BOTTOM_ACTION_RENAME = 1024 const val BOTTOM_ACTION_SET_AS = 2048 const val BOTTOM_ACTION_COPY = 4096 const val BOTTOM_ACTION_MOVE = 8192 const val BOTTOM_ACTION_RESIZE = 16384 const val DEFAULT_BOTTOM_ACTIONS = BOTTOM_ACTION_TOGGLE_FAVORITE or BOTTOM_ACTION_EDIT or BOTTOM_ACTION_SHARE or BOTTOM_ACTION_DELETE // aspect ratios used at the editor for cropping const val ASPECT_RATIO_FREE = 0 const val ASPECT_RATIO_ONE_ONE = 1 const val ASPECT_RATIO_FOUR_THREE = 2 const val ASPECT_RATIO_SIXTEEN_NINE = 3 const val ASPECT_RATIO_OTHER = 4 // some constants related to zooming videos const val MIN_VIDEO_ZOOM_SCALE = 1f const val MAX_VIDEO_ZOOM_SCALE = 5f const val ZOOM_MODE_NONE = 0 const val ZOOM_MODE_DRAG = 1 const val ZOOM_MODE_ZOOM = 2 // constants related to image quality const val LOW_TILE_DPI = 160 const val NORMAL_TILE_DPI = 220 const val WEIRD_TILE_DPI = 240 const val HIGH_TILE_DPI = 280 const val ROUNDED_CORNERS_NONE = 1 const val ROUNDED_CORNERS_SMALL = 2 const val ROUNDED_CORNERS_BIG = 3 const val FOLDER_MEDIA_CNT_LINE = 1 const val FOLDER_MEDIA_CNT_BRACKETS = 2 const val FOLDER_MEDIA_CNT_NONE = 3 const val FOLDER_STYLE_SQUARE = 1 const val FOLDER_STYLE_ROUNDED_CORNERS = 2
gpl-3.0
8a523d9aae544bd190d2182a59a57052
40.728033
133
0.770581
3.29795
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/util/android/_Anim.kt
1
2037
package net.ketc.numeri.util.android import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation /** * @param durationMillis Duration in milliseconds */ fun View.fadeIn(durationMillis: Long = 300L): AnimationCallback { val anim = AlphaAnimation(0f, 1f) anim.duration = durationMillis return AnimationCallback(anim, this) } /** * @param durationMillis Duration in milliseconds */ fun View.fadeOut(durationMillis: Long = 300L): AnimationCallback { val anim = AlphaAnimation(1f, 0f) anim.duration = durationMillis return AnimationCallback(anim, this) } class AnimationCallback(private val animation: Animation, private val view: View) { private var repeat: View.(Animation) -> Unit = {} private var end: View.(Animation) -> Unit = {} private var start: View.(Animation) -> Unit = {} private var then: (View.() -> Unit)? = null init { animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation) { [email protected](view, animation) } override fun onAnimationEnd(animation: Animation) { [email protected](view, animation) [email protected]?.invoke(view) } override fun onAnimationStart(animation: Animation) { [email protected](view, animation) } }) } infix fun repeat(func: View.(Animation) -> Unit): AnimationCallback { repeat = func return this } infix fun start(func: View.(Animation) -> Unit): AnimationCallback { start = func return this } infix fun end(func: View.(Animation) -> Unit): AnimationCallback { end = func return this } fun execute() { view.startAnimation(animation) } infix fun then(func: View.() -> Unit): Unit { then = func execute() } }
mit
e75fe7d2602d653825849fcc41d0a0ed
27.305556
83
0.640648
4.608597
false
false
false
false
grote/BlitzMail
src/de/grobox/blitzmail/preferences/MailPreferences.kt
1
3621
package de.grobox.blitzmail.preferences import android.content.Context import android.preference.PreferenceManager import android.util.Log import de.grobox.blitzmail.crypto.Crypto import de.grobox.blitzmail.R import java.net.InetAddress import java.net.UnknownHostException import java.util.* fun getProperties(c: Context): Properties { val pref = PreferenceManager.getDefaultSharedPreferences(c) val crypto = Crypto(c) val recipients = pref.getString("pref_recipient", null) val sender = pref.getString("pref_sender", null) val server = pref.getString("pref_smtp_server", null) val port = pref.getString("pref_smtp_port", null) val encryption = pref.getString("pref_smtp_encryption", null) val auth = pref.getBoolean("pref_smtp_auth", false) val user = pref.getString("pref_smtp_user", null) var password = pref.getString("pref_smtp_pass", null) if (recipients == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_recipient)) if (sender == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_sender)) if (server == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_smtp_server)) if (port == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_smtp_port)) if (auth) { if (user == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_smtp_user)) if (password == null) throw RuntimeException(c.getString(R.string.error_option_not_set) + " " + c.getString(R.string.pref_smtp_pass)) // Decrypt password password = crypto.decrypt(password) } val props = Properties() props.setProperty("mail.transport.protocol", "smtp") props.setProperty("mail.host", server) val appName = c.getString(R.string.app_name) val from = (pref.getString("pref_sender_name", appName) ?: appName) + " <" + sender + ">" props.setProperty("mail.user", from) props.setProperty("mail.from", from) props.setProperty("mail.smtp.auth", auth.toString()) props.setProperty("mail.smtp.port", port) props.setProperty("mail.smtp.recipients", recipients) props.setProperty("mail.smtp.quitwait", "false") if (auth) { // set username and password props.setProperty("mail.smtp.user", user) props.setProperty("mail.smtp.pass", password) } else { // set some hostname for proper HELO greeting props.setProperty("mail.smtp.localhost", "android.com") } // set encryption properties if (encryption == "ssl") { Log.i("SendActivity", "Using SSL Encryption...") props.setProperty("mail.smtp.ssl.enable", "true") props.setProperty("mail.smtp.ssl.checkserveridentity", "true") } else if (encryption == "tls") { Log.i("SendActivity", "Using STARTTLS Encryption...") props.setProperty("mail.smtp.starttls.enable", "true") props.setProperty("mail.smtp.ssl.checkserveridentity", "true") } // try to get proper hostname and set fake one if failed if (props.getProperty("mail.smtp.localhost", "") == "android.com") { var hostname = "" try { hostname = InetAddress.getLocalHost().hostName } catch (e: UnknownHostException) { // do nothing } if (hostname != "localhost") { props.setProperty("mail.smtp.localhost", hostname) } } return props }
agpl-3.0
d7386a05ef5331615a3e5e031db405a4
41.104651
141
0.6686
3.81962
false
false
false
false
Litote/kmongo
kmongo-property/src/test/kotlin/org/litote/kmongo/FiltersTest.kt
1
2721
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo import com.mongodb.client.model.Filters import org.junit.Test import kotlin.test.assertEquals /** * */ class FiltersTest { class T(val s: List<String>, val string: String, val zz:List<Z>) class Z(val a: String) @Test fun `all works with Iterable sub interface`() { //check this compile T::s all setOf("test") } @Test fun `eq works with null`() { //check this compile T::s eq null } @Test fun `in works with a collection property`() { //check this compile T::s `in` setOf("test") } @Test fun `nin works with a collection property`() { //check this compile T::s nin setOf("test") } @Test fun `regex works with a string property`() { val r1 = T::string regex "test" val r2 = T::string regex "test".toRegex().toPattern() val r3 = T::string regex "test".toRegex() val r4 = T::string.regex("test", "") assertEquals(r1.document, Filters.regex("string", "test").document) assertEquals(r1.document, r2.document) assertEquals(r1.document, r3.document) assertEquals(r1.document, r4.document) } @Test fun `regex works with a collection property`() { val r1 = T::s regex "test" val r2 = T::s regex "test".toRegex().toPattern() val r3 = T::s regex "test".toRegex() val r4 = T::s.regex("test", "") assertEquals(r1.document, Filters.regex("s", "test").document) assertEquals(r1.document, r2.document) assertEquals(r1.document, r3.document) assertEquals(r1.document, r4.document) } @Test fun `positional projection`() { val p = T::zz.pos(0) / Z::a assertEquals("zz.0.a", p.path()) } data class Map1(val p1: Map<String, Map2>) data class Map2(val p2: Map<String, String>) @Test fun `multiple key projection`() { val m1 = Map1::p1.keyProjection("a") val m2 = Map2::p2.keyProjection("b") val doc = m1 / m2 assertEquals("p1.a.p2.b", doc.path()) } }
apache-2.0
903d119b6f69f282498ab92d960b12d5
25.950495
75
0.612642
3.647453
false
true
false
false
ibinti/intellij-community
python/educational-core/src/com/jetbrains/edu/learning/ui/StudyHint.kt
6
3355
package com.jetbrains.edu.learning.ui import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.project.Project import com.jetbrains.edu.coursecreator.actions.CCEditHintAction import com.jetbrains.edu.learning.StudySettings import com.jetbrains.edu.learning.StudyTaskManager import com.jetbrains.edu.learning.StudyUtils import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder import java.util.* open class StudyHint(private val myPlaceholder: AnswerPlaceholder?, private val myProject: Project) { companion object { private val OUR_WARNING_MESSAGE = "Put the caret in the answer placeholder to get hint" private val HINTS_NOT_AVAILABLE = "There is no hint for this answer placeholder" } val studyToolWindow: StudyToolWindow protected var myShownHintNumber = 0 protected var isEditingMode = false init { if (StudyUtils.hasJavaFx() && StudySettings.getInstance().shouldUseJavaFx()) { studyToolWindow = StudyJavaFxToolWindow() } else { studyToolWindow = StudySwingToolWindow() } studyToolWindow.init(myProject, false) if (myPlaceholder == null) { studyToolWindow.setText(OUR_WARNING_MESSAGE) studyToolWindow.setActionToolbar(DefaultActionGroup()) } val course = StudyTaskManager.getInstance(myProject).course if (course != null) { val group = DefaultActionGroup() val hints = myPlaceholder?.hints if (hints != null) { group.addAll(Arrays.asList(GoBackward(), GoForward(), CCEditHintAction(myPlaceholder))) studyToolWindow.setActionToolbar(group) setHintText(hints) } } } protected fun setHintText(hints: List<String>) { if (!hints.isEmpty()) { studyToolWindow.setText(hints[myShownHintNumber]) } else { myShownHintNumber = -1 studyToolWindow.setText(HINTS_NOT_AVAILABLE) } } inner class GoForward : AnAction("Next Hint", "Next Hint", AllIcons.Actions.Forward) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[++myShownHintNumber]) } override fun update(e: AnActionEvent) { val presentation = e.presentation updateVisibility(myPlaceholder, presentation) presentation.isEnabled = !isEditingMode && myPlaceholder != null && myShownHintNumber + 1 < myPlaceholder.hints.size } } private fun updateVisibility(myPlaceholder: AnswerPlaceholder?, presentation: Presentation) { val hasMultipleHints = myPlaceholder != null && myPlaceholder.hints.size > 1 presentation.isVisible = !StudyUtils.isStudentProject(myProject) || hasMultipleHints } inner class GoBackward : AnAction("Previous Hint", "Previous Hint", AllIcons.Actions.Back) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[--myShownHintNumber]) } override fun update(e: AnActionEvent) { val presentation = e.presentation updateVisibility(myPlaceholder, presentation) presentation.isEnabled = !isEditingMode && myShownHintNumber - 1 >= 0 } } }
apache-2.0
70c26647520eccee3c7b4c96e6fa284a
33.947917
122
0.728763
4.779202
false
false
false
false
ilya-g/kotlinx.collections.immutable
core/commonMain/src/implementations/persistentOrderedMap/PersistentOrderedMapBuilderContentIterators.kt
1
3835
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.collections.immutable.implementations.persistentOrderedMap import kotlinx.collections.immutable.implementations.immutableMap.MapEntry import kotlinx.collections.immutable.internal.EndOfChain internal open class PersistentOrderedMapBuilderLinksIterator<K, V>( private var nextKey: Any?, internal val builder: PersistentOrderedMapBuilder<K, V> ) : MutableIterator<LinkedValue<V>> { internal var lastIteratedKey: Any? = EndOfChain private var nextWasInvoked = false private var expectedModCount = builder.hashMapBuilder.modCount internal var index = 0 override fun hasNext(): Boolean { return index < builder.size } override fun next(): LinkedValue<V> { checkForComodification() checkHasNext() lastIteratedKey = nextKey nextWasInvoked = true index++ val result = builder.hashMapBuilder[nextKey]!! nextKey = result.next return result } override fun remove() { checkNextWasInvoked() builder.remove(lastIteratedKey) lastIteratedKey = null nextWasInvoked = false expectedModCount = builder.hashMapBuilder.modCount index-- } private fun checkHasNext() { if (!hasNext()) throw NoSuchElementException() } private fun checkNextWasInvoked() { if (!nextWasInvoked) throw IllegalStateException() } private fun checkForComodification() { if (builder.hashMapBuilder.modCount != expectedModCount) throw ConcurrentModificationException() } } internal class PersistentOrderedMapBuilderEntriesIterator<K, V>(map: PersistentOrderedMapBuilder<K, V>): MutableIterator<MutableMap.MutableEntry<K, V>> { private val internal = PersistentOrderedMapBuilderLinksIterator(map.firstKey, map) override fun hasNext(): Boolean { return internal.hasNext() } override fun next(): MutableMap.MutableEntry<K, V> { val links = internal.next() @Suppress("UNCHECKED_CAST") return MutableMapEntry(internal.builder.hashMapBuilder, internal.lastIteratedKey as K, links) } override fun remove() { internal.remove() } } private class MutableMapEntry<K, V>(private val mutableMap: MutableMap<K, LinkedValue<V>>, key: K, private var links: LinkedValue<V>) : MapEntry<K, V>(key, links.value), MutableMap.MutableEntry<K, V> { override val value: V get() = links.value override fun setValue(newValue: V): V { val result = links.value links = links.withValue(newValue) mutableMap[key] = links return result } } internal class PersistentOrderedMapBuilderKeysIterator<out K, out V>(map: PersistentOrderedMapBuilder<K, V>): MutableIterator<K> { private val internal = PersistentOrderedMapBuilderLinksIterator(map.firstKey, map) override fun hasNext(): Boolean { return internal.hasNext() } override fun next(): K { internal.next() @Suppress("UNCHECKED_CAST") return internal.lastIteratedKey as K } override fun remove() { internal.remove() } } internal class PersistentOrderedMapBuilderValuesIterator<out K, out V>(map: PersistentOrderedMapBuilder<K, V>): MutableIterator<V> { private val internal = PersistentOrderedMapBuilderLinksIterator(map.firstKey, map) override fun hasNext(): Boolean { return internal.hasNext() } override fun next(): V { return internal.next().value } override fun remove() { internal.remove() } }
apache-2.0
e97d67b5ad9c0bc8da0f4c745e742776
29.688
153
0.6691
4.752169
false
false
false
false
juanavelez/crabzilla
crabzilla-pg-client/src/main/java/io/github/crabzilla/pgc/PgcUowJournal.kt
1
4294
package io.github.crabzilla.pgc import io.github.crabzilla.EventBusChannels import io.github.crabzilla.framework.Entity import io.github.crabzilla.framework.EntityJsonAware import io.github.crabzilla.framework.UnitOfWork import io.github.crabzilla.internal.UnitOfWorkJournal import io.vertx.core.Promise import io.vertx.core.Vertx import io.vertx.core.json.JsonObject import io.vertx.pgclient.PgPool import io.vertx.sqlclient.Tuple import org.slf4j.LoggerFactory class PgcUowJournal<E: Entity>(private val vertx: Vertx, private val pgPool: PgPool, private val jsonFunctions: EntityJsonAware<E>) : UnitOfWorkJournal<E> { companion object { internal val log = LoggerFactory.getLogger(PgcUowJournal::class.java) const val SQL_SELECT_CURRENT_VERSION = "select max(version) as last_version " + "from units_of_work where ar_id = $1 and ar_name = $2 " const val SQL_APPEND_UOW = "insert into units_of_work " + "(uow_events, cmd_id, cmd_name, cmd_data, ar_name, ar_id, version) " + "values ($1, $2, $3, $4, $5, $6, $7) returning uow_id" } override fun append(unitOfWork: UnitOfWork): Promise<Long> { val promise = Promise.promise<Long>() pgPool.begin { res -> if (res.succeeded()) { val tx = res.result() val params1 = Tuple.of(unitOfWork.entityId, unitOfWork.entityName) tx.preparedQuery(SQL_SELECT_CURRENT_VERSION, params1) { event1 -> if (event1.succeeded()) { val currentVersion = event1.result().first()?.getInteger("last_version") ?: 0 if (currentVersion == unitOfWork.version - 1) { // if version is OK, then insert val cmdAsJsonObject = jsonFunctions.cmdToJson(unitOfWork.command) val eventsListAsJsonArray = jsonFunctions.toJsonArray(unitOfWork.events) val params2 = Tuple.of( eventsListAsJsonArray, unitOfWork.commandId, unitOfWork.commandName, cmdAsJsonObject, unitOfWork.entityName, unitOfWork.entityId, unitOfWork.version) tx.preparedQuery(SQL_APPEND_UOW, params2) { event2 -> if (event2.succeeded()) { val insertRows = event2.result().value() val uowId = insertRows.first().getLong(0) // Commit the transaction tx.commit { event3 -> if (event3.failed()) { log.error("Transaction failed", event3.cause()) promise.fail(event3.cause()) } else { log.trace("Transaction succeeded for $uowId") val message = JsonObject() .put("uowId", uowId) .put(UnitOfWork.JsonMetadata.ENTITY_NAME, unitOfWork.entityName) .put(UnitOfWork.JsonMetadata.ENTITY_ID, unitOfWork.entityId) .put(UnitOfWork.JsonMetadata.VERSION, unitOfWork.version) .put(UnitOfWork.JsonMetadata.EVENTS, eventsListAsJsonArray) if (log.isTraceEnabled) log.trace("will publish message $message") vertx.eventBus().publish(EventBusChannels.unitOfWorkChannel, message.encode()) if (log.isTraceEnabled) log.trace("publish success") promise.complete(uowId) } } } else { log.error("Transaction failed", event2.cause()) promise.fail(event2.cause()) } } } else { val error = "expected version is ${unitOfWork.version - 1} but current version is $currentVersion" log.error(error) promise.fail(error) } } else { log.error("when selecting current version") promise.fail(event1.cause()) } } } else { log.error("when starting transaction") promise.fail(res.cause()) } } return promise } }
apache-2.0
8e754761c0a4805273b70041b0608ff8
42.816327
112
0.561015
4.524763
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/module/ModuleImport.kt
1
1852
package com.github.prologdb.runtime.module import com.github.prologdb.runtime.ClauseIndicator import com.github.prologdb.runtime.util.OperatorDefinition import com.github.prologdb.runtime.util.OperatorType sealed class ModuleImport { abstract val moduleReference: ModuleReference data class Full(override val moduleReference: ModuleReference) : ModuleImport() data class Selective( override val moduleReference: ModuleReference, /** * The imported predicates. The key refers to the indicator of the predicate as exported * by the imported module. The value is the functor to be used in the code that imports * the module. E.g. `:- use_module(foo, [bar/1 as baz])` will result in the key being * `bar/1` and the value being `baz`. */ val predicates: Map<ClauseIndicator, String>, val operators: Set<OperatorImport>, ) : ModuleImport() data class Except( override val moduleReference: ModuleReference, val excludedPredicates: Set<ClauseIndicator>, val excludedOperators: Set<OperatorImport>, ) : ModuleImport() data class OperatorImport( /** If non-null: the precedence to import; if null: unbound, import operators with any precedence */ val precedence: Short?, /** If non-null: the type to import; if null: unbound, import operators of all types */ val type: OperatorType?, /** If non-null: the name to import; if null: unbound, import operators with any name */ val name: String?, ) { fun matches(definition: OperatorDefinition): Boolean { return precedence == null || precedence == definition.precedence && type == null || type == definition.type && name == null || name == definition.name } } }
mit
7b09b2b7274172c3071510432f9abf92
38.404255
108
0.662527
4.748718
false
false
false
false
googlearchive/background-tasks-samples
WorkManager/lib/src/main/java/com/example/background/workers/WaterColorFilterWorker.kt
1
1723
package com.example.background.workers import android.content.Context import android.graphics.Bitmap import android.renderscript.Allocation import android.renderscript.RenderScript import androidx.work.WorkerParameters import com.example.background.ScriptC_waterColorEffect class WaterColorFilterWorker(context: Context, parameters: WorkerParameters) : BaseFilterWorker(context, parameters) { override fun applyFilter(input: Bitmap): Bitmap { var rsContext: RenderScript? = null try { val output = Bitmap .createBitmap(input.width, input.height, input.config) rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG) val inAlloc = Allocation.createFromBitmap(rsContext, input) val outAlloc = Allocation.createTyped(rsContext, inAlloc.type) // The Renderscript function that generates the water color effect is defined in // `src/main/rs/waterColorEffect.rs`. The main idea, is to select a window of the image // and then find the most dominant pixel value. Then we set the r, g, b, channels of the // pixels to the one with the dominant pixel value. val oilFilterEffect = ScriptC_waterColorEffect(rsContext) oilFilterEffect._script = oilFilterEffect oilFilterEffect._width = input.width.toLong() oilFilterEffect._height = input.height.toLong() oilFilterEffect._in = inAlloc oilFilterEffect._out = outAlloc oilFilterEffect.invoke_filter() outAlloc.copyTo(output) return output } finally { rsContext?.finish() } } }
apache-2.0
8981941e61ea725451dc0fc43e34471a
44.368421
100
0.680209
4.694823
false
false
false
false
dslomov/intellij-community
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/TestGraphs.kt
80
2186
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.graph object TestGraphs { /* 1 | 2 | 3 | 4 */ val line = graph { 1(2) 2(3) 3(4) 4() } /* 1 |\ 2 | |/ 3 */ val smallMerge = graph { 1(2, 3) 2(3) 3() } /* 0 |\ 1 2 |\|\ 3 4 5 */ val downTree = graph { 0(1, 2) 1(3, 4) 2(4, 5) 3() 4() 5() } /* 0 1 2 \/\/ 3 4 \/ 5 */ val upTree = graph { 0(3) 1(3, 4) 2(4) 3(5) 4(5) 5() } /* 1 |\ 2 | | 3 4 | | 5 |/ 6 */ val simpleMerge = graph { 1(2, 3) 2(4) 3(5) 4(6) 5(6) 6() } /* 1 |\ 2 \ | 3 4 | \ | 5 6 7 |/ | 8 |/ 9 */ val plainMerge = graph { 1(2, 3) 2(4) 3(5, 6) 4(7) 5(8) 6(8) 7(9) 8(9) 9() } /* 1 |\ 2 \ | 3 4 | \ | 5 6 7 \/ | /\ |/ 8 9 | | / 10 */ val notPlainMerge = graph { 1(2, 3) 2(4) 3(5, 6) 4(7) 5(8) 6(9) 7(9) 8(10) 9(10) 10() } /* 1 | 2 |/| 3 4 | |\ 5 |6 |/ / 7 / |/ 8 */ val autoMerge = graph { 1(3) 2(3, 4) 3(5) 4(7, 6) 5(7) 6(8) 7(8) 8() } /* 0 |\ | 1 2 |\ | | 3 | 4 | |/ 5 6 /| |\/ / |7 / \ / 8 */ val twoInit = graph { 0(1, 2) 1(3, 4) 2(6) 3(5) 4(6) 5(7, 8) 6(7, 8) 7() 8() } /* 1 | 2 3 | | 4 5 / |/ 6 */ val twoBranches = graph { 1(3) 2(4) 3(5) 4(6) 5(6) 6() } }
apache-2.0
b70d8b54cd805dea10e184254ffa08ff
9.027523
75
0.396615
2.54482
false
false
false
false
MaibornWolff/codecharta
analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/subcommands/LogScanParserDialog.kt
1
1065
package de.maibornwolff.codecharta.importer.gitlogparser.subcommands import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptInput import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface class LogScanParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { print("You can generate this file with: git log --numstat --raw --topo-order --reverse -m > git.log") val gitLogFile = KInquirer.promptInput( message = "What is the git.log file that has to be parsed?", hint = "path/to/git.log" ) print("You can generate this file with: git ls-files > file-name-list.txt") val gitLsFile = KInquirer.promptInput( message = "What is the path to the file name list?", hint = "path/to/file-name-list.txt" ) return listOfNotNull( "--git-log=$gitLogFile", "--repo-files=$gitLsFile" ) } } }
bsd-3-clause
586f174c8cfa8add3ff0ee3d0f5790da
37.035714
113
0.634742
4.456067
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/persistence/jdbcx.kt
1
5868
package at.cpickl.gadsu.persistence import org.slf4j.LoggerFactory import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import javax.sql.DataSource interface Jdbcx { val jdbc: JdbcTemplate fun <E> query(sql: String, rowMapper: RowMapper<E>): MutableList<E> fun <E> query(sql: String, args: Array<out Any?>, rowMapper: RowMapper<E>): MutableList<E> fun <E> query2(sql: String, rowMapper: RowMapper<E>, vararg args: Any): MutableList<E> fun <E> queryMaybeSingle(rowMapper: RowMapper<E>, sql: String, args: Array<out Any?>): E? fun <E> querySingle(rowMapper: RowMapper<E>, sql: String, vararg args: Any?): E fun <E> queryForObject(sql: String, args: Array<Any>, mapper: RowMapper<E>): E fun update(sql: String, vararg args: Any?): Int fun updateSingle(sql: String, vararg args: Any?) fun deleteSingle(sql: String, vararg args: Any?) fun deleteTable(tableName: String) fun transactionSafe(function: () -> Unit) fun <T> transactionSafeAndReturn(function: () -> T): T fun count(table: String, args: Array<in Any> = emptyArray(), optionalWhereClause: String = ""): Int fun execute(sql: String) } class SpringJdbcx(private val dataSource: DataSource) : Jdbcx { private val log = LoggerFactory.getLogger(javaClass) override val jdbc = JdbcTemplate(dataSource) override fun <E> query(sql: String, rowMapper: RowMapper<E>): MutableList<E> { log.trace("query(sql='{}', rowMapper)", sql) return encapsulateException({ jdbc.query(sql, rowMapper) }) } override fun <E> query(sql: String, args: Array<out Any?>, rowMapper: RowMapper<E>): MutableList<E> { log.trace("query(sql='{}', args={}, rowMapper)", sql, args) return encapsulateException({ jdbc.query(sql, args, rowMapper) }) } override fun <E> query2(sql: String, rowMapper: RowMapper<E>, vararg args: Any): MutableList<E> { log.trace("query(sql='{}', args={}, rowMapper)", sql, args) return encapsulateException({ jdbc.query(sql, args, rowMapper) }) } override fun <E> queryMaybeSingle(rowMapper: RowMapper<E>, sql: String, args: Array<out Any?>): E? { return encapsulateException({ val result = jdbc.query(sql, args, rowMapper) when (result.size) { 0 -> null 1 -> result[0] else -> throw PersistenceException("Expected not more than one returned but was ${result.size},by sql code: '$sql'!", PersistenceErrorCode.EXPECT_QUERY_SINGLE_ONE) } }) } override fun <E> queryForObject(sql: String, args: Array<Any>, mapper: RowMapper<E>): E { return jdbc.queryForObject(sql, args, mapper) } override fun <E> querySingle(rowMapper: RowMapper<E>, sql: String, args: Array<out Any?>): E { log.trace("querySingle(rowMapper, sql='{}', args)", sql) val maybe = queryMaybeSingle(rowMapper, sql, args) ?: throw PersistenceException("Expected exactly one item to be returned but was 0, by sql code: '$sql'!", PersistenceErrorCode.EXPECT_QUERY_SINGLE_ONE) return maybe } override fun update(sql: String, vararg args: Any?): Int { log.trace("update(sql='{}', args={})", sql, args) return encapsulateException({ jdbc.update(sql, *args) }) } override fun updateSingle(sql: String, vararg args: Any?) { val affectedRows = jdbc.update(sql, *args) if (affectedRows != 1) { throw PersistenceException("Expected exactly one row to be updated, but was: $affectedRows!", PersistenceErrorCode.EXPECT_UPDATE_ONE) } } override fun deleteSingle(sql: String, vararg args: Any?) { log.trace("deleteSingle(sql='{}', args={})", sql, args) encapsulateException { val affectedRows = jdbc.update(sql, *args) if (affectedRows != 1) { throw PersistenceException("Expected exactly one row to be deleted, but was: $affectedRows! SQL: [[$sql]], args: [[$args]]", PersistenceErrorCode.EXPECT_DELETED_ONE) } } } override fun deleteTable(tableName: String) { execute("DELETE FROM $tableName") } override fun count(table: String, args: Array<in Any>, optionalWhereClause: String): Int = jdbc.queryForObject("SELECT COUNT(*) FROM $table $optionalWhereClause", args) { rs, _ -> rs.getInt(1) } override fun execute(sql: String) { log.trace("execute(sql='{}')", sql) encapsulateException { jdbc.execute(sql) } } // ... what about nested transactions? override fun transactionSafe(function: () -> Unit) { transactionSafeAndReturn { function() } } override fun <T> transactionSafeAndReturn(function: () -> T): T { log.trace("transactionSafeAndReturn(function)") val wasAutoCommit = dataSource.connection.autoCommit dataSource.connection.autoCommit = false try { var committed = false try { val result: T = function() dataSource.connection.commit() log.trace("Transaction committed successfully.") committed = true return result } finally { if (!committed) { log.warn("Rolling back transaction!") dataSource.connection.rollback() } } } finally { dataSource.connection.autoCommit = wasAutoCommit } } private fun <E> encapsulateException(body: () -> E): E { try { return body() } catch (e: Exception) { throw PersistenceException("SQL execution failed! See cause for more details.", PersistenceErrorCode.UNKNOWN, e) } } }
apache-2.0
3474fb5d1e4fbe66d7257e60e59df3ca
38.648649
179
0.620484
4.264535
false
false
false
false
intellij-rust/intellij-rust
src/main/kotlin/org/rust/cargo/project/model/impl/CargoSettingsFilesService.kt
1
5044
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model.impl import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import org.rust.cargo.CargoConstants import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.PackageOrigin import org.rust.ide.experiments.RsExperiments import org.rust.lang.RsFileType import org.rust.lang.core.macros.proc.ProcMacroApplicationService import org.rust.openapiext.isFeatureEnabled @Service class CargoSettingsFilesService(private val project: Project) { @Volatile private var settingsFilesCache: Map<String, SettingFileType>? = null fun collectSettingsFiles(useCache: Boolean): Map<String, SettingFileType> { return if (useCache) { settingsFilesCache ?: collectSettingsFiles() } else { collectSettingsFiles() } } private fun collectSettingsFiles(): Map<String, SettingFileType> { val result = mutableMapOf<String, SettingFileType>() for (cargoProject in project.cargoProjects.allProjects) { cargoProject.collectSettingsFiles(result) } settingsFilesCache = result return result } private fun CargoProject.collectSettingsFiles(out: MutableMap<String, SettingFileType>) { val rootPath = rootDir?.path if (rootPath != null) { out["$rootPath/${CargoConstants.MANIFEST_FILE}"] = SettingFileType.CONFIG out["$rootPath/${CargoConstants.LOCK_FILE}"] = SettingFileType.CONFIG out["$rootPath/${CargoConstants.TOOLCHAIN_FILE}"] = SettingFileType.CONFIG out["$rootPath/${CargoConstants.TOOLCHAIN_TOML_FILE}"] = SettingFileType.CONFIG out["$rootPath/.cargo/${CargoConstants.CONFIG_FILE}"] = SettingFileType.CONFIG out["$rootPath/.cargo/${CargoConstants.CONFIG_TOML_FILE}"] = SettingFileType.CONFIG } for (pkg in workspace?.packages.orEmpty().filter { it.origin == PackageOrigin.WORKSPACE }) { pkg.collectSettingsFiles(out) } } private fun CargoWorkspace.Package.collectSettingsFiles(out: MutableMap<String, SettingFileType>) { val root = contentRoot ?: return out["${root.path}/${CargoConstants.MANIFEST_FILE}"] = SettingFileType.CONFIG // Here we track only existing implicit target files. // It's enough because `com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectAware.getSettingsFiles` // will be called on new file creation by the platform, so we need to provide a list of all possible implicit target files here for (targetFileName in IMPLICIT_TARGET_FILES) { val path = root.findFileByRelativePath(targetFileName)?.path ?: continue out[path] = SettingFileType.IMPLICIT_TARGET } for (targetDirName in IMPLICIT_TARGET_DIRS) { val dir = root.findFileByRelativePath(targetDirName) ?: continue for (file in VfsUtil.collectChildrenRecursively(dir)) { if (file.fileType == RsFileType) { out[file.path] = SettingFileType.IMPLICIT_TARGET } } } val (buildScriptFile, settingType) = if (isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)) { // Ideally, we should add any child module of build script target as config files as well. // But it's a quite rare case, so let's implement it separately if it's really needed val buildScriptFile = targets.find { it.kind.isCustomBuild }?.crateRoot ?: root.findFileByRelativePath(CargoConstants.BUILD_FILE) buildScriptFile to SettingFileType.CONFIG } else { root.findFileByRelativePath(CargoConstants.BUILD_FILE) to SettingFileType.IMPLICIT_TARGET } if (buildScriptFile != null) { out[buildScriptFile.path] = settingType } if (ProcMacroApplicationService.isAnyEnabled()) { val procMacroLibCrateRoot = targets.find { it.kind.isProcMacro }?.crateRoot if (procMacroLibCrateRoot != null) { // Ideally, we should add any child module of proc macro lib target as config files as well. out[procMacroLibCrateRoot.path] = SettingFileType.CONFIG } } } companion object { fun getInstance(project: Project): CargoSettingsFilesService = project.service() private val IMPLICIT_TARGET_FILES = listOf( "src/main.rs", "src/lib.rs" ) private val IMPLICIT_TARGET_DIRS = listOf( "src/bin", "examples", "tests", "benches" ) } enum class SettingFileType { CONFIG, IMPLICIT_TARGET } }
mit
20bc8d468f74fc846838bb8fe0fa18d0
40.68595
141
0.676249
4.812977
false
true
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/fragment/AddToHomescreenDialogFragment.kt
1
5823
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.fragment import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.Button import android.widget.EditText import android.widget.ImageView import androidx.appcompat.app.AlertDialog import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.preference.PreferenceManager import mozilla.components.browser.icons.IconRequest import mozilla.components.service.glean.private.NoExtras import org.mozilla.focus.GleanMetrics.AddToHomeScreen import org.mozilla.focus.R import org.mozilla.focus.ext.components import org.mozilla.focus.shortcut.HomeScreen import org.mozilla.focus.shortcut.IconGenerator import org.mozilla.focus.telemetry.TelemetryWrapper /** * Fragment displaying a dialog where a user can change the title for a homescreen shortcut */ class AddToHomescreenDialogFragment : DialogFragment() { @Suppress("LongMethod") override fun onCreateDialog(bundle: Bundle?): AlertDialog { AddToHomeScreen.dialogDisplayed.record(NoExtras()) val url = requireArguments().getString(URL) val title = requireArguments().getString(TITLE) val blockingEnabled = requireArguments().getBoolean(BLOCKING_ENABLED) val requestDesktop = requireArguments().getBoolean(REQUEST_DESKTOP) val builder = AlertDialog.Builder(requireActivity(), R.style.DialogStyle) builder.setCancelable(true) val inflater = requireActivity().layoutInflater val dialogView = inflater.inflate(R.layout.dialog_add_to_homescreen2, null) builder.setView(dialogView) val iconView = dialogView.findViewById<ImageView>(R.id.homescreen_icon) requireContext().components.icons.loadIntoView( iconView, IconRequest(url.toString(), isPrivate = true), ) val blockIcon = dialogView.findViewById<ImageView>(R.id.homescreen_dialog_block_icon) blockIcon.setImageResource(R.drawable.mozac_ic_shield_disabled) val warning = dialogView.findViewById<ConstraintLayout>(R.id.homescreen_dialog_warning_layout) warning.isVisible = blockingEnabled val editableTitle = dialogView.findViewById<EditText>(R.id.edit_title) if (!TextUtils.isEmpty(title)) { editableTitle.setText(title) } setButtons(dialogView, editableTitle, url, blockingEnabled, requestDesktop, title) return builder.create() } @Suppress("LongParameterList") private fun setButtons( parentView: View, editableTitle: EditText, iconUrl: String?, blockingEnabled: Boolean, requestDesktop: Boolean, initialTitle: String?, ) { val addToHomescreenDialogCancelButton = parentView.findViewById<Button>(R.id.addtohomescreen_dialog_cancel) val addToHomescreenDialogConfirmButton = parentView.findViewById<Button>(R.id.addtohomescreen_dialog_add) addToHomescreenDialogCancelButton.setOnClickListener { AddToHomeScreen.cancelButtonTapped.record(NoExtras()) TelemetryWrapper.cancelAddToHomescreenShortcutEvent() dismiss() } addToHomescreenDialogConfirmButton.setOnClickListener { HomeScreen.installShortCut( context, IconGenerator.generateLauncherIcon(requireContext(), iconUrl), iconUrl, editableTitle.text.toString().trim { it <= ' ' }, blockingEnabled, requestDesktop, ) val hasEditedTitle = initialTitle != editableTitle.text.toString().trim { it <= ' ' } AddToHomeScreen.addButtonTapped.record( AddToHomeScreen.AddButtonTappedExtra( hasEditedTitle = hasEditedTitle, ), ) TelemetryWrapper.addToHomescreenShortcutEvent() PreferenceManager.getDefaultSharedPreferences(requireContext()).edit() .putBoolean( requireContext().getString(R.string.has_added_to_home_screen), true, ).apply() dismiss() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) return super.onCreateView(inflater, container, savedInstanceState) } companion object { const val FRAGMENT_TAG = "add-to-homescreen-prompt-dialog" private const val URL = "url" private const val TITLE = "title" private const val BLOCKING_ENABLED = "blocking_enabled" private const val REQUEST_DESKTOP = "request_desktop" fun newInstance( url: String, title: String, blockingEnabled: Boolean, requestDesktop: Boolean, ): AddToHomescreenDialogFragment { val frag = AddToHomescreenDialogFragment() val args = Bundle() args.putString(URL, url) args.putString(TITLE, title) args.putBoolean(BLOCKING_ENABLED, blockingEnabled) args.putBoolean(REQUEST_DESKTOP, requestDesktop) frag.arguments = args return frag } } }
mpl-2.0
df73d717b9621f1c061b93f4c170f6c8
37.562914
116
0.679547
4.943124
false
false
false
false
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/repo/BookRepository.kt
1
2231
package de.ph1b.audiobook.data.repo import de.ph1b.audiobook.data.Book import de.ph1b.audiobook.data.BookContent import de.ph1b.audiobook.data.Chapter import de.ph1b.audiobook.data.repo.internals.BookStorage import de.ph1b.audiobook.data.repo.internals.MemoryRepo import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import timber.log.Timber import java.io.File import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @Singleton class BookRepository @Inject constructor( private val storage: BookStorage ) { private val memory = MemoryRepo( runBlocking { storage.books() } ) fun flow(): Flow<List<Book>> { return memory.flow.map { books -> books.filter { it.content.settings.active } } } fun flow(bookId: UUID): Flow<Book?> { return memory.flow.map { books -> books.find { it.id == bookId } } } fun bookById(id: UUID): Book? = memory.allBooks().find { it.id == id } fun allBooks(): List<Book> = memory.allBooks() fun activeBooks(): List<Book> = memory.allBooks().filterActive(true) suspend fun addBook(book: Book) { Timber.v("addBook=${book.name}") require(book.content.settings.active) { "Book $book must be active" } memory.addOrUpdate(book) storage.addOrUpdate(book) } suspend fun updateBookContent(content: BookContent): Book? { val updated = memory.updateBookContent(content) storage.updateBookContent(content) return updated } suspend fun updateBookName(id: UUID, name: String) { memory.updateBookName(id, name) storage.updateBookName(id, name) } suspend fun setBookActive(bookId: UUID, active: Boolean) { Timber.d("setBookActive(bookId=$bookId, active=$active)") memory.setBookActive(bookId, active) storage.setBookActive(bookId, active) } fun chapterByFile(file: File): Chapter? { memory.allBooks().forEach { book -> val chapter = book.content.chapters.find { it.file == file } if (chapter != null) { return chapter } } return null } } private fun List<Book>.filterActive(active: Boolean): List<Book> { return filter { it.content.settings.active == active } }
lgpl-3.0
9226626976dee2629bdb5416b2012f1c
25.559524
72
0.702824
3.610032
false
false
false
false
robinverduijn/gradle
buildSrc/subprojects/configuration/src/main/kotlin/org/gradle/gradlebuild/ProjectGroups.kt
1
2752
package org.gradle.gradlebuild import org.gradle.api.Project object ProjectGroups { val excludedFromVulnerabilityCheck = setOf( ":buildScanPerformance", ":distributions", ":docs", ":integTest", ":internalAndroidPerformanceTesting", ":internalIntegTesting", ":internalPerformanceTesting", ":internalTesting", ":performance", ":runtimeApiInfo", ":smokeTest", ":soak") // TODO Why is smoke test not on that list private val Project.internalProjects get() = rootProject.subprojects.filter { it.name.startsWith("internal") || it.name in internalProjectNames || it.name in kotlinJsProjectNames }.toSet() private val internalProjectNames = setOf( "integTest", "distributions", "performance", "buildScanPerformance", "kotlinCompilerEmbeddable", "kotlinDslTestFixtures", "kotlinDslIntegTests" ) private val kotlinJsProjectNames = setOf( "instantExecutionReport" ) val Project.kotlinJsProjects get() = kotlinJsProjectNames.map { project(":$it") } val Project.javaProjects get() = rootProject.subprojects - kotlinJsProjects - listOf(project(":distributionsDependencies")) val Project.publicJavaProjects get() = javaProjects - internalProjects val Project.pluginProjects get() = setOf("antlr", "plugins", "codeQuality", "wrapper", "maven", "ide", "scala", "signing", "ear", "javascript", "diagnostics", "reporting", "publish", "ivy", "jacoco", "buildInit", "platformBase", "platformJvm", "languageJvm", "languageJava", "languageGroovy", "languageScala", "platformNative", "platformPlay", "idePlay", "languageNative", "toolingNative", "ideNative", "testingBase", "testingNative", "testingJvm", "testingJunitPlatform", "pluginDevelopment", "pluginUse", "resourcesHttp", "resourcesSftp", "resourcesS3", "resourcesGcs", "compositeBuilds", "buildCacheHttp").map { rootProject.project(it) }.toSet() val Project.implementationPluginProjects get() = setOf( rootProject.project("buildProfile"), rootProject.project("toolingApiBuilders"), rootProject.project("kotlinDslProviderPlugins"), rootProject.project("kotlinDslToolingBuilders"), rootProject.project("instantExecution") ) val Project.publicProjects get() = pluginProjects + implementationPluginProjects + publicJavaProjects + rootProject.project(":kotlinDsl") - setOf(":smokeTest", ":soak").map { rootProject.project(it) } }
apache-2.0
46aff8319b8eed199bab9aaf89fd20e8
36.189189
153
0.635901
4.84507
false
true
false
false
ReactiveCircus/FlowBinding
flowbinding-viewpager2/src/androidTest/java/reactivecircus/flowbinding/viewpager2/ViewPager2PageScrollStateChangedFlowTest.kt
1
2342
package reactivecircus.flowbinding.viewpager2 import androidx.test.filters.LargeTest import androidx.viewpager2.widget.ViewPager2 import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.blueprint.testing.action.swipeLeftOnView import reactivecircus.blueprint.testing.action.swipeRightOnView import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith import reactivecircus.flowbinding.viewpager2.fixtures.ViewPager2Fragment import reactivecircus.flowbinding.viewpager2.test.R @LargeTest class ViewPager2PageScrollStateChangedFlowTest { @Test fun pageScrollStateChanges_swipe() { launchTest<ViewPager2Fragment> { val recorder = FlowRecorder<Int>(testScope) getViewById<ViewPager2>(R.id.viewPager).pageScrollStateChanges().recordWith(recorder) recorder.assertNoMoreValues() swipeLeftOnView(R.id.viewPager) assertThat(recorder.takeValue()) .isEqualTo(ViewPager2.SCROLL_STATE_DRAGGING) assertThat(recorder.takeValue()) .isEqualTo(ViewPager2.SCROLL_STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(ViewPager2.SCROLL_STATE_IDLE) recorder.assertNoMoreValues() cancelTestScope() swipeRightOnView(R.id.viewPager) recorder.assertNoMoreValues() } } @Test fun pageScrollStateChanges_programmatic() { launchTest<ViewPager2Fragment> { val recorder = FlowRecorder<Int>(testScope) val viewPager = getViewById<ViewPager2>(R.id.viewPager) viewPager.pageScrollStateChanges().recordWith(recorder) recorder.assertNoMoreValues() viewPager.currentItem = 1 // SCROLL_STATE_DRAGGING state is not emitted for programmatic page change assertThat(recorder.takeValue()) .isEqualTo(ViewPager2.SCROLL_STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(ViewPager2.SCROLL_STATE_IDLE) recorder.assertNoMoreValues() cancelTestScope() viewPager.currentItem = 0 recorder.assertNoMoreValues() } } }
apache-2.0
5dbcca13941b3c8f2e109e01df0d97b0
35.030769
97
0.69684
5.421296
false
true
false
false
ze-pequeno/okhttp
okhttp/src/jvmTest/java/okhttp3/internal/http2/MockHttp2Peer.kt
3
8768
/* * Copyright (C) 2011 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 okhttp3.internal.http2 import java.io.Closeable import java.io.IOException import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import java.util.concurrent.BlockingQueue import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.logging.Logger import okhttp3.internal.closeQuietly import okhttp3.internal.threadFactory import okio.Buffer import okio.BufferedSource import okio.ByteString import okio.buffer import okio.source /** Replays prerecorded outgoing frames and records incoming frames. */ class MockHttp2Peer : Closeable { private var frameCount = 0 private var client = false private val bytesOut = Buffer() private var writer = Http2Writer(bytesOut, client) private val outFrames: MutableList<OutFrame> = ArrayList() private val inFrames: BlockingQueue<InFrame> = LinkedBlockingQueue() private var port = 0 private val executor = Executors.newSingleThreadExecutor(threadFactory("MockHttp2Peer", false)) private var serverSocket: ServerSocket? = null private var socket: Socket? = null fun setClient(client: Boolean) { if (this.client == client) return this.client = client writer = Http2Writer(bytesOut, client) } fun acceptFrame() { frameCount++ } /** Maximum length of an outbound data frame. */ fun maxOutboundDataLength(): Int = writer.maxDataLength() /** Count of frames sent or received. */ fun frameCount(): Int = frameCount fun sendFrame(): Http2Writer { outFrames.add(OutFrame(frameCount++, bytesOut.size, false)) return writer } /** * Shortens the last frame from its original length to `length`. This will cause the peer to * close the socket as soon as this frame has been written; otherwise the peer stays open until * explicitly closed. */ fun truncateLastFrame(length: Int): Http2Writer { val lastFrame = outFrames.removeAt(outFrames.size - 1) require(length < bytesOut.size - lastFrame.start) // Move everything from bytesOut into a new buffer. val fullBuffer = Buffer() bytesOut.read(fullBuffer, bytesOut.size) // Copy back all but what we're truncating. fullBuffer.read(bytesOut, lastFrame.start + length) outFrames.add(OutFrame(lastFrame.sequence, lastFrame.start, true)) return writer } fun takeFrame(): InFrame = inFrames.take() fun play() { check(serverSocket == null) serverSocket = ServerSocket() serverSocket!!.reuseAddress = false serverSocket!!.bind(InetSocketAddress("localhost", 0), 1) port = serverSocket!!.localPort executor.execute { try { readAndWriteFrames() } catch (e: IOException) { [email protected]() logger.info("${this@MockHttp2Peer} done: ${e.message}") } } } private fun readAndWriteFrames() { check(socket == null) val socket = serverSocket!!.accept()!! this.socket = socket // Bail out now if this instance was closed while waiting for the socket to accept. synchronized(this) { if (executor.isShutdown) { socket.close() return } } val outputStream = socket.getOutputStream() val inputStream = socket.getInputStream() val reader = Http2Reader(inputStream.source().buffer(), client) val outFramesIterator: Iterator<OutFrame> = outFrames.iterator() val outBytes = bytesOut.readByteArray() var nextOutFrame: OutFrame? = null for (i in 0 until frameCount) { if (nextOutFrame == null && outFramesIterator.hasNext()) { nextOutFrame = outFramesIterator.next() } if (nextOutFrame != null && nextOutFrame.sequence == i) { val start = nextOutFrame.start var truncated: Boolean var end: Long if (outFramesIterator.hasNext()) { nextOutFrame = outFramesIterator.next() end = nextOutFrame.start truncated = false } else { end = outBytes.size.toLong() truncated = nextOutFrame.truncated } // Write a frame. val length = (end - start).toInt() outputStream.write(outBytes, start.toInt(), length) // If the last frame was truncated, immediately close the connection. if (truncated) { socket.close() } } else { // read a frame val inFrame = InFrame(i, reader) reader.nextFrame(false, inFrame) inFrames.add(inFrame) } } } fun openSocket(): Socket = Socket("localhost", port) @Synchronized override fun close() { executor.shutdown() socket?.closeQuietly() serverSocket?.closeQuietly() } override fun toString(): String = "MockHttp2Peer[$port]" private class OutFrame( val sequence: Int, val start: Long, val truncated: Boolean ) class InFrame(val sequence: Int, val reader: Http2Reader) : Http2Reader.Handler { @JvmField var type = -1 var clearPrevious = false @JvmField var outFinished = false @JvmField var inFinished = false @JvmField var streamId = 0 @JvmField var associatedStreamId = 0 @JvmField var errorCode: ErrorCode? = null @JvmField var windowSizeIncrement: Long = 0 @JvmField var headerBlock: List<Header>? = null @JvmField var data: ByteArray? = null @JvmField var settings: Settings? = null @JvmField var ack = false @JvmField var payload1 = 0 @JvmField var payload2 = 0 override fun settings(clearPrevious: Boolean, settings: Settings) { check(type == -1) this.type = Http2.TYPE_SETTINGS this.clearPrevious = clearPrevious this.settings = settings } override fun ackSettings() { check(type == -1) this.type = Http2.TYPE_SETTINGS this.ack = true } override fun headers( inFinished: Boolean, streamId: Int, associatedStreamId: Int, headerBlock: List<Header> ) { check(type == -1) this.type = Http2.TYPE_HEADERS this.inFinished = inFinished this.streamId = streamId this.associatedStreamId = associatedStreamId this.headerBlock = headerBlock } override fun data( inFinished: Boolean, streamId: Int, source: BufferedSource, length: Int ) { check(type == -1) this.type = Http2.TYPE_DATA this.inFinished = inFinished this.streamId = streamId this.data = source.readByteString(length.toLong()).toByteArray() } override fun rstStream(streamId: Int, errorCode: ErrorCode) { check(type == -1) this.type = Http2.TYPE_RST_STREAM this.streamId = streamId this.errorCode = errorCode } override fun ping(ack: Boolean, payload1: Int, payload2: Int) { check(type == -1) type = Http2.TYPE_PING this.ack = ack this.payload1 = payload1 this.payload2 = payload2 } override fun goAway(lastGoodStreamId: Int, errorCode: ErrorCode, debugData: ByteString) { check(type == -1) this.type = Http2.TYPE_GOAWAY this.streamId = lastGoodStreamId this.errorCode = errorCode this.data = debugData.toByteArray() } override fun windowUpdate(streamId: Int, windowSizeIncrement: Long) { check(type == -1) this.type = Http2.TYPE_WINDOW_UPDATE this.streamId = streamId this.windowSizeIncrement = windowSizeIncrement } override fun priority( streamId: Int, streamDependency: Int, weight: Int, exclusive: Boolean ) { throw UnsupportedOperationException() } override fun pushPromise(streamId: Int, associatedStreamId: Int, headerBlock: List<Header>) { this.type = Http2.TYPE_PUSH_PROMISE this.streamId = streamId this.associatedStreamId = associatedStreamId this.headerBlock = headerBlock } override fun alternateService( streamId: Int, origin: String, protocol: ByteString, host: String, port: Int, maxAge: Long ) { throw UnsupportedOperationException() } } companion object { private val logger = Logger.getLogger(MockHttp2Peer::class.java.name) } }
apache-2.0
a0984028db155c50ca78dd6fb75bb446
29.444444
97
0.673244
4.266667
false
false
false
false
7hens/KDroid
sample/src/main/java/cn/thens/kdroid/sample/nature/base/Stage.kt
1
1017
package cn.thens.kdroid.sample.nature.base import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.View import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit open class Stage(context: Context, attrs: AttributeSet? = null) : View(context, attrs) { private var isStarted = false val children = ArrayList<Sprite>() init { Observable.interval(PERIOD, TimeUnit.MILLISECONDS, Schedulers.io()) .filter { isStarted } .observeOn(AndroidSchedulers.mainThread()) .doOnNext { invalidate() } .subscribe() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) children.forEach { it.onDraw(canvas) } isStarted = true } companion object { const val PERIOD = 40L const val SPEED_FACTOR = PERIOD / 1000F } }
apache-2.0
9d10958f42920cc11a96925022599cfb
28.941176
88
0.678466
4.560538
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/extension/cap/handler/CapNakHandler.kt
1
1676
package chat.willow.warren.extension.cap.handler import chat.willow.kale.IMetadataStore import chat.willow.kale.KaleHandler import chat.willow.kale.irc.message.extension.cap.CapMessage import chat.willow.warren.IMessageSink import chat.willow.warren.extension.cap.CapLifecycle import chat.willow.warren.extension.cap.CapState import chat.willow.warren.extension.cap.ICapManager import chat.willow.warren.extension.sasl.SaslState import chat.willow.warren.helper.loggerFor class CapNakHandler(val capState: CapState, val saslState: SaslState, val sink: IMessageSink, val capManager: ICapManager) : KaleHandler<CapMessage.Nak.Message>(CapMessage.Nak.Message.Parser) { private val LOGGER = loggerFor<CapNakHandler>() override fun handle(message: CapMessage.Nak.Message, metadata: IMetadataStore) { val caps = message.caps val lifecycle = capState.lifecycle LOGGER.trace("server NAKed following caps: $caps") for (cap in caps) { if (capState.rejected.contains(cap)) { LOGGER.debug("we've already rejected cap $cap") continue } capState.rejected += cap capManager.capDisabled(cap) } when (lifecycle) { CapLifecycle.NEGOTIATING -> { LOGGER.trace("server NAKed some caps, checked if it's the last reply") val remainingCaps = capState.negotiate.subtract(capState.accepted).subtract(capState.rejected) LOGGER.trace("remaining caps to negotiate: $remainingCaps") capManager.onRegistrationStateChanged() } else -> Unit } } }
isc
87c1a65b30c8a3bdc79bc105ee15b605
33.204082
193
0.683771
4.158809
false
false
false
false
ice1000/algo4j
src/main/kotlin/org/algo4j/Heap.kt
1
863
@file:JvmName("Extension") @file:JvmMultifileClass /** * Created by ice1000 on 2017/1/24. * * @author ice1000 */ package org.algo4j import org.algo4j.tree.heap.MaxHeap import org.algo4j.tree.heap.MinHeap import org.jetbrains.annotations.Contract @Contract(pure = true) operator fun MinHeap.get(index: Int): Int = getElementAt(index) @Contract(pure = false) operator fun MinHeap.plusAssign(value: Int) = push(value) /** * functional plus */ @Contract(pure = true) operator fun MinHeap.plus(value: Int) = clone().apply { plusAssign(value) } @Contract(pure = true) operator fun MaxHeap.get(index: Int): Int = getElementAt(index) @Contract(pure = false) operator fun MaxHeap.plusAssign(value: Int) = push(value) /** * functional plus */ @Contract(pure = true) operator fun MaxHeap.plus(value: Int) = clone().apply { plusAssign(value) }
lgpl-3.0
b90ad14c32fa871c5ee3fa453e1b9ad2
17.76087
45
0.713789
3.082143
false
false
false
false
FredJul/TaskGame
TaskGame-Hero/src/main/java/net/fred/taskgame/hero/views/EmptyRecyclerView.kt
1
2712
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.hero.views import android.content.Context import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.View class EmptyRecyclerView : RecyclerView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val observer = object : RecyclerView.AdapterDataObserver() { override fun onChanged() { super.onChanged() checkIfEmpty() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { super.onItemRangeInserted(positionStart, itemCount) checkIfEmpty() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { super.onItemRangeRemoved(positionStart, itemCount) checkIfEmpty() } } private var emptyView: View? = null override fun setAdapter(adapter: RecyclerView.Adapter<*>?) { val oldAdapter = getAdapter() oldAdapter?.unregisterAdapterDataObserver(observer) adapter?.registerAdapterDataObserver(observer) super.setAdapter(adapter) checkIfEmpty() } override fun swapAdapter(adapter: RecyclerView.Adapter<*>?, removeAndRecycleExistingViews: Boolean) { val oldAdapter = getAdapter() oldAdapter?.unregisterAdapterDataObserver(observer) adapter?.registerAdapterDataObserver(observer) super.swapAdapter(adapter, removeAndRecycleExistingViews) checkIfEmpty() } fun setEmptyView(mEmptyView: View?) { this.emptyView = mEmptyView checkIfEmpty() } private fun checkIfEmpty() { emptyView?.let { if (adapter != null) { it.visibility = if (adapter.itemCount > 0) View.GONE else View.VISIBLE } } } }
gpl-3.0
7b504baa32cd567febcb3318b7808c4c
32.9
112
0.686578
4.834225
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/activities/MainActivity.kt
1
4785
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.activities import android.os.Bundle import androidx.viewpager.widget.ViewPager import com.google.android.material.tabs.TabLayout import com.pitchedapps.frost.facebook.FbItem import com.pitchedapps.frost.facebook.parsers.BadgeParser import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.views.BadgedIcon import com.pitchedapps.frost.web.FrostEmitter import com.pitchedapps.frost.web.asFrostEmitter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.onEach class MainActivity : BaseMainActivity() { private val fragmentMutableFlow = MutableSharedFlow<Int>(extraBufferCapacity = 10, onBufferOverflow = BufferOverflow.DROP_OLDEST) override val fragmentFlow: SharedFlow<Int> = fragmentMutableFlow.asSharedFlow() override val fragmentEmit: FrostEmitter<Int> = fragmentMutableFlow.asFrostEmitter() private val headerMutableFlow = MutableStateFlow("") override val headerFlow: SharedFlow<String> = headerMutableFlow.asSharedFlow() override val headerEmit: FrostEmitter<String> = headerMutableFlow.asFrostEmitter() override fun onNestedCreate(savedInstanceState: Bundle?) { with(contentBinding) { setupTabs() setupViewPager() } } private fun ActivityMainContentBinding.setupViewPager() { viewpager.addOnPageChangeListener( object : ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { super.onPageSelected(position) if (lastPosition == position) { return } if (lastPosition != -1) { fragmentEmit(-(lastPosition + 1)) } fragmentEmit(position) lastPosition = position } override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { super.onPageScrolled(position, positionOffset, positionOffsetPixels) val delta = positionOffset * (SELECTED_TAB_ALPHA - UNSELECTED_TAB_ALPHA) tabsForEachView { tabPosition, view -> view.setAllAlpha( when (tabPosition) { position -> SELECTED_TAB_ALPHA - delta position + 1 -> UNSELECTED_TAB_ALPHA + delta else -> UNSELECTED_TAB_ALPHA } ) } } } ) } private fun ActivityMainContentBinding.setupTabs() { viewpager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs)) tabs.addOnTabSelectedListener( object : TabLayout.ViewPagerOnTabSelectedListener(viewpager) { override fun onTabReselected(tab: TabLayout.Tab) { super.onTabReselected(tab) currentFragment?.onTabClick() } override fun onTabSelected(tab: TabLayout.Tab) { super.onTabSelected(tab) (tab.customView as BadgedIcon).badgeText = null } } ) headerFlow .filter { it.isNotBlank() } .mapNotNull { html -> BadgeParser.parseFromData(cookie = fbCookie.webCookie, text = html)?.data } .distinctUntilChanged() .flowOn(Dispatchers.IO) .onEach { data -> L.v { "Badges $data" } tabsForEachView { _, view -> when (view.iicon) { FbItem.FEED.icon -> view.badgeText = data.feed FbItem.FRIENDS.icon -> view.badgeText = data.friends FbItem.MESSAGES.icon -> view.badgeText = data.messages FbItem.NOTIFICATIONS.icon -> view.badgeText = data.notifications } } } .flowOn(Dispatchers.Main) .launchIn(this@MainActivity) } }
gpl-3.0
b4cf37fb061a25a51ea0808337e23d18
35.526718
99
0.695925
4.737624
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/permission/DownloadPermissionRequestContract.kt
1
1938
/* * Copyright (c) 2021 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.yobidashi.browser.permission import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts class DownloadPermissionRequestContract : ActivityResultContract<String?, Boolean>() { override fun createIntent(context: Context, input: String?): Intent { return Intent(ActivityResultContracts.RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS) .putExtra( ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, PERMISSIONS ) } override fun parseResult(resultCode: Int, intent: Intent?): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return true } if (resultCode != Activity.RESULT_OK) return false val granted = intent ?.getIntArrayExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS) ?.getOrNull(0) == PackageManager.PERMISSION_GRANTED return granted } companion object { private val PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arrayOf( Manifest.permission.POST_NOTIFICATIONS ) } else { arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE ) } } }
epl-1.0
e722cf60af2581fd072e8fb549bc09b5
33.625
113
0.680599
5.126984
false
false
false
false
npryce/krouton
src/main/kotlin/com/natpryce/krouton/PathTemplate.kt
1
8059
package com.natpryce.krouton import kotlin.reflect.KProperty interface PathTemplate<T> { fun parsePathElements(pathElements: List<String>): Pair<T, List<String>>? fun pathElementsFrom(value: T): List<String> fun templateElements(): List<UrlTemplateElement> fun monitoredTemplateElementsFrom(value: T): List<UrlTemplateElement> } typealias PathTemplate0 = PathTemplate<Unit> typealias PathTemplate1<A> = PathTemplate<A> typealias PathTemplate2<A, B> = PathTemplate<Tuple2<A, B>> typealias PathTemplate3<A, B, C> = PathTemplate<Tuple3<A, B, C>> typealias PathTemplate4<A, B, C, D> = PathTemplate<Tuple4<A, B, C, D>> typealias PathTemplate5<A, B, C, D, E> = PathTemplate<Tuple5<A, B, C, D, E>> fun <T> PathTemplate<T>.parse(s: String): T? { return parse(splitPath(s)) } fun <T> PathTemplate<T>.parse(splitPath: List<String>): T? = parsePathElements(splitPath)?.let { (result, unused) -> if (unused.isEmpty()) result else null } fun <T> PathTemplate<T>.path(value: T): String = joinPath(pathElementsFrom(value), ::encodePathElement) fun <T> PathTemplate<T>.monitoredPath(value: T): String = joinPath(monitoredTemplateElementsFrom(value), ::encodeUrlTemplatePathElement) fun <T> PathTemplate<T>.toUrlTemplate(): String = joinPath(templateElements(), ::encodeUrlTemplatePathElement) internal fun splitPath(path: String) = path.split("/").filterNot(String::isEmpty).map(::decodePathElement) internal fun <T> joinPath(pathElements: List<T>, transform: (T) -> CharSequence) = "/" + pathElements.joinToString("/", transform = transform) internal fun encodeUrlTemplatePathElement(it: UrlTemplateElement): CharSequence { return when (it) { is Variable -> "{" + it.name + "}" is Literal -> encodePathElement(it.value) } } /** * The root of path, <code>/</code>. */ object root : PathTemplate<Unit> { override fun parsePathElements(pathElements: List<String>) = Pair(Unit, pathElements) override fun pathElementsFrom(value: Unit) = emptyList<String>() override fun templateElements() = emptyList<UrlTemplateElement>() override fun monitoredTemplateElementsFrom(value: Unit) = emptyList<UrlTemplateElement>() } sealed class PathElement<T> : PathTemplate<T> { final override fun parsePathElements(pathElements: List<String>): Pair<T, List<String>>? = pathElements.firstOrNull() ?.let { parsePathElement(it) } ?.let { it to pathElements.drop(1) } abstract fun parsePathElement(element: String): T? final override fun pathElementsFrom(value: T) = listOf(pathElementFrom(value)) abstract fun pathElementFrom(value: T): String final override fun templateElements() = listOf(templateElement()) abstract fun templateElement(): UrlTemplateElement final override fun monitoredTemplateElementsFrom(value: T) = listOf(monitoredPathElementFrom(value)) abstract fun monitoredPathElementFrom(value: T): UrlTemplateElement } class VariablePathElement<T>( private val type: PathElementType<T>, private val name: String, private val isMonitored: Boolean = false ) : PathElement<T>() { override fun parsePathElement(element: String): T? = type.parsePathElement(element) override fun pathElementFrom(value: T): String = type.pathElementFrom(value) override fun templateElement() = Variable(name) override fun monitoredPathElementFrom(value: T): UrlTemplateElement = if (isMonitored) Literal(pathElementFrom(value)) else Variable(name) fun named(name: String) = VariablePathElement(type = type, name = name, isMonitored = isMonitored) fun monitored() = VariablePathElement(type = type, name = name, isMonitored = true) } operator fun <T> PathElementType<T>.getValue(obj: Any?, property: KProperty<*>): VariablePathElement<T> = VariablePathElement(this, property.name) operator fun <T> VariablePathElement<T>.getValue(obj: Any?, property: KProperty<*>): VariablePathElement<T> = this.named(property.name) class LiteralPathElement(private val pathElement: String) : PathElement<Unit>() { override fun parsePathElement(element: String) = Unit.takeIf { element == pathElement } override fun pathElementFrom(value: Unit) = pathElement override fun templateElement() = Literal(pathElement) override fun monitoredPathElementFrom(value: Unit) = Literal(pathElement) } class AppendedPathTemplate<T, U>(private val tScheme: PathTemplate<T>, private val uScheme: PathTemplate<U>) : PathTemplate<Tuple2<T, U>> { override fun parsePathElements(pathElements: List<String>) = tScheme.parsePathElements(pathElements)?.let { (t, uPathElements) -> uScheme.parsePathElements(uPathElements)?.let { (u, rest) -> tuple(t, u) to rest } } override fun pathElementsFrom(value: Tuple2<T,U>) = tScheme.pathElementsFrom(value.val1) + uScheme.pathElementsFrom(value.val2) override fun templateElements() = tScheme.templateElements() + uScheme.templateElements() override fun monitoredTemplateElementsFrom(value: Tuple2<T,U>) = tScheme.monitoredTemplateElementsFrom(value.val1) + uScheme.monitoredTemplateElementsFrom(value.val2) } class PrefixedPathTemplate<T>(private val prefix: PathTemplate<Unit>, private val rest: PathTemplate<T>) : PathTemplate<T> { override fun pathElementsFrom(value: T) = prefix.pathElementsFrom(Unit) + rest.pathElementsFrom(value) override fun parsePathElements(pathElements: List<String>) = prefix.parsePathElements(pathElements) ?.let { (_, restPathElements) -> rest.parsePathElements(restPathElements) } override fun templateElements() = prefix.templateElements() + rest.templateElements() override fun monitoredTemplateElementsFrom(value: T) = prefix.monitoredTemplateElementsFrom(Unit) + rest.monitoredTemplateElementsFrom(value) } class SuffixedPathTemplate<T>(private val first: PathTemplate<T>, private val suffix: PathTemplate<Unit>) : PathTemplate<T> { override fun pathElementsFrom(value: T) = first.pathElementsFrom(value) + suffix.pathElementsFrom(Unit) override fun parsePathElements(pathElements: List<String>) = first.parsePathElements(pathElements) ?.let { (value, restPathElements) -> suffix.parsePathElements(restPathElements) ?.let { (_, remainderPathElements) -> Pair(value, remainderPathElements) } } override fun templateElements() = first.templateElements() + suffix.templateElements() override fun monitoredTemplateElementsFrom(value: T) = first.monitoredTemplateElementsFrom(value) + suffix.monitoredTemplateElementsFrom(Unit) } class RestrictedPathTemplate<T>(private val base: PathTemplate<T>, private val p: (T) -> Boolean) : PathTemplate<T> { override fun parsePathElements(pathElements: List<String>) = base.parsePathElements(pathElements)?.flatMapFirst { if (p(it)) it else null } override fun pathElementsFrom(value: T) = base.pathElementsFrom(value) override fun templateElements() = base.templateElements() override fun monitoredTemplateElementsFrom(value: T) = base.monitoredTemplateElementsFrom(value) } class ProjectedPathTemplate<T, U>( private val base: PathTemplate<T>, private val projection: Projection<T, U> ) : PathTemplate<U> { override fun parsePathElements(pathElements: List<String>) = base.parsePathElements(pathElements).flatMapFirst { projection.fromParts(it) } override fun pathElementsFrom(value: U) = base.pathElementsFrom(projection.toParts(value)) override fun templateElements() = base.templateElements() override fun monitoredTemplateElementsFrom(value: U) = base.monitoredTemplateElementsFrom(projection.toParts(value)) } private fun <T1, T2, U> Pair<T1, U>?.flatMapFirst(f: (T1) -> T2?): Pair<T2, U>? = this?.run { f(first)?.to(second) }
apache-2.0
00cce82c08b5a7861218b2391de9d36c
40.973958
139
0.714729
3.935059
false
false
false
false
KotlinBy/awesome-kotlin
src/main/kotlin/link/kotlin/scripts/CategoryProcessor.kt
1
1063
package link.kotlin.scripts import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import link.kotlin.scripts.dsl.Category interface CategoryProcessor { suspend fun process(category: Category): Category companion object } private class ParallelCategoryProcessor( private val linksProcessor: LinksProcessor ) : CategoryProcessor { override suspend fun process(category: Category): Category = coroutineScope { val result = category.copy( subcategories = category.subcategories.map { subcategory -> subcategory.copy( links = subcategory.links.map { link -> async { linksProcessor.process(link) } }.awaitAll().toMutableList() ) }.toMutableList() ) result } } fun CategoryProcessor.Companion.default( linksProcessor: LinksProcessor ): CategoryProcessor { return ParallelCategoryProcessor( linksProcessor = linksProcessor ) }
apache-2.0
82da96ddb9ae4141c3e6d3ecf5d6c728
26.973684
81
0.670743
5.288557
false
false
false
false
lukecwik/incubator-beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/WindowedWordCount.kt
5
8581
/* * 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 org.apache.beam.examples.kotlin import org.apache.beam.examples.kotlin.common.ExampleBigQueryTableOptions import org.apache.beam.examples.kotlin.common.ExampleOptions import org.apache.beam.examples.kotlin.common.WriteOneFilePerWindow import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.io.TextIO import org.apache.beam.sdk.options.* import org.apache.beam.sdk.transforms.DoFn import org.apache.beam.sdk.transforms.MapElements import org.apache.beam.sdk.transforms.ParDo import org.apache.beam.sdk.transforms.windowing.FixedWindows import org.apache.beam.sdk.transforms.windowing.Window import org.apache.beam.sdk.values.PDone import org.joda.time.Duration import org.joda.time.Instant import java.io.IOException import java.util.concurrent.ThreadLocalRandom /** * An example that counts words in text, and can run over either unbounded or bounded input * collections. * * * This class, [WindowedWordCount], is the last in a series of four successively more * detailed 'word count' examples. First take a look at [MinimalWordCount], [WordCount], * and [DebuggingWordCount]. * * * Basic concepts, also in the MinimalWordCount, WordCount, and DebuggingWordCount examples: * Reading text files; counting a PCollection; writing to GCS; executing a Pipeline both locally and * using a selected runner; defining DoFns; user-defined PTransforms; defining PipelineOptions. * * * New Concepts: * * <pre> * 1. Unbounded and bounded pipeline input modes * 2. Adding timestamps to data * 3. Windowing * 4. Re-using PTransforms over windowed PCollections * 5. Accessing the window of an element * 6. Writing data to per-window text files </pre> * * * * By default, the examples will run with the `DirectRunner`. To change the runner, * specify: * * <pre>`--runner=YOUR_SELECTED_RUNNER `</pre> * * * See examples/kotlin/README.md for instructions about how to configure different runners. * * * To execute this pipeline locally, specify a local output file (if using the `DirectRunner`) or output prefix on a supported distributed file system. * * <pre>`--output=[YOUR_LOCAL_FILE | YOUR_OUTPUT_PREFIX] `</pre> * * * * The input file defaults to a public data set containing the text of King Lear, by William * Shakespeare. You can override it and choose your own input with `--inputFile`. * * * By default, the pipeline will do fixed windowing, on 10-minute windows. You can change this * interval by setting the `--windowSize` parameter, e.g. `--windowSize=15` for * 15-minute windows. * * * The example will try to cancel the pipeline on the signal to terminate the process (CTRL-C). */ public object WindowedWordCount { const val WINDOW_SIZE = 10 // Default window duration in minutes /** * Concept #2: A DoFn that sets the data element timestamp. This is a silly method, just for this * example, for the bounded data case. * * * Imagine that many ghosts of Shakespeare are all typing madly at the same time to recreate * his masterworks. Each line of the corpus will get a random associated timestamp somewhere in a * 2-hour period. */ public class AddTimestampFn(private val minTimestamp: Instant, private val maxTimestamp: Instant) : DoFn<String, String>() { @ProcessElement fun processElement(@Element element: String, receiver: DoFn.OutputReceiver<String>) { val randomTimestamp = Instant( ThreadLocalRandom.current() .nextLong(minTimestamp.millis, maxTimestamp.millis)) /* * Concept #2: Set the data element with that timestamp. */ receiver.outputWithTimestamp(element, Instant(randomTimestamp)) } } /** A [DefaultValueFactory] that returns the current system time. */ public class DefaultToCurrentSystemTime : DefaultValueFactory<Long> { override fun create(options: PipelineOptions) = System.currentTimeMillis() } /** A [DefaultValueFactory] that returns the minimum timestamp plus one hour. */ public class DefaultToMinTimestampPlusOneHour : DefaultValueFactory<Long> { override fun create(options: PipelineOptions) = (options as Options).minTimestampMillis!! + Duration.standardHours(1).millis } /** * Options for [WindowedWordCount]. * * * Inherits standard example configuration options, which allow specification of the runner, as * well as the [WordCount.WordCountOptions] support for specification of the input and * output files. */ public interface Options : WordCount.WordCountOptions, ExampleOptions, ExampleBigQueryTableOptions { @get:Description("Fixed window duration, in minutes") @get:Default.Integer(WINDOW_SIZE) var windowSize: Int? @get:Description("Minimum randomly assigned timestamp, in milliseconds-since-epoch") @get:Default.InstanceFactory(DefaultToCurrentSystemTime::class) var minTimestampMillis: Long? @get:Description("Maximum randomly assigned timestamp, in milliseconds-since-epoch") @get:Default.InstanceFactory(DefaultToMinTimestampPlusOneHour::class) var maxTimestampMillis: Long? @get:Description("Fixed number of shards to produce per window") var numShards: Int? } @Throws(IOException::class) @JvmStatic fun runWindowedWordCount(options: Options) { val output = options.output val minTimestamp = Instant(options.minTimestampMillis) val maxTimestamp = Instant(options.maxTimestampMillis) val pipeline = Pipeline.create(options) /* * Concept #1: the Beam SDK lets us run the same pipeline with either a bounded or * unbounded input source. */ val input = pipeline /* Read from the GCS file. */ .apply(TextIO.read().from(options.inputFile)) // Concept #2: Add an element timestamp, using an artificial time just to show // windowing. // See AddTimestampFn for more detail on this. .apply(ParDo.of(AddTimestampFn(minTimestamp, maxTimestamp))) /* * Concept #3: Window into fixed windows. The fixed window size for this example defaults to 1 * minute (you can change this with a command-line option). See the documentation for more * information on how fixed windows work, and for information on the other types of windowing * available (e.g., sliding windows). */ val windowedWords = input.apply( Window.into<String>(FixedWindows.of(Duration.standardMinutes(options.windowSize!!.toLong())))) /* * Concept #4: Re-use our existing CountWords transform that does not have knowledge of * windows over a PCollection containing windowed values. */ val wordCounts = windowedWords.apply(WordCount.CountWords()) /* * Concept #5: Format the results and write to a sharded file partitioned by window, using a * simple ParDo operation. Because there may be failures followed by retries, the * writes must be idempotent, but the details of writing to files is elided here. */ wordCounts .apply(MapElements.via(WordCount.FormatAsTextFn())) .apply<PDone>(WriteOneFilePerWindow(output, options.numShards)) val result = pipeline.run() try { result.waitUntilFinish() } catch (exc: Exception) { result.cancel() } } @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { val options = (PipelineOptionsFactory.fromArgs(*args).withValidation() as Options) runWindowedWordCount(options) } }
apache-2.0
d73eb2b9c5d1a5931861aeaf28a51e54
39.476415
151
0.702482
4.294795
false
false
false
false
Sjtek/sjtekcontrol-core
data/src/main/kotlin/nl/sjtek/control/data/amqp/SwitchStateEvent.kt
1
827
package nl.sjtek.control.data.amqp import nl.sjtek.control.data.toInt data class SwitchStateEvent(val id: Int, val state: Boolean) : AMQPEvent() { override fun toMessage(): ByteArray = TEMPLATE.format(id, state.toInt()).toByteArray() companion object { private const val TEMPLATE = "99;%02d;%01d" fun parseMessage(message: String): SwitchStateEvent? { val args = message.split(delimiters = ";") return if (args.size == 3 && args[0] == "99") { try { val id = args[1].toInt() val state = args[2] == "1" SwitchStateEvent(id, state) } catch (e: NumberFormatException) { null } } else { null } } } }
gpl-3.0
2fc3cea40c9583d24ce6016ed2d5f403
29.666667
90
0.505441
4.375661
false
false
false
false
ZsemberiDaniel/EgerBusz
app/src/main/java/com/zsemberidaniel/egerbuszuj/realm/objects/Trip.kt
1
517
package com.zsemberidaniel.egerbuszuj.realm.objects import io.realm.RealmObject /** * Created by zsemberi.daniel on 2017. 05. 12.. */ open class Trip : RealmObject() { var id: String? = null var route: Route? = null var headSign: String? = null var direction: Int = 0 var dayType: Int = 0 companion object { val CN_ID = "id" val CN_ROUTE = "route" val CN_DAY_TYPE = "dayType" val CN_HEAD_SIGN = "headSign" val CN_DIRECTION = "direction" } }
apache-2.0
269e7345b9ebc7b1cd064df9d7397053
19.68
51
0.603482
3.493243
false
false
false
false