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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/people/PersonViewModel.kt | 1 | 1332 | package com.battlelancer.seriesguide.people
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.tmdbapi.TmdbTools2
import kotlinx.coroutines.Dispatchers
class PersonViewModel(
application: Application,
private val personTmdbId: Int
) : AndroidViewModel(application) {
val languageCode = MutableLiveData<String>()
val personLiveData = languageCode.switchMap {
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
val peopleService = SgApp.getServicesComponent(getApplication()).peopleService()!!
val personOrNull = TmdbTools2().getPerson(peopleService, personTmdbId, it)
emit(personOrNull)
}
}
}
class PersonViewModelFactory(
private val application: Application,
private val personTmdbId: Int
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PersonViewModel(application, personTmdbId) as T
}
}
| apache-2.0 | 275693a29af29fcc44e9ff3f21f78207 | 33.153846 | 94 | 0.77027 | 4.988764 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/CupsPrinter.kt | 1 | 6648 | package org.cups4j
/**
* Copyright (C) 2009 Harald Weyhing
*
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see
* <http:></http:>//www.gnu.org/licenses/>.
*/
import android.content.Context
import org.cups4j.operations.ipp.IppGetJobAttributesOperation
import org.cups4j.operations.ipp.IppGetJobsOperation
import org.cups4j.operations.ipp.IppPrintJobOperation
import java.net.URL
import java.util.HashMap
/**
* Represents a printer on your IPP server
*/
/**
* Constructor
*
* @param printerURL Printer URL
* @param name Printer name
* @param isDefault true if this is the default printer on this IPP server
*/
class CupsPrinter(
/**
* The URL for this printer
*/
val printerURL: URL,
/**
* Name of this printer.
* For a printer http://localhost:631/printers/printername 'printername' will
* be returned.
*/
val name: String,
/**
* Is this the default printer
*/
var isDefault: Boolean) {
/**
* Description attribute for this printer
*/
var description: String? = null
/**
* Location attribute for this printer
*/
var location: String? = null
/**
* Print method
*
* @param printJob Print job
* @return PrintRequestResult
* @throws Exception
*/
@Throws(Exception::class)
fun print(printJob: PrintJob, context: Context): PrintRequestResult {
var ippJobID = -1
val document = printJob.document
var userName = printJob.userName
val jobName = printJob.jobName ?: "Unknown"
val copies = printJob.copies
val pageRanges = printJob.pageRanges
var attributes: MutableMap<String, String>? = printJob.attributes
if (userName == null) {
userName = CupsClient.DEFAULT_USER
}
if (attributes == null) {
attributes = HashMap()
}
attributes["requesting-user-name"] = userName
attributes["job-name"] = jobName
val copiesString: String
val rangesString = StringBuilder()
if (copies > 0) {// other values are considered bad value by CUPS
copiesString = "copies:integer:$copies"
addAttribute(attributes, "job-attributes", copiesString)
}
if (pageRanges != null && "" != pageRanges) {
val ranges = pageRanges.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var delimiter = ""
rangesString.append("page-ranges:setOfRangeOfInteger:")
for (range in ranges) {
var actualRange = range.trim { it <= ' ' }
val values = range.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (values.size == 1) {
actualRange = "$range-$range"
}
rangesString.append(delimiter).append(actualRange)
// following ranges need to be separated with ","
delimiter = ","
}
addAttribute(attributes, "job-attributes", rangesString.toString())
}
if (printJob.isDuplex) {
addAttribute(attributes, "job-attributes", "sides:keyword:two-sided-long-edge")
}
val command = IppPrintJobOperation(context)
val ippResult = command.request(printerURL, attributes, document)
// IppResultPrinter.print(ippResult);
val result = PrintRequestResult(ippResult)
for (group in ippResult!!.attributeGroupList!!) {
if (group.tagName == "job-attributes-tag") {
for (attr in group.attribute) {
if (attr.name == "job-id") {
ippJobID = attr.attributeValue[0].value?.toInt()!!
}
}
}
}
result.jobId = ippJobID
return result
}
/**
* @param map Attributes map
* @param name Attribute key
* @param value Attribute value
*/
private fun addAttribute(map: MutableMap<String, String>, name: String?, value: String?) {
if (value != null && name != null) {
var attribute: String? = map[name]
if (attribute == null) {
attribute = value
} else {
attribute += "#$value"
}
map[name] = attribute
}
}
/**
* Get a list of jobs
*
* @param whichJobs completed, not completed or all
* @param user requesting user (null will be translated to anonymous)
* @param myJobs boolean only jobs for requesting user or all jobs for this printer?
* @return job list
* @throws Exception
*/
@Throws(Exception::class)
fun getJobs(whichJobs: WhichJobsEnum, user: String, myJobs: Boolean, context: Context): List<PrintJobAttributes> =
IppGetJobsOperation(context).getPrintJobs(this, whichJobs, user, myJobs)
/**
* Get current status for the print job with the given ID.
*
* @param jobID Job ID
* @return job status
* @throws Exception
*/
@Throws(Exception::class)
fun getJobStatus(jobID: Int, context: Context): JobStateEnum? = getJobStatus(CupsClient.DEFAULT_USER, jobID, context)
/**
* Get current status for the print job with the given ID
*
* @param userName Requesting user name
* @param jobID Job ID
* @return job status
* @throws Exception
*/
@Throws(Exception::class)
fun getJobStatus(userName: String, jobID: Int, context: Context): JobStateEnum? {
val command = IppGetJobAttributesOperation(context)
val job = command.getPrintJobAttributes(printerURL, userName, jobID)
return job.jobState
}
/**
* Get a String representation of this printer consisting of the printer URL
* and the name
*
* @return String
*/
override fun toString(): String =
"printer uri=$printerURL default=$isDefault name=$name"
}
| lgpl-3.0 | b1c27e9eda4c0b1a718dd05e5c9965e3 | 31.115942 | 121 | 0.60364 | 4.482805 | false | false | false | false |
google/fhir-app-examples | demo/src/main/java/com/google/fhir/examples/demo/ScreenerFragment.kt | 1 | 4615 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.fhir.examples.demo
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.navArgs
import com.google.android.fhir.datacapture.QuestionnaireFragment
/** A fragment class to show screener questionnaire screen. */
class ScreenerFragment : Fragment(R.layout.screener_encounter_fragment) {
private val viewModel: ScreenerViewModel by viewModels()
private val args: ScreenerFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpActionBar()
setHasOptionsMenu(true)
updateArguments()
onBackPressed()
observeResourcesSaveAction()
if (savedInstanceState == null) {
addQuestionnaireFragment()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.screen_encounter_fragment_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_add_patient_submit -> {
onSubmitAction()
true
}
android.R.id.home -> {
showCancelScreenerQuestionnaireAlertDialog()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun setUpActionBar() {
(requireActivity() as AppCompatActivity).supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
}
}
private fun updateArguments() {
requireArguments().putString(QUESTIONNAIRE_FILE_PATH_KEY, "screener-questionnaire.json")
}
private fun addQuestionnaireFragment() {
val fragment = QuestionnaireFragment()
fragment.arguments =
bundleOf(QuestionnaireFragment.EXTRA_QUESTIONNAIRE_JSON_STRING to viewModel.questionnaire)
childFragmentManager.commit {
add(R.id.add_patient_container, fragment, QUESTIONNAIRE_FRAGMENT_TAG)
}
}
private fun onSubmitAction() {
val questionnaireFragment =
childFragmentManager.findFragmentByTag(QUESTIONNAIRE_FRAGMENT_TAG) as QuestionnaireFragment
viewModel.saveScreenerEncounter(
questionnaireFragment.getQuestionnaireResponse(),
args.patientId
)
}
private fun showCancelScreenerQuestionnaireAlertDialog() {
val alertDialog: AlertDialog? =
activity?.let {
val builder = AlertDialog.Builder(it)
builder.apply {
setMessage(getString(R.string.cancel_questionnaire_message))
setPositiveButton(getString(android.R.string.yes)) { _, _ ->
NavHostFragment.findNavController(this@ScreenerFragment).navigateUp()
}
setNegativeButton(getString(android.R.string.no)) { _, _ -> }
}
builder.create()
}
alertDialog?.show()
}
private fun onBackPressed() {
activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner) {
showCancelScreenerQuestionnaireAlertDialog()
}
}
private fun observeResourcesSaveAction() {
viewModel.isResourcesSaved.observe(viewLifecycleOwner) {
if (!it) {
Toast.makeText(requireContext(), getString(R.string.inputs_missing), Toast.LENGTH_SHORT)
.show()
return@observe
}
Toast.makeText(requireContext(), getString(R.string.resources_saved), Toast.LENGTH_SHORT)
.show()
NavHostFragment.findNavController(this).navigateUp()
}
}
companion object {
const val QUESTIONNAIRE_FILE_PATH_KEY = "questionnaire-file-path-key"
const val QUESTIONNAIRE_FRAGMENT_TAG = "questionnaire-fragment-tag"
}
}
| apache-2.0 | ffde54ad0a5db2a18518eb2a994aabc9 | 31.964286 | 97 | 0.729144 | 4.728484 | false | false | false | false |
cketti/k-9 | mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/RealImapFolder.kt | 1 | 46279 | package com.fsck.k9.mail.store.imap
import com.fsck.k9.logging.Timber
import com.fsck.k9.mail.Body
import com.fsck.k9.mail.BodyFactory
import com.fsck.k9.mail.FetchProfile
import com.fsck.k9.mail.Flag
import com.fsck.k9.mail.K9MailLib
import com.fsck.k9.mail.Message
import com.fsck.k9.mail.MessageRetrievalListener
import com.fsck.k9.mail.MessagingException
import com.fsck.k9.mail.Part
import com.fsck.k9.mail.filter.EOLConvertingOutputStream
import com.fsck.k9.mail.internet.MimeBodyPart
import com.fsck.k9.mail.internet.MimeHeader
import com.fsck.k9.mail.internet.MimeMessageHelper
import com.fsck.k9.mail.internet.MimeMultipart
import com.fsck.k9.mail.internet.MimeParameterEncoder.isToken
import com.fsck.k9.mail.internet.MimeParameterEncoder.quotedUtf8
import com.fsck.k9.mail.internet.MimeUtility
import java.io.IOException
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
internal class RealImapFolder(
private val internalImapStore: InternalImapStore,
private val connectionManager: ImapConnectionManager,
override val serverId: String,
private val folderNameCodec: FolderNameCodec
) : ImapFolder {
private var uidNext = -1L
internal var connection: ImapConnection? = null
private set
private var exists = false
private var inSearch = false
private var canCreateKeywords = false
private var uidValidity: Long? = null
override var messageCount = -1
private set
override var mode: OpenMode? = null
private set
val isOpen: Boolean
get() = connection != null
override fun getUidValidity(): Long? {
check(isOpen) { "ImapFolder needs to be open" }
return uidValidity
}
@get:Throws(MessagingException::class)
private val prefixedName: String
get() {
var prefixedName = ""
if (!INBOX.equals(serverId, ignoreCase = true)) {
val connection = synchronized(this) {
this.connection ?: connectionManager.getConnection()
}
try {
connection.open()
} catch (ioe: IOException) {
throw MessagingException("Unable to get IMAP prefix", ioe)
} finally {
if (this.connection == null) {
connectionManager.releaseConnection(connection)
}
}
prefixedName = internalImapStore.getCombinedPrefix()
}
prefixedName += serverId
return prefixedName
}
@Throws(MessagingException::class, IOException::class)
private fun executeSimpleCommand(command: String): List<ImapResponse> {
return handleUntaggedResponses(connection!!.executeSimpleCommand(command))
}
@Throws(MessagingException::class)
override fun open(mode: OpenMode) {
internalOpen(mode)
if (messageCount == -1) {
throw MessagingException("Did not find message count during open")
}
}
@Throws(MessagingException::class)
private fun internalOpen(mode: OpenMode): List<ImapResponse> {
if (isOpen && this.mode == mode) {
// Make sure the connection is valid. If it's not we'll close it down and continue on to get a new one.
try {
return executeSimpleCommand(Commands.NOOP)
} catch (ioe: IOException) {
/* don't throw */ ioExceptionHandler(connection, ioe)
}
}
connectionManager.releaseConnection(connection)
synchronized(this) {
connection = connectionManager.getConnection()
}
try {
val openCommand = if (mode == OpenMode.READ_WRITE) "SELECT" else "EXAMINE"
val encodedFolderName = folderNameCodec.encode(prefixedName)
val escapedFolderName = ImapUtility.encodeString(encodedFolderName)
val command = String.format("%s %s", openCommand, escapedFolderName)
val responses = executeSimpleCommand(command)
/*
* If the command succeeds we expect the folder has been opened read-write unless we
* are notified otherwise in the responses.
*/
this.mode = mode
for (response in responses) {
extractUidValidity(response)
handlePermanentFlags(response)
}
handleSelectOrExamineOkResponse(ImapUtility.getLastResponse(responses))
exists = true
return responses
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
} catch (me: MessagingException) {
Timber.e(me, "Unable to open connection for %s", logId)
throw me
}
}
private fun extractUidValidity(response: ImapResponse) {
val uidValidityResponse = UidValidityResponse.parse(response)
if (uidValidityResponse != null) {
uidValidity = uidValidityResponse.uidValidity
}
}
private fun handlePermanentFlags(response: ImapResponse) {
val permanentFlagsResponse = PermanentFlagsResponse.parse(response) ?: return
val permanentFlags = internalImapStore.getPermanentFlagsIndex()
permanentFlags.addAll(permanentFlagsResponse.flags)
canCreateKeywords = permanentFlagsResponse.canCreateKeywords()
}
private fun handleSelectOrExamineOkResponse(response: ImapResponse) {
val selectOrExamineResponse = SelectOrExamineResponse.parse(response) ?: return // This shouldn't happen
if (selectOrExamineResponse.hasOpenMode()) {
mode = selectOrExamineResponse.openMode
}
}
override fun close() {
messageCount = -1
if (!isOpen) {
return
}
synchronized(this) {
// If we are mid-search and we get a close request, we gotta trash the connection.
if (inSearch && connection != null) {
Timber.i("IMAP search was aborted, shutting down connection.")
connection!!.close()
} else {
connectionManager.releaseConnection(connection)
}
connection = null
}
}
@Throws(MessagingException::class)
private fun exists(escapedFolderName: String): Boolean {
return try {
// Since we don't care about RECENT, we'll use that for the check, because we're checking
// a folder other than ourself, and don't want any untagged responses to cause a change
// in our own fields
connection!!.executeSimpleCommand(String.format("STATUS %s (RECENT)", escapedFolderName))
true
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
} catch (e: NegativeImapResponseException) {
false
}
}
@Throws(MessagingException::class)
override fun exists(): Boolean {
if (exists) {
return true
}
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
val connection = synchronized(this) {
this.connection ?: connectionManager.getConnection()
}
return try {
val encodedFolderName = folderNameCodec.encode(prefixedName)
val escapedFolderName = ImapUtility.encodeString(encodedFolderName)
connection.executeSimpleCommand(String.format("STATUS %s (UIDVALIDITY)", escapedFolderName))
exists = true
true
} catch (e: NegativeImapResponseException) {
false
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
} finally {
if (this.connection == null) {
connectionManager.releaseConnection(connection)
}
}
}
@Throws(MessagingException::class)
fun create(): Boolean {
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
val connection = synchronized(this) {
this.connection ?: connectionManager.getConnection()
}
return try {
val encodedFolderName = folderNameCodec.encode(prefixedName)
val escapedFolderName = ImapUtility.encodeString(encodedFolderName)
connection.executeSimpleCommand(String.format("CREATE %s", escapedFolderName))
true
} catch (e: NegativeImapResponseException) {
false
} catch (ioe: IOException) {
throw ioExceptionHandler(this.connection, ioe)
} finally {
if (this.connection == null) {
connectionManager.releaseConnection(connection)
}
}
}
/**
* Copies the given messages to the specified folder.
*
* **Note:**
* Only the UIDs of the given [ImapMessage] instances are used. It is assumed that all
* UIDs represent valid messages in this folder.
*
* @param messages The messages to copy to the specified folder.
* @param folder The name of the target folder.
*
* @return The mapping of original message UIDs to the new server UIDs.
*/
@Throws(MessagingException::class)
override fun copyMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? {
require(folder is RealImapFolder) { "'folder' needs to be a RealImapFolder instance" }
if (messages.isEmpty()) {
return null
}
checkOpen() // only need READ access
val uids = messages.map { it.uid.toLong() }.toSet()
val encodedDestinationFolderName = folderNameCodec.encode(folder.prefixedName)
val escapedDestinationFolderName = ImapUtility.encodeString(encodedDestinationFolderName)
// TODO: Just perform the operation and only check for existence of the folder if the operation fails.
if (!exists(escapedDestinationFolderName)) {
if (K9MailLib.isDebug()) {
Timber.i(
"ImapFolder.copyMessages: couldn't find remote folder '%s' for %s",
escapedDestinationFolderName, logId
)
}
throw FolderNotFoundException(folder.serverId)
}
return try {
val imapResponses = connection!!.executeCommandWithIdSet(
Commands.UID_COPY,
escapedDestinationFolderName,
uids
)
UidCopyResponse.parse(imapResponses)?.uidMapping
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
override fun moveMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? {
if (messages.isEmpty()) {
return null
}
val uidMapping = copyMessages(messages, folder)
setFlags(messages, setOf(Flag.DELETED), true)
return uidMapping
}
@Throws(MessagingException::class)
private fun getRemoteMessageCount(criteria: String): Int {
checkOpen()
try {
val command = String.format(Locale.US, "SEARCH 1:* %s", criteria)
val responses = executeSimpleCommand(command)
return responses.sumOf { response ->
if (ImapResponseParser.equalsIgnoreCase(response[0], "SEARCH")) {
response.size - 1
} else {
0
}
}
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@get:Throws(MessagingException::class)
val unreadMessageCount: Int
get() = getRemoteMessageCount("UNSEEN NOT DELETED")
@get:Throws(MessagingException::class)
val flaggedMessageCount: Int
get() = getRemoteMessageCount("FLAGGED NOT DELETED")
@get:Throws(MessagingException::class)
internal val highestUid: Long
get() = try {
val responses = executeSimpleCommand("UID SEARCH *:*")
val searchResponse = SearchResponse.parse(responses)
extractHighestUid(searchResponse)
} catch (e: NegativeImapResponseException) {
-1L
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
private fun extractHighestUid(searchResponse: SearchResponse): Long {
return searchResponse.numbers.maxOrNull() ?: -1L
}
override fun getMessage(uid: String): ImapMessage {
return ImapMessage(uid)
}
@Throws(MessagingException::class)
override fun getMessages(
start: Int,
end: Int,
earliestDate: Date?,
listener: MessageRetrievalListener<ImapMessage>?
): List<ImapMessage> {
return getMessages(start, end, earliestDate, false, listener)
}
@Throws(MessagingException::class)
private fun getMessages(
start: Int,
end: Int,
earliestDate: Date?,
includeDeleted: Boolean,
listener: MessageRetrievalListener<ImapMessage>?
): List<ImapMessage> {
if (start < 1 || end < 1 || end < start) {
throw MessagingException(String.format(Locale.US, "Invalid message set %d %d", start, end))
}
checkOpen()
val dateSearchString = getDateSearchString(earliestDate)
val command = String.format(
Locale.US, "UID SEARCH %d:%d%s%s",
start,
end,
dateSearchString,
if (includeDeleted) "" else " NOT DELETED"
)
try {
val imapResponses = connection!!.executeSimpleCommand(command)
val searchResponse = SearchResponse.parse(imapResponses)
return getMessages(searchResponse, listener)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
private fun getDateSearchString(earliestDate: Date?): String {
return if (earliestDate == null) {
""
} else {
" SINCE " + RFC3501_DATE.get()!!.format(earliestDate)
}
}
@Throws(IOException::class, MessagingException::class)
override fun areMoreMessagesAvailable(indexOfOldestMessage: Int, earliestDate: Date?): Boolean {
checkOpen()
if (indexOfOldestMessage == 1) {
return false
}
var endIndex = indexOfOldestMessage - 1
val dateSearchString = getDateSearchString(earliestDate)
while (endIndex > 0) {
val startIndex = max(0, endIndex - MORE_MESSAGES_WINDOW_SIZE) + 1
if (existsNonDeletedMessageInRange(startIndex, endIndex, dateSearchString)) {
return true
}
endIndex -= MORE_MESSAGES_WINDOW_SIZE
}
return false
}
@Throws(MessagingException::class, IOException::class)
private fun existsNonDeletedMessageInRange(startIndex: Int, endIndex: Int, dateSearchString: String): Boolean {
val command = String.format(
Locale.US, "SEARCH %d:%d%s NOT DELETED",
startIndex, endIndex, dateSearchString
)
val imapResponses = executeSimpleCommand(command)
val response = SearchResponse.parse(imapResponses)
return response.numbers.size > 0
}
@Throws(MessagingException::class)
internal fun getMessages(
mesgSeqs: Set<Long>,
includeDeleted: Boolean,
listener: MessageRetrievalListener<ImapMessage>?
): List<ImapMessage> {
checkOpen()
try {
val commandSuffix = if (includeDeleted) "" else " NOT DELETED"
val imapResponses = connection!!.executeCommandWithIdSet(Commands.UID_SEARCH, commandSuffix, mesgSeqs)
val searchResponse = SearchResponse.parse(imapResponses)
return getMessages(searchResponse, listener)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
internal fun getMessagesFromUids(mesgUids: List<String>): List<ImapMessage> {
checkOpen()
val uidSet = mesgUids.map { it.toLong() }.toSet()
try {
val imapResponses = connection!!.executeCommandWithIdSet("UID SEARCH UID", "", uidSet)
val searchResponse = SearchResponse.parse(imapResponses)
return getMessages(searchResponse, null)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
private fun getMessages(
searchResponse: SearchResponse,
listener: MessageRetrievalListener<ImapMessage>?
): List<ImapMessage> {
// Sort the uids in numerically decreasing order
// By doing it in decreasing order, we ensure newest messages are dealt with first
// This makes the most sense when a limit is imposed, and also prevents UI from going
// crazy adding stuff at the top.
val uids = searchResponse.numbers.sortedDescending()
return uids.map { uidLong ->
val uid = uidLong.toString()
val message = ImapMessage(uid)
listener?.messageFinished(message)
message
}
}
@Throws(MessagingException::class)
override fun fetch(
messages: List<ImapMessage>,
fetchProfile: FetchProfile,
listener: FetchListener?,
maxDownloadSize: Int
) {
if (messages.isEmpty()) {
return
}
checkOpen()
val messageMap = messages.associateBy { it.uid }
val uids = messages.map { it.uid }
val fetchFields: MutableSet<String> = LinkedHashSet()
fetchFields.add("UID")
if (fetchProfile.contains(FetchProfile.Item.FLAGS)) {
fetchFields.add("FLAGS")
}
if (fetchProfile.contains(FetchProfile.Item.ENVELOPE)) {
fetchFields.add("INTERNALDATE")
fetchFields.add("RFC822.SIZE")
fetchFields.add(
"BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc " +
"reply-to message-id references in-reply-to list-unsubscribe " +
K9MailLib.IDENTITY_HEADER + " " + K9MailLib.CHAT_HEADER + ")]"
)
}
if (fetchProfile.contains(FetchProfile.Item.STRUCTURE)) {
fetchFields.add("BODYSTRUCTURE")
}
if (fetchProfile.contains(FetchProfile.Item.BODY_SANE)) {
if (maxDownloadSize > 0) {
fetchFields.add(String.format(Locale.US, "BODY.PEEK[]<0.%d>", maxDownloadSize))
} else {
fetchFields.add("BODY.PEEK[]")
}
}
if (fetchProfile.contains(FetchProfile.Item.BODY)) {
fetchFields.add("BODY.PEEK[]")
}
val spaceSeparatedFetchFields = ImapUtility.join(" ", fetchFields)
var windowStart = 0
val processedUids = mutableSetOf<String>()
while (windowStart < messages.size) {
val windowEnd = min(windowStart + FETCH_WINDOW_SIZE, messages.size)
val uidWindow = uids.subList(windowStart, windowEnd)
try {
val commaSeparatedUids = ImapUtility.join(",", uidWindow)
val command = String.format("UID FETCH %s (%s)", commaSeparatedUids, spaceSeparatedFetchFields)
connection!!.sendCommand(command, false)
var callback: ImapResponseCallback? = null
if (fetchProfile.contains(FetchProfile.Item.BODY) ||
fetchProfile.contains(FetchProfile.Item.BODY_SANE)
) {
callback = FetchBodyCallback(messageMap)
}
var response: ImapResponse
do {
response = connection!!.readResponse(callback)
if (response.tag == null && ImapResponseParser.equalsIgnoreCase(response[1], "FETCH")) {
val fetchList = response.getKeyedValue("FETCH") as ImapList
val uid = fetchList.getKeyedString("UID")
val message = messageMap[uid]
if (message == null) {
if (K9MailLib.isDebug()) {
Timber.d("Do not have message in messageMap for UID %s for %s", uid, logId)
}
handleUntaggedResponse(response)
continue
}
val literal = handleFetchResponse(message, fetchList)
if (literal != null) {
when (literal) {
is String -> {
val bodyStream: InputStream = literal.toByteArray().inputStream()
message.parse(bodyStream)
}
is Int -> {
// All the work was done in FetchBodyCallback.foundLiteral()
}
else -> {
// This shouldn't happen
throw MessagingException("Got FETCH response with bogus parameters")
}
}
}
val isFirstResponse = uid !in processedUids
processedUids.add(uid)
listener?.onFetchResponse(message, isFirstResponse)
} else {
handleUntaggedResponse(response)
}
} while (response.tag == null)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
windowStart += FETCH_WINDOW_SIZE
}
}
@Throws(MessagingException::class)
override fun fetchPart(
message: ImapMessage,
part: Part,
bodyFactory: BodyFactory,
maxDownloadSize: Int
) {
checkOpen()
val partId = part.serverExtra
val fetch = if ("TEXT".equals(partId, ignoreCase = true)) {
String.format(Locale.US, "BODY.PEEK[TEXT]<0.%d>", maxDownloadSize)
} else {
String.format("BODY.PEEK[%s]", partId)
}
try {
val command = String.format("UID FETCH %s (UID %s)", message.uid, fetch)
connection!!.sendCommand(command, false)
val callback: ImapResponseCallback = FetchPartCallback(part, bodyFactory)
var response: ImapResponse
do {
response = connection!!.readResponse(callback)
if (response.tag == null && ImapResponseParser.equalsIgnoreCase(response[1], "FETCH")) {
val fetchList = response.getKeyedValue("FETCH") as ImapList
val uid = fetchList.getKeyedString("UID")
if (message.uid != uid) {
if (K9MailLib.isDebug()) {
Timber.d("Did not ask for UID %s for %s", uid, logId)
}
handleUntaggedResponse(response)
continue
}
val literal = handleFetchResponse(message, fetchList)
if (literal != null) {
when (literal) {
is Body -> {
// Most of the work was done in FetchAttachmentCallback.foundLiteral()
MimeMessageHelper.setBody(part, literal as Body?)
}
is String -> {
val bodyStream: InputStream = literal.toByteArray().inputStream()
val contentTransferEncoding =
part.getHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0]
val contentType = part.getHeader(MimeHeader.HEADER_CONTENT_TYPE)[0]
val body = bodyFactory.createBody(contentTransferEncoding, contentType, bodyStream)
MimeMessageHelper.setBody(part, body)
}
else -> {
// This shouldn't happen
throw MessagingException("Got FETCH response with bogus parameters")
}
}
}
} else {
handleUntaggedResponse(response)
}
} while (response.tag == null)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
// Returns value of body field
@Throws(MessagingException::class)
private fun handleFetchResponse(message: ImapMessage, fetchList: ImapList): Any? {
var result: Any? = null
if (fetchList.containsKey("FLAGS")) {
val flags = fetchList.getKeyedList("FLAGS")
if (flags != null) {
for (i in flags.indices) {
val flag = flags.getString(i)
when {
flag.equals("\\Deleted", ignoreCase = true) -> {
message.setFlag(Flag.DELETED, true)
}
flag.equals("\\Answered", ignoreCase = true) -> {
message.setFlag(Flag.ANSWERED, true)
}
flag.equals("\\Seen", ignoreCase = true) -> {
message.setFlag(Flag.SEEN, true)
}
flag.equals("\\Flagged", ignoreCase = true) -> {
message.setFlag(Flag.FLAGGED, true)
}
flag.equals("\$Forwarded", ignoreCase = true) -> {
message.setFlag(Flag.FORWARDED, true)
// a message contains FORWARDED FLAG -> so we can also create them
internalImapStore.getPermanentFlagsIndex().add(Flag.FORWARDED)
}
flag.equals("\\Draft", ignoreCase = true) -> {
message.setFlag(Flag.DRAFT, true)
}
}
}
}
}
if (fetchList.containsKey("INTERNALDATE")) {
message.internalDate = fetchList.getKeyedDate("INTERNALDATE")
}
if (fetchList.containsKey("RFC822.SIZE")) {
val size = fetchList.getKeyedNumber("RFC822.SIZE")
message.setSize(size)
}
if (fetchList.containsKey("BODYSTRUCTURE")) {
val bs = fetchList.getKeyedList("BODYSTRUCTURE")
if (bs != null) {
try {
parseBodyStructure(bs, message, "TEXT")
} catch (e: MessagingException) {
if (K9MailLib.isDebug()) {
Timber.d(e, "Error handling message for %s", logId)
}
message.body = null
}
}
}
if (fetchList.containsKey("BODY")) {
val index = fetchList.getKeyIndex("BODY") + 2
val size = fetchList.size
if (index < size) {
result = fetchList.getObject(index)
// Check if there's an origin octet
if (result is String) {
if (result.startsWith("<") && index + 1 < size) {
result = fetchList.getObject(index + 1)
}
}
}
}
return result
}
private fun handleUntaggedResponses(responses: List<ImapResponse>): List<ImapResponse> {
for (response in responses) {
handleUntaggedResponse(response)
}
return responses
}
private fun handlePossibleUidNext(response: ImapResponse) {
if (ImapResponseParser.equalsIgnoreCase(response[0], "OK") && response.size > 1) {
val bracketed = response[1] as? ImapList ?: return
val key = bracketed.firstOrNull() as? String ?: return
if ("UIDNEXT".equals(key, ignoreCase = true)) {
uidNext = bracketed.getLong(1)
if (K9MailLib.isDebug()) {
Timber.d("Got UidNext = %s for %s", uidNext, logId)
}
}
}
}
/**
* Handle an untagged response that the caller doesn't care to handle themselves.
*/
private fun handleUntaggedResponse(response: ImapResponse) {
if (response.tag == null && response.size > 1) {
if (ImapResponseParser.equalsIgnoreCase(response[1], "EXISTS")) {
messageCount = response.getNumber(0)
if (K9MailLib.isDebug()) {
Timber.d("Got untagged EXISTS with value %d for %s", messageCount, logId)
}
}
handlePossibleUidNext(response)
if (ImapResponseParser.equalsIgnoreCase(response[1], "EXPUNGE") && messageCount > 0) {
messageCount--
if (K9MailLib.isDebug()) {
Timber.d("Got untagged EXPUNGE with messageCount %d for %s", messageCount, logId)
}
}
}
}
@Throws(MessagingException::class)
private fun parseBodyStructure(bs: ImapList, part: Part, id: String) {
if (bs[0] is ImapList) {
// This is a multipart
val mp = MimeMultipart.newInstance()
for (i in bs.indices) {
if (bs[i] is ImapList) {
// For each part in the message we're going to add a new BodyPart and parse into it.
val bp = MimeBodyPart()
val bodyPartId = (i + 1).toString()
if (id.equals("TEXT", ignoreCase = true)) {
parseBodyStructure(bs.getList(i), bp, bodyPartId)
} else {
parseBodyStructure(bs.getList(i), bp, "$id.$bodyPartId")
}
mp.addBodyPart(bp)
} else {
// We've got to the end of the children of the part, so now we can find out what type it is and
// bail out.
val subType = bs.getString(i)
mp.setSubType(subType.lowercase())
break
}
}
MimeMessageHelper.setBody(part, mp)
} else {
// This is a body. We need to add as much information as we can find out about it to the Part.
/*
* 0| 0 body type
* 1| 1 body subtype
* 2| 2 body parameter parenthesized list
* 3| 3 body id (unused)
* 4| 4 body description (unused)
* 5| 5 body encoding
* 6| 6 body size
* -| 7 text lines (only for type TEXT, unused)
* Extensions (optional):
* 7| 8 body MD5 (unused)
* 8| 9 body disposition
* 9|10 body language (unused)
* 10|11 body location (unused)
*/
val type = bs.getString(0)
val subType = bs.getString(1)
val mimeType = "$type/$subType".lowercase()
var bodyParams: ImapList? = null
if (bs[2] is ImapList) {
bodyParams = bs.getList(2)
}
val encoding = bs.getString(5)
val size = bs.getNumber(6)
if (MimeUtility.isMessage(mimeType)) {
// A body type of type MESSAGE and subtype RFC822
// contains, immediately after the basic fields, the
// envelope structure, body structure, and size in
// text lines of the encapsulated message.
// [MESSAGE, RFC822, [NAME, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory allocation - displayware.eml], NIL, NIL, 7BIT, 5974, NIL, [INLINE, [FILENAME*0, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory all, FILENAME*1, ocation - displayware.eml]], NIL]
/*
* This will be caught by fetch and handled appropriately.
*/
throw MessagingException("BODYSTRUCTURE message/rfc822 not yet supported.")
}
// Set the content type with as much information as we know right now.
val contentType = StringBuilder()
contentType.append(mimeType)
if (bodyParams != null) {
// If there are body params we might be able to get some more information out of them.
for (i in bodyParams.indices step 2) {
val paramName = bodyParams.getString(i)
val paramValue = bodyParams.getString(i + 1)
val encodedValue = if (paramValue.isToken()) paramValue else paramValue.quotedUtf8()
contentType.append(String.format(";\r\n %s=%s", paramName, encodedValue))
}
}
part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType.toString())
// Extension items
var bodyDisposition: ImapList? = null
if ("text".equals(type, ignoreCase = true) && bs.size > 9 && bs[9] is ImapList) {
bodyDisposition = bs.getList(9)
} else if (!"text".equals(type, ignoreCase = true) && bs.size > 8 && bs[8] is ImapList) {
bodyDisposition = bs.getList(8)
}
val contentDisposition = StringBuilder()
if (bodyDisposition != null && !bodyDisposition.isEmpty()) {
if (!"NIL".equals(bodyDisposition.getString(0), ignoreCase = true)) {
contentDisposition.append(bodyDisposition.getString(0).lowercase())
}
if (bodyDisposition.size > 1 && bodyDisposition[1] is ImapList) {
val bodyDispositionParams = bodyDisposition.getList(1)
// If there is body disposition information we can pull some more information
// about the attachment out.
for (i in bodyDispositionParams.indices step 2) {
val paramName = bodyDispositionParams.getString(i).lowercase()
val paramValue = bodyDispositionParams.getString(i + 1)
val encodedValue = if (paramValue.isToken()) paramValue else paramValue.quotedUtf8()
contentDisposition.append(String.format(";\r\n %s=%s", paramName, encodedValue))
}
}
}
if (MimeUtility.getHeaderParameter(contentDisposition.toString(), "size") == null) {
contentDisposition.append(String.format(Locale.US, ";\r\n size=%d", size))
}
// Set the content disposition containing at least the size. Attachment handling code will use this
// down the road.
part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, contentDisposition.toString())
// Set the Content-Transfer-Encoding header. Attachment code will use this to parse the body.
part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding)
if (part is ImapMessage) {
part.setSize(size)
}
part.serverExtra = id
}
}
/**
* Appends the given messages to the selected folder.
*
* This implementation also determines the new UIDs of the given messages on the IMAP
* server and changes the messages' UIDs to the new server UIDs.
*
* @param messages
* The messages to append to the folder.
*
* @return The mapping of original message UIDs to the new server UIDs.
*/
@Throws(MessagingException::class)
override fun appendMessages(messages: List<Message>): Map<String, String>? {
open(OpenMode.READ_WRITE)
checkOpen()
return try {
val uidMap: MutableMap<String, String> = HashMap()
for (message in messages) {
val messageSize = message.calculateSize()
val encodeFolderName = folderNameCodec.encode(prefixedName)
val escapedFolderName = ImapUtility.encodeString(encodeFolderName)
val combinedFlags = ImapUtility.combineFlags(
message.flags,
canCreateKeywords || internalImapStore.getPermanentFlagsIndex().contains(Flag.FORWARDED)
)
val command = String.format(
Locale.US, "APPEND %s (%s) {%d}",
escapedFolderName, combinedFlags, messageSize
)
connection!!.sendCommand(command, false)
var response: ImapResponse
do {
response = connection!!.readResponse()
handleUntaggedResponse(response)
if (response.isContinuationRequested) {
val eolOut = EOLConvertingOutputStream(connection!!.outputStream)
message.writeTo(eolOut)
eolOut.write('\r'.code)
eolOut.write('\n'.code)
eolOut.flush()
}
} while (response.tag == null)
if (response.size < 1 || !ImapResponseParser.equalsIgnoreCase(response[0], Responses.OK)) {
throw NegativeImapResponseException("APPEND failed", listOf(response))
} else if (response.size > 1) {
/*
* If the server supports UIDPLUS, then along with the APPEND response it
* will return an APPENDUID response code, e.g.
*
* 11 OK [APPENDUID 2 238268] APPEND completed
*
* We can use the UID included in this response to update our records.
*/
val appendList = response[1]
if (appendList is ImapList) {
if (appendList.size >= 3 && appendList.getString(0) == "APPENDUID") {
val newUid = appendList.getString(2)
if (newUid.isNotEmpty()) {
uidMap[message.uid] = newUid
message.uid = newUid
continue
}
}
}
}
// This part is executed in case the server does not support UIDPLUS or does not implement the
// APPENDUID response code.
val messageId = extractMessageId(message)
val newUid = messageId?.let { getUidFromMessageId(it) }
if (K9MailLib.isDebug()) {
Timber.d("Got UID %s for message for %s", newUid, logId)
}
newUid?.let {
uidMap[message.uid] = newUid
message.uid = newUid
}
}
// We need uidMap to be null if new UIDs are not available to maintain consistency with the behavior of
// other similar methods (copyMessages, moveMessages) which return null.
if (uidMap.isEmpty()) null else uidMap
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
private fun extractMessageId(message: Message): String? {
return message.getHeader("Message-ID").firstOrNull()
}
@Throws(MessagingException::class)
override fun getUidFromMessageId(messageId: String): String? {
if (K9MailLib.isDebug()) {
Timber.d("Looking for UID for message with message-id %s for %s", messageId, logId)
}
val command = String.format("UID SEARCH HEADER MESSAGE-ID %s", ImapUtility.encodeString(messageId))
val imapResponses = try {
executeSimpleCommand(command)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
val searchResponse = SearchResponse.parse(imapResponses)
return searchResponse.numbers.firstOrNull()?.toString()
}
@Throws(MessagingException::class)
override fun expunge() {
open(OpenMode.READ_WRITE)
checkOpen()
try {
executeSimpleCommand("EXPUNGE")
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
override fun expungeUids(uids: List<String>) {
require(uids.isNotEmpty()) { "expungeUids() must be called with a non-empty set of UIDs" }
open(OpenMode.READ_WRITE)
checkOpen()
try {
if (connection!!.isUidPlusCapable) {
val longUids = uids.map { it.toLong() }.toSet()
connection!!.executeCommandWithIdSet(Commands.UID_EXPUNGE, "", longUids)
} else {
executeSimpleCommand("EXPUNGE")
}
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
override fun setFlags(flags: Set<Flag>, value: Boolean) {
open(OpenMode.READ_WRITE)
checkOpen()
val canCreateForwardedFlag = canCreateKeywords || internalImapStore.getPermanentFlagsIndex().contains(Flag.FORWARDED)
try {
val combinedFlags = ImapUtility.combineFlags(flags, canCreateForwardedFlag)
val command = String.format(
"%s 1:* %sFLAGS.SILENT (%s)",
Commands.UID_STORE,
if (value) "+" else "-",
combinedFlags
)
executeSimpleCommand(command)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
override fun setFlags(messages: List<ImapMessage>, flags: Set<Flag>, value: Boolean) {
open(OpenMode.READ_WRITE)
checkOpen()
val uids = messages.map { it.uid.toLong() }.toSet()
val canCreateForwardedFlag = canCreateKeywords || internalImapStore.getPermanentFlagsIndex().contains(Flag.FORWARDED)
val combinedFlags = ImapUtility.combineFlags(flags, canCreateForwardedFlag)
val commandSuffix = String.format("%sFLAGS.SILENT (%s)", if (value) "+" else "-", combinedFlags)
try {
connection!!.executeCommandWithIdSet(Commands.UID_STORE, commandSuffix, uids)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
}
@Throws(MessagingException::class)
private fun checkOpen() {
if (!isOpen) {
throw MessagingException("Folder $prefixedName is not open.")
}
}
private fun ioExceptionHandler(connection: ImapConnection?, ioe: IOException): MessagingException {
Timber.e(ioe, "IOException for %s", logId)
connection?.close()
close()
return MessagingException("IO Error", ioe)
}
override fun equals(other: Any?): Boolean {
if (other is ImapFolder) {
return other.serverId == serverId
}
return super.equals(other)
}
override fun hashCode(): Int {
return serverId.hashCode()
}
private val logId: String
get() {
var id = internalImapStore.logLabel + ":" + serverId + "/" + Thread.currentThread().name
if (connection != null) {
id += "/" + connection!!.logId
}
return id
}
/**
* Search the remote ImapFolder.
*/
@Throws(MessagingException::class)
override fun search(
queryString: String?,
requiredFlags: Set<Flag>?,
forbiddenFlags: Set<Flag>?,
performFullTextSearch: Boolean
): List<ImapMessage> {
try {
open(OpenMode.READ_ONLY)
checkOpen()
inSearch = true
val searchCommand = UidSearchCommandBuilder()
.queryString(queryString)
.performFullTextSearch(performFullTextSearch)
.requiredFlags(requiredFlags)
.forbiddenFlags(forbiddenFlags)
.build()
try {
val imapResponses = executeSimpleCommand(searchCommand)
val searchResponse = SearchResponse.parse(imapResponses)
return getMessages(searchResponse, null)
} catch (ioe: IOException) {
throw ioExceptionHandler(connection, ioe)
}
} finally {
inSearch = false
}
}
companion object {
private const val MORE_MESSAGES_WINDOW_SIZE = 500
private const val FETCH_WINDOW_SIZE = 100
const val INBOX = "INBOX"
private val RFC3501_DATE: ThreadLocal<SimpleDateFormat> = object : ThreadLocal<SimpleDateFormat>() {
override fun initialValue(): SimpleDateFormat {
return SimpleDateFormat("dd-MMM-yyyy", Locale.US)
}
}
}
}
enum class OpenMode {
READ_WRITE,
READ_ONLY
}
| apache-2.0 | 1f506c6e70f584e30a34ea5cc8d6269f | 37.121087 | 291 | 0.55913 | 4.978913 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/bookmarks/items/BookmarkItemsAdapter.kt | 5 | 2102 | package fr.free.nrw.commons.bookmarks.items
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.view.SimpleDraweeView
import fr.free.nrw.commons.R
import fr.free.nrw.commons.explore.depictions.WikidataItemDetailsActivity
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
/**
* Helps to inflate Wikidata Items into Items tab
*/
class BookmarkItemsAdapter (val list: List<DepictedItem>, val context: Context) :
RecyclerView.Adapter<BookmarkItemsAdapter.BookmarkItemViewHolder>() {
class BookmarkItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var depictsLabel: TextView = itemView.findViewById(R.id.depicts_label)
var description: TextView = itemView.findViewById(R.id.description)
var depictsImage: SimpleDraweeView = itemView.findViewById(R.id.depicts_image)
var layout : ConstraintLayout = itemView.findViewById(R.id.layout_item)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookmarkItemViewHolder {
val v: View = LayoutInflater.from(context)
.inflate(R.layout.item_depictions, parent, false)
return BookmarkItemViewHolder(v)
}
override fun onBindViewHolder(holder: BookmarkItemViewHolder, position: Int) {
val depictedItem = list[position]
holder.depictsLabel.text = depictedItem.name
holder.description.text = depictedItem.description
if (depictedItem.imageUrl?.isNotBlank() == true) {
holder.depictsImage.setImageURI(depictedItem.imageUrl)
} else {
holder.depictsImage.setActualImageResource(R.drawable.ic_wikidata_logo_24dp)
}
holder.layout.setOnClickListener {
WikidataItemDetailsActivity.startYourself(context, depictedItem)
}
}
override fun getItemCount(): Int {
return list.size
}
} | apache-2.0 | 231b5d5427ef647ec5108be7655aeea1 | 37.944444 | 95 | 0.745005 | 4.609649 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/misc/TopBottomSpaceItemDecoration.kt | 1 | 1570 | package fr.geobert.efficio.misc
import android.graphics.Rect
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
class TopBottomSpaceItemDecoration constructor(private val space: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
super.getItemOffsets(outRect, view, parent, state)
if (space <= 0) {
return
}
if (parent.getChildLayoutPosition(view) < 1) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.top = space
outRect.bottom = 0
} else {
outRect.left = space
}
}
if (parent.getChildAdapterPosition(view) == getTotalItemCount(parent) - 1) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.top = 0
outRect.bottom = space
} else {
outRect.right = space
}
}
}
private fun getTotalItemCount(parent: RecyclerView): Int {
return parent.adapter.itemCount
}
private fun getOrientation(parent: RecyclerView): Int {
if (parent.layoutManager is LinearLayoutManager) {
return (parent.layoutManager as LinearLayoutManager).orientation
} else {
throw IllegalStateException("SpaceItemDecoration can only be used with a LinearLayoutManager.")
}
}
} | gpl-2.0 | 6f4748a7e71d6fc8e191dcfd864a8618 | 33.152174 | 110 | 0.626752 | 5.147541 | false | false | false | false |
luxons/seven-wonders | sw-server/src/test/kotlin/org/luxons/sevenwonders/server/lobby/LobbyTest.kt | 1 | 7711 | package org.luxons.sevenwonders.server.lobby
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.data.GameDefinition
import org.luxons.sevenwonders.model.Settings
import org.luxons.sevenwonders.model.api.State
import org.luxons.sevenwonders.server.lobby.Lobby.GameAlreadyStartedException
import org.luxons.sevenwonders.server.lobby.Lobby.PlayerListMismatchException
import org.luxons.sevenwonders.server.lobby.Lobby.PlayerNameAlreadyUsedException
import org.luxons.sevenwonders.server.lobby.Lobby.PlayerOverflowException
import org.luxons.sevenwonders.server.lobby.Lobby.PlayerUnderflowException
import org.luxons.sevenwonders.server.lobby.Lobby.UnknownPlayerException
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
@RunWith(Theories::class)
class LobbyTest {
private lateinit var gameOwner: Player
private lateinit var lobby: Lobby
@Before
fun setUp() {
gameOwner = Player("gameowner", "Game owner")
lobby = Lobby(42, "Test Game", gameOwner, gameDefinition)
}
@Test
fun testId() {
assertEquals(42, lobby.id)
}
@Test
fun testName() {
assertEquals("Test Game", lobby.name)
}
@Test
fun testOwner() {
assertSame(gameOwner, lobby.getPlayers()[0])
assertSame(lobby, gameOwner.lobby)
}
@Test
fun isOwner_falseWhenNull() {
assertFalse(lobby.isOwner(null))
}
@Test
fun isOwner_falseWhenEmptyString() {
assertFalse(lobby.isOwner(""))
}
@Test
fun isOwner_falseWhenGarbageString() {
assertFalse(lobby.isOwner("this is garbage"))
}
@Test
fun isOwner_trueWhenOwnerUsername() {
assertTrue(lobby.isOwner(gameOwner.username))
}
@Test
fun isOwner_falseWhenOtherPlayerName() {
val player = Player("testuser", "Test User")
lobby.addPlayer(player)
assertFalse(lobby.isOwner(player.username))
}
@Test
fun addPlayer_success() {
val player = Player("testuser", "Test User")
lobby.addPlayer(player)
assertTrue(lobby.containsUser("testuser"))
assertSame(lobby, player.lobby)
}
@Test
fun addPlayer_failsOnSameName() {
val player = Player("testuser", "Test User")
val player2 = Player("testuser2", "Test User")
lobby.addPlayer(player)
assertFailsWith<PlayerNameAlreadyUsedException> {
lobby.addPlayer(player2)
}
}
@Test
fun addPlayer_playerOverflowWhenTooMany() {
assertFailsWith<PlayerOverflowException> {
// the owner + the max number gives an overflow
addPlayers(gameDefinition.maxPlayers)
}
}
@Test
fun addPlayer_failWhenGameStarted() {
// total with owner is the minimum
addPlayers(gameDefinition.minPlayers - 1)
lobby.startGame()
assertFailsWith<GameAlreadyStartedException> {
lobby.addPlayer(Player("soonerNextTime", "The Late Guy"))
}
}
private fun addPlayers(nbPlayers: Int) {
repeat(nbPlayers) {
val player = Player("testuser$it", "Test User $it")
lobby.addPlayer(player)
}
}
@Test
fun removePlayer_failsWhenNotPresent() {
assertFailsWith<UnknownPlayerException> {
lobby.removePlayer("anyname")
}
}
@Test
fun removePlayer_success() {
val player = Player("testuser", "Test User")
lobby.addPlayer(player)
assertTrue(player.isInLobby)
assertFalse(player.isInGame)
lobby.removePlayer("testuser")
assertFalse(lobby.containsUser("testuser"))
assertFalse(player.isInLobby)
assertFalse(player.isInGame)
}
@Test
fun reorderPlayers_success() {
val player1 = Player("testuser1", "Test User 1")
val player2 = Player("testuser2", "Test User 2")
val player3 = Player("testuser3", "Test User 3")
lobby.addPlayer(player1)
lobby.addPlayer(player2)
lobby.addPlayer(player3)
val reorderedUsernames = listOf("testuser3", "gameowner", "testuser1", "testuser2")
lobby.reorderPlayers(reorderedUsernames)
assertEquals(reorderedUsernames, lobby.getPlayers().map { it.username })
}
@Test
fun reorderPlayers_failsOnUnknownPlayer() {
val player1 = Player("testuser1", "Test User 1")
val player2 = Player("testuser2", "Test User 2")
lobby.addPlayer(player1)
lobby.addPlayer(player2)
assertFailsWith<PlayerListMismatchException> {
lobby.reorderPlayers(listOf("unknown", "testuser2", "gameowner"))
}
}
@Test
fun reorderPlayers_failsOnExtraPlayer() {
val player1 = Player("testuser1", "Test User 1")
val player2 = Player("testuser2", "Test User 2")
lobby.addPlayer(player1)
lobby.addPlayer(player2)
assertFailsWith<PlayerListMismatchException> {
lobby.reorderPlayers(listOf("testuser2", "onemore", "testuser1", "gameowner"))
}
}
@Test
fun reorderPlayers_failsOnMissingPlayer() {
val player1 = Player("testuser1", "Test User 1")
val player2 = Player("testuser2", "Test User 2")
lobby.addPlayer(player1)
lobby.addPlayer(player2)
assertFailsWith<PlayerListMismatchException> {
lobby.reorderPlayers(listOf("testuser2", "gameowner"))
}
}
@Theory
fun startGame_failsBelowMinPlayers(nbPlayers: Int) {
assumeTrue(nbPlayers < gameDefinition.minPlayers)
// there is already the owner
addPlayers(nbPlayers - 1)
assertFailsWith<PlayerUnderflowException> {
lobby.startGame()
}
}
@Theory
fun startGame_succeedsAboveMinPlayers(nbPlayers: Int) {
assumeTrue(nbPlayers >= gameDefinition.minPlayers)
assumeTrue(nbPlayers <= gameDefinition.maxPlayers)
// there is already the owner
addPlayers(nbPlayers - 1)
assertEquals(nbPlayers, lobby.getPlayers().size)
lobby.getPlayers().forEach {
assertSame(lobby, it.lobby)
assertTrue(it.isInLobby)
assertFalse(it.isInGame)
}
val game = lobby.startGame()
assertNotNull(game)
lobby.getPlayers().forEachIndexed { index, it ->
assertSame(index, it.index)
assertSame(lobby, it.lobby)
assertSame(game, it.game)
assertTrue(it.isInLobby)
assertTrue(it.isInGame)
}
}
@Test
fun startGame_switchesState() {
assertEquals(State.LOBBY, lobby.state)
// there is already the owner
addPlayers(gameDefinition.minPlayers - 1)
lobby.startGame()
assertEquals(State.PLAYING, lobby.state)
}
@Test
fun setSettings() {
val settings = Settings()
lobby.settings = settings
assertSame(settings, lobby.settings)
}
companion object {
private lateinit var gameDefinition: GameDefinition
@JvmStatic
@DataPoints
fun nbPlayers(): IntArray = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
@JvmStatic
@BeforeClass
fun loadDefinition() {
gameDefinition = GameDefinition.load()
}
}
}
| mit | 8473a8dbc0ebd7dea95b2fa0b6b61847 | 28.208333 | 91 | 0.650888 | 4.341779 | false | true | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/intentions/WrapLambdaExprIntention.kt | 1 | 1635 | package org.rust.ide.intentions
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.util.parentOfType
class WrapLambdaExprIntention : PsiElementBaseIntentionAction() {
override fun getText() = "Add braces to lambda expression"
override fun getFamilyName() = text
override fun startInWriteAction() = true
private data class Context(
val lambdaExprBody: RustExprElement
)
private fun findContext(element: PsiElement): Context? {
if (!element.isWritable) return null
val lambdaExpr = element.parentOfType<RustLambdaExprElement>() ?: return null
val body = lambdaExpr.expr ?: return null
return if (body !is RustBlockExprElement) Context(body) else null
}
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
val ctx = findContext(element) ?: return
val lambdaBody = ctx.lambdaExprBody
val relativeCaretPosition = editor.caretModel.offset - lambdaBody.textOffset
val bodyStr = "\n${lambdaBody.text}\n"
val blockExpr = RustPsiFactory(project).createBlockExpr(bodyStr)
val offset = ((lambdaBody.replace(blockExpr)) as RustBlockExprElement).block?.expr?.textOffset ?: return
editor.caretModel.moveToOffset(offset + relativeCaretPosition)
}
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean =
findContext(element) != null
}
| mit | 4ba2484cf72d31be3f8096d24df5b0cb | 38.878049 | 112 | 0.732722 | 4.725434 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/impl/RustTextLiteralImplBase.kt | 1 | 1096 | package org.rust.lang.core.psi.impl
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.tree.IElementType
import org.rust.lang.core.psi.RustLiteral
import org.rust.lang.core.psi.visitors.RustVisitorEx
abstract class RustTextLiteralImplBase(type: IElementType, text: CharSequence) : RustLiteral.Text(type, text) {
override val possibleSuffixes: Collection<String>
get() = emptyList()
override val hasUnpairedQuotes: Boolean
get() = offsets.openDelim == null || offsets.closeDelim == null
override fun accept(visitor: PsiElementVisitor) = when (visitor) {
is RustVisitorEx -> visitor.visitTextLiteral(this)
else -> super.accept(visitor)
}
protected fun locatePrefix(): Int {
text.forEachIndexed { i, ch ->
if (!ch.isLetter()) {
return i
}
}
return textLength
}
protected inline fun doLocate(start: Int, locator: (Int) -> Int): Int =
if (start >= textLength) {
start
} else {
locator(start)
}
}
| mit | 91f4768119a4362fb1a466e6508add79 | 30.314286 | 111 | 0.633212 | 4.23166 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SonarImporter/src/test/kotlin/de/maibornwolff/codecharta/importer/sonar/dataaccess/AuthentificationHandlerTest.kt | 1 | 897 | package de.maibornwolff.codecharta.importer.sonar.dataaccess
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.junit.Test
class AuthentificationHandlerTest {
@Test
@Throws(Exception::class)
fun createAuthWithPassword() {
val password = "password"
val expectedEncodedString = "dXNlcjpwYXNzd29yZA=="
val encodedString = AuthentificationHandler.createAuthTxtBase64Encoded(USERNAME, password)
assertThat(encodedString, `is`(expectedEncodedString))
}
@Test
@Throws(Exception::class)
fun createAuthWithoutPassword() {
val expectedEncodedString = "dXNlcjo="
val encodedString = AuthentificationHandler.createAuthTxtBase64Encoded(USERNAME)
assertThat(encodedString, `is`(expectedEncodedString))
}
companion object {
private const val USERNAME = "user"
}
}
| bsd-3-clause | e79950730d667e3ce642697009a32996 | 29.931034 | 98 | 0.726867 | 4.333333 | false | true | false | false |
MaibornWolff/codecharta | analysis/import/SonarImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/sonar/SonarMetricTranslatorFactory.kt | 1 | 1043 | package de.maibornwolff.codecharta.importer.sonar
import de.maibornwolff.codecharta.translator.MetricNameTranslator
internal object SonarMetricTranslatorFactory {
fun createMetricTranslator(): MetricNameTranslator {
val prefix = "sonar_"
val replacementMap = mutableMapOf<String, String>()
replacementMap["accessors"] = "accessors"
replacementMap["commented_out_code_lines"] = "commented_out_loc"
replacementMap["comment_lines"] = "comment_lines"
replacementMap["complexity"] = "mcc"
replacementMap["function_complexity"] = "average_function_mcc"
replacementMap["branch_coverage"] = "branch_coverage"
replacementMap["functions"] = "functions"
replacementMap["line_coverage"] = "line_coverage"
replacementMap["lines"] = "loc"
replacementMap["ncloc"] = "rloc"
replacementMap["public_api"] = "public_api"
replacementMap["statements"] = "statements"
return MetricNameTranslator(replacementMap.toMap(), prefix)
}
}
| bsd-3-clause | 973d9b54c66bc413e720b9b35c962f61 | 39.115385 | 72 | 0.68744 | 4.762557 | false | false | false | false |
agilie/SwipeToDelete | swipe2delete/src/main/java/com/agilie/swipe2delete/AnimationInitiator.kt | 1 | 1903 | package com.agilie.swipe2delete
import android.animation.Animator
import android.animation.ValueAnimator
import com.agilie.swipe2delete.interfaces.IAnimationUpdateListener
import com.agilie.swipe2delete.interfaces.IAnimatorListener
var rowWidth: Int = 0
internal fun initAnimator(options: ModelOptions<*>, animatorListener: IAnimatorListener? = null,
valUpdateListener: IAnimationUpdateListener? = null, valueAnimator: ValueAnimator? = null): ValueAnimator {
val animator: ValueAnimator
val screenWidth = rowWidth
if (valueAnimator == null) animator = ValueAnimator.ofFloat(options.posX, screenWidth * options.direction!!.toFloat())
else {
animator = valueAnimator
animator.removeAllUpdateListeners()
animator.removeAllListeners()
animator.setFloatValues(options.posX, screenWidth * options.direction!!.toFloat())
}
animator.addUpdateListener { animation -> valUpdateListener?.onAnimationUpdated(animation, options) }
animator.addListener((object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
options.runningAnimation = true
animatorListener?.onAnimationStart(animation, options)
}
override fun onAnimationEnd(animation: Animator) {
options.runningAnimation = false
animatorListener?.onAnimationEnd(animation, options)
}
override fun onAnimationCancel(animation: Animator) {
clearOptions(options)
animatorListener?.onAnimationCancel(animation, options)
}
override fun onAnimationRepeat(animation: Animator) {
animatorListener?.onAnimationRepeat(animation, options)
}
}))
animator.duration = (options.deletingDuration * (screenWidth - options.posX * options.direction!!.toFloat()) / screenWidth).toLong()
return animator
} | mit | 3da554fbe32d118a1c380e95a4db8baa | 40.391304 | 136 | 0.71939 | 5.375706 | false | false | false | false |
Ribesg/Pure | src/main/kotlin/fr/ribesg/minecraft/pure/common/MCVersion.kt | 1 | 7840 | package fr.ribesg.minecraft.pure.common
import org.bukkit.World.Environment
import org.bukkit.generator.ChunkGenerator
import java.net.MalformedURLException
import java.net.URL
/**
* Lists Minecraft versions, with hashes of and links to their jar files.
*
* @author Ribesg
*/
internal enum class MCVersion {
/**
* Minecraft Alpha 1.2.6 (2010-12-03)
*
* Server version 0.2.8
*/
A0_2_8(
"29BB180262250235131FB53F12D61F438D008620E1B428E372DBADEC731F5E09",
"EBE3CF77CA4E7E3BE45A8B319AB9FE27CD51EEF734DD5CC16C763EE7A91526E8",
"http://files.ribesg.fr/minecraft_server.jar/minecraft_server.a0.2.8.jar",
fr.ribesg.minecraft.pure.vanilla.a0_2_8.ProxyChunkGenerator::class.java
),
/**
* Minecraft Beta 1.7.3 (2011-07-08)
*/
B1_7_3(
"033A127E4A25A60B038F15369C89305A3D53752242A1CFF11AE964954E79BA4D",
"AFF8849A9B625552045544925E578E70E0567BC5ED88834BE95DD8D9AC1F22B2",
"http://files.ribesg.fr/minecraft_server.jar/minecraft_server.b1.7.3.jar",
null
),
/**
* Minecraft 1.2.5 (2012-03-29) TODO
*/
R1_2_5(
"19285D7D16AEE740F5A0584F0D80A4940F273A97F5A3EAF251FC1C6C3F2982D1",
"11BDC22C2CF6785774B09A29BE5743BC9597DE9343BE20262B49C0AC00979D72",
"https://s3.amazonaws.com/Minecraft.Download/versions/1.2.5/minecraft_server.1.2.5.jar",
null
),
/**
* Minecraft 1.3.2 (2012-08-15) TODO
*/
R1_3_2(
"0795E098D970B459832750D4C6C2C4F58EF55A333A67281418318275E6026EBA",
"0C68314039E8A55B0ACFBDC10B69A1E5B116229CC255B78BD1EF04F0FE4CA6DE",
"https://s3.amazonaws.com/Minecraft.Download/versions/1.3.2/minecraft_server.1.3.2.jar",
null
),
/**
* Minecraft 1.4.7 (2012-12-27) TODO
*/
R1_4_7(
"96B7512AEAD2FB20DDF780D7DD74208D77F209E16058EA8944150179E65B4DD3",
"0A9F5D2CAF06C85A383772BE2C01E6289690555483AC3BAB1DD2F78F75D124C6",
"https://s3.amazonaws.com/Minecraft.Download/versions/1.4.7/minecraft_server.1.4.7.jar",
null
),
/**
* Minecraft 1.5.2 (2013-04-25) TODO
*/
R1_5_2(
"4F0C7B79CA2B10716703436550F75FA14E784B999707FFAD0EA4E9C38CC256A0",
"9AA1E33A276EC2EAC6E377679EDF1F9728E10CDBCD01EE91FFECCA773E13C13D",
"https://s3.amazonaws.com/Minecraft.Download/versions/1.5.2/minecraft_server.1.5.2.jar",
null
),
/**
* Minecraft 1.6.4 (2013-09-19)
*/
R1_6_4(
"81841A2FEDFE0CE19983156A06FA5294335284BEEB95C8CA872D3C1A5FCF5774",
"B5F598584EE44B592D35856332495850B6083CE11F4F6928B4F078E14F23FB53",
"https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar",
fr.ribesg.minecraft.pure.vanilla.r1_6_4.ProxyChunkGenerator::class.java
),
/**
* Minecraft 1.7.10 (2014-06-26)
*/
R1_7_10(
"C70870F00C4024D829E154F7E5F4E885B02DD87991726A3308D81F513972F3FC",
"AC886902C6357289ED76D651F03380ABC1835EFFB6953058202191A1E2BAC9DC",
"http://s3.amazonaws.com/Minecraft.Download/versions/1.7.10/minecraft_server.1.7.10.jar",
fr.ribesg.minecraft.pure.vanilla.r1_7_10.ProxyChunkGenerator::class.java
),
/**
* Minecraft 1.8 (2014-09-02)
*/
R1_8(
"40E23F3823D6F0E3CBADC491CEDB55B8BA53F8AB516B68182DDD1536BABEB291",
"950C597411A970CC3FCC59E3B04EDE6FCA78BB07D542BD56F077C85E9D45B0B8",
"http://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar",
fr.ribesg.minecraft.pure.vanilla.r1_8.ProxyChunkGenerator::class.java
),
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */;
/**
* Vanilla jar hash (SHA-256)
*/
private val vanillaHash: String
/**
* Remapped jar hash (SHA-256)
*/
private val remappedHash: String
/**
* Jar location
*/
private val url: URL
/**
* Proxy ChunkGenerator class
*/
private val chunkGeneratorClass: Class<out ChunkGenerator>?
/**
* Builds a MCVersion enum value.
*
* @param vanillaHash the vanilla jar hash (SHA-256)
* @param remappedHash the remapped jar hash (SHA-256)
* @param url the jar location
* @param chunkGeneratorClass the class of the associated {@link ChunkGenerator}
*/
private constructor(
vanillaHash: String,
remappedHash: String,
url: String,
chunkGeneratorClass: Class<out ChunkGenerator>?
) {
this.vanillaHash = vanillaHash
this.remappedHash = remappedHash
this.url = try {
URL(url)
} catch (e: MalformedURLException) {
throw IllegalArgumentException(e)
}
this.chunkGeneratorClass = chunkGeneratorClass
}
/**
* Gets the vanilla jar hash (SHA-256).
*
* @return the vanilla jar hash (SHA-256)
*/
fun getVanillaHash(): String = this.vanillaHash
/**
* Gets the remapped jar hash (SHA-256).
*
* @return the remapped jar hash (SHA-256)
*/
fun getRemappedHash(): String = this.remappedHash
/**
* Gets the URL.
*
* @return the URL
*/
fun getUrl(): URL = this.url
/**
* Gets a new instance of a Chunk Generator matching this version.
*
* @param environment the required environment
*
* @return the Chunk Generator instance
*/
fun getChunkGenerator(environment: Environment?): ChunkGenerator = try {
try {
this.chunkGeneratorClass?.getDeclaredConstructor(Environment::class.java)!!.newInstance(environment)
} catch (ex: NoSuchMethodException) {
try {
if (environment != null) {
Log.warn("Ignored environment parameter for MC version " + this)
}
this.chunkGeneratorClass?.getDeclaredConstructor()!!.newInstance()
} catch (ex: NoSuchMethodException) {
throw RuntimeException("Associated proxy ChunkGenerator class has no valid constructor ("
+ this.chunkGeneratorClass?.canonicalName + ')')
}
}
} catch (e: ReflectiveOperationException) {
throw RuntimeException("Failed to call associated proxy ChunkGenerator class constructor")
} catch (e: NullPointerException) {
throw IllegalStateException("Generator for Minecraft version " + this + " is not implemented yet.", e)
}
companion object {
fun get(string: String): MCVersion? = try {
MCVersion.valueOf(string.toUpperCase())
} catch (e: IllegalArgumentException) {
Log.error("Invalid MC version String: " + string.toUpperCase())
this.suggestVersionString(string.toUpperCase())
null
}
private fun suggestVersionString(version: String) {
val withUnderscores = version.replace(".", "_")
try {
MCVersion.valueOf(withUnderscores)
Log.info("Did you mean '$withUnderscores'?")
} catch (ignored: IllegalArgumentException) {
when (withUnderscores) {
"A1_2_6" ->
Log.info("You have to provide SERVER version, for Alpha 1.2.6 the correct version is 'A0_2_8'")
else ->
Log.info("Find a list of all available versions on https://github.com/Ribesg/Pure !")
}
}
}
}
}
| gpl-3.0 | 78a1ce789e5631fc6b670822a2d43b5e | 33.690265 | 119 | 0.601786 | 3.386609 | false | false | false | false |
toastkidjp/Jitte | todo/src/main/java/jp/toastkid/todo/view/item/menu/ItemMenuPopup.kt | 1 | 2098 | /*
* Copyright (c) 2019 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.todo.view.item.menu
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import androidx.annotation.DimenRes
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import jp.toastkid.todo.R
import jp.toastkid.todo.databinding.PopupTodoTasksItemMenuBinding
import jp.toastkid.todo.model.TodoTask
/**
*
* @param context Use for obtaining [PopupWindow]
* @param action [ItemMenuPopupActionUseCase]
* @author toastkidjp
*/
class ItemMenuPopup(context: Context, private val action: ItemMenuPopupActionUseCase) {
private val popupWindow = PopupWindow(context)
private val binding: PopupTodoTasksItemMenuBinding = DataBindingUtil.inflate(
LayoutInflater.from(context),
LAYOUT_ID,
null,
false
)
private var lastTask: TodoTask? = null
init {
popupWindow.contentView = binding.root
popupWindow.isOutsideTouchable = true
popupWindow.width = context.resources.getDimensionPixelSize(WIDTH)
popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT
binding.popup = this
}
fun show(view: View, item: TodoTask) {
lastTask = item
popupWindow.showAsDropDown(view)
}
fun modify() {
lastTask?.let {
action.modify(it)
}
popupWindow.dismiss()
}
fun delete() {
lastTask?.let {
action.delete(it)
}
popupWindow.dismiss()
}
companion object {
@LayoutRes
private val LAYOUT_ID = R.layout.popup_todo_tasks_item_menu
@DimenRes
private val WIDTH = R.dimen.item_menu_popup_width
}
} | epl-1.0 | 36843e224ef2e9e87c9fa12b8ded7c74 | 25.910256 | 88 | 0.693994 | 4.502146 | false | false | false | false |
toastkidjp/Jitte | lib/src/main/java/jp/toastkid/lib/image/ImageStoreService.kt | 1 | 1772 | /*
* 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.lib.image
import android.graphics.Bitmap
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.storage.StorageWrapper
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.util.UUID
/**
* @author toastkidjp
*/
class ImageStoreService(
private val filesDir: StorageWrapper,
private val preferenceApplier: PreferenceApplier,
private val bitmapScaling: BitmapScaling = BitmapScaling()
) {
/**
* Store image file.
*
* @param image
* @param uri
* @param displaySize
*
* @throws FileNotFoundException
*/
@Throws(FileNotFoundException::class)
operator fun invoke(image: Bitmap, uri: Uri, displaySize: Rect) {
val output = filesDir.assignNewFile(uri.lastPathSegment ?: UUID.randomUUID().toString())
preferenceApplier.backgroundImagePath = output.path
val fileOutputStream = FileOutputStream(output)
val compressFormat = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Bitmap.CompressFormat.WEBP_LOSSLESS
} else {
@Suppress("DEPRECATION")
Bitmap.CompressFormat.WEBP
}
bitmapScaling(image, displaySize.width().toDouble(), displaySize.height().toDouble())
.compress(compressFormat, 100, fileOutputStream)
fileOutputStream.close()
}
} | epl-1.0 | b3502c740f22674b983ef70175ecc759 | 31.236364 | 96 | 0.707675 | 4.54359 | false | false | false | false |
outersky/ystore | ystore-lib/src/main/java/db.kt | 1 | 2660 | package com.ystore.lib.db
import com.mchange.v2.c3p0.*
import java.sql.Connection
import com.ystore.lib.config.*
import com.ystore.lib.log.*
import com.avaje.ebean.Ebean
object Db {
fun createDs(cfg:IConfig):ComboPooledDataSource{
assert(cfg.getString("databaseUrl")!=null)
assert(cfg.getString("databaseDriver")!=null)
println(cfg.getString("databaseUrl"))
println(cfg.getString("databaseDriver"))
Class.forName(cfg.getString("databaseDriver")!!)
val ds = ComboPooledDataSource()
ds.setDriverClass(cfg.getString("databaseDriver"))
ds.setUser(cfg.getString("username"))
ds.setPassword(cfg.getString("password"))
ds.setJdbcUrl(cfg.getString("databaseUrl"))
return ds
}
fun <T> tx(f:()->T):T{
Ebean.beginTransaction()
var result:T
try{
result = f()
Ebean.commitTransaction()
return result
}catch(e:Exception){
Ebean.rollbackTransaction()
throw e
}finally{
Ebean.endTransaction()
}
}
fun save(c:Collection<*>){
Ebean.save(c)
}
fun save(c:Any){
Ebean.save(c)
}
}
data class Column(val name:String, val clazz:Class<Any>)
class Table {
private val log = Log.find(javaClass<Table>())
class object{
fun inspect(conn:Connection,name:String){
val stmt = conn.createStatement()!!
val rs = stmt.executeQuery("select * from ${name} where 1=2")
val tablemeta = rs.getMetaData()
for (i in 1..tablemeta.getColumnCount()) {
print("${tablemeta.getTableName(i)}.${tablemeta.getColumnName(i)}:${tablemeta.getColumnClassName(i)}")
println(" ${tablemeta.getColumnTypeName(i)}(${tablemeta.getPrecision(i)},${tablemeta.getScale(i)})")
}
}
}
fun t(){
log.debug("table")
}
}
/*
fun main(args:Array<String>){
println("hi")
val cfg = Config.getDefault()
//val cfg = Config.getDefault()
val conn = Db.createDs(cfg.sub("db.visitor")).getConnection()!!
val dbmeta = conn.getMetaData()!!
println( "Db: ${dbmeta.getDatabaseProductName()}, Version: ${dbmeta.getDatabaseProductVersion()} ")
Table.inspect(conn,"login_user")
//
// val stmt = conn.createStatement()!!
// val rs = stmt.executeQuery("select * from login_user where 1=2")!!
// val tablemeta = rs.getMetaData()!!
// for (i in 1..tablemeta.getColumnCount()) {
// println("${tablemeta.getTableName(i)}.${tablemeta.getColumnName(i)}:${tablemeta.getColumnClassName(i)}")
// }
}*/
| mit | d8c5ca5d56ad962da7aa272da6952254 | 28.230769 | 118 | 0.604887 | 3.871907 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/store/SiteStoreTest.kt | 1 | 12667 | package org.wordpress.android.fluxc.store
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.PostFormatModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.SitesModel
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.PARSE_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response
import org.wordpress.android.fluxc.network.rest.wpcom.site.DomainsResponse
import org.wordpress.android.fluxc.network.rest.wpcom.site.PrivateAtomicCookie
import org.wordpress.android.fluxc.network.rest.wpcom.site.SiteRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.site.SiteRestClient.NewSiteResponsePayload
import org.wordpress.android.fluxc.network.xmlrpc.site.SiteXMLRPCClient
import org.wordpress.android.fluxc.persistence.PostSqlUtils
import org.wordpress.android.fluxc.persistence.SiteSqlUtils
import org.wordpress.android.fluxc.store.SiteStore.FetchSitesPayload
import org.wordpress.android.fluxc.store.SiteStore.FetchedPostFormatsPayload
import org.wordpress.android.fluxc.store.SiteStore.NewSiteError
import org.wordpress.android.fluxc.store.SiteStore.NewSiteErrorType.SITE_NAME_INVALID
import org.wordpress.android.fluxc.store.SiteStore.NewSitePayload
import org.wordpress.android.fluxc.store.SiteStore.OnPostFormatsChanged
import org.wordpress.android.fluxc.store.SiteStore.PostFormatsError
import org.wordpress.android.fluxc.store.SiteStore.PostFormatsErrorType.INVALID_SITE
import org.wordpress.android.fluxc.store.SiteStore.SiteError
import org.wordpress.android.fluxc.store.SiteStore.SiteErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.SiteStore.SiteFilter.WPCOM
import org.wordpress.android.fluxc.store.SiteStore.SiteVisibility.PUBLIC
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
@RunWith(MockitoJUnitRunner::class)
class SiteStoreTest {
@Mock lateinit var dispatcher: Dispatcher
@Mock lateinit var postSqlUtils: PostSqlUtils
@Mock lateinit var siteRestClient: SiteRestClient
@Mock lateinit var siteXMLRPCClient: SiteXMLRPCClient
@Mock lateinit var privateAtomicCookie: PrivateAtomicCookie
@Mock lateinit var siteSqlUtils: SiteSqlUtils
@Mock lateinit var successResponse: Response.Success<DomainsResponse>
@Mock lateinit var errorResponse: Response.Error<DomainsResponse>
private lateinit var siteStore: SiteStore
@Before
fun setUp() {
siteStore = SiteStore(
dispatcher,
postSqlUtils,
siteRestClient,
siteXMLRPCClient,
privateAtomicCookie,
siteSqlUtils,
initCoroutineEngine()
)
}
@Test
fun `fetchSite from WPCom endpoint and stores it to DB`() = test {
val site = SiteModel()
site.setIsWPCom(true)
val updatedSite = SiteModel()
whenever(siteRestClient.fetchSite(site)).thenReturn(updatedSite)
assertSiteFetched(updatedSite, site)
}
@Test
fun `fetchSite error from WPCom endpoint returns error`() = test {
val site = SiteModel()
site.setIsWPCom(true)
val errorSite = SiteModel()
errorSite.error = BaseNetworkError(PARSE_ERROR)
whenever(siteRestClient.fetchSite(site)).thenReturn(errorSite)
assertSiteFetchError(site)
}
@Test
fun `fetchSite from XMLRPC endpoint and stores it to DB`() = test {
val site = SiteModel()
site.setIsWPCom(false)
val updatedSite = SiteModel()
whenever(siteXMLRPCClient.fetchSite(site)).thenReturn(updatedSite)
assertSiteFetched(updatedSite, site)
}
@Test
fun `fetchSite error from XMLRPC endpoint returns error`() = test {
val site = SiteModel()
site.setIsWPCom(false)
val errorSite = SiteModel()
errorSite.error = BaseNetworkError(PARSE_ERROR)
whenever(siteXMLRPCClient.fetchSite(site)).thenReturn(errorSite)
assertSiteFetchError(site)
}
private suspend fun assertSiteFetchError(site: SiteModel) {
val onSiteChanged = siteStore.fetchSite(site)
assertThat(onSiteChanged.rowsAffected).isEqualTo(0)
assertThat(onSiteChanged.error).isEqualTo(SiteError(GENERIC_ERROR, null))
verifyNoInteractions(siteSqlUtils)
}
private suspend fun assertSiteFetched(
updatedSite: SiteModel,
site: SiteModel
) {
val rowsChanged = 1
whenever(siteSqlUtils.insertOrUpdateSite(updatedSite)).thenReturn(rowsChanged)
val onSiteChanged = siteStore.fetchSite(site)
assertThat(onSiteChanged.rowsAffected).isEqualTo(rowsChanged)
assertThat(onSiteChanged.error).isNull()
verify(siteSqlUtils).insertOrUpdateSite(updatedSite)
}
@Test
fun `fetchSites saves fetched sites to DB and removes absent sites`() = test {
val payload = FetchSitesPayload(listOf(WPCOM))
val sitesModel = SitesModel()
val siteA = SiteModel()
val siteB = SiteModel()
sitesModel.sites = listOf(siteA, siteB)
whenever(siteRestClient.fetchSites(payload.filters, false)).thenReturn(sitesModel)
whenever(siteSqlUtils.insertOrUpdateSite(siteA)).thenReturn(1)
whenever(siteSqlUtils.insertOrUpdateSite(siteB)).thenReturn(1)
val onSiteChanged = siteStore.fetchSites(payload)
assertThat(onSiteChanged.rowsAffected).isEqualTo(2)
assertThat(onSiteChanged.error).isNull()
val inOrder = inOrder(siteSqlUtils)
inOrder.verify(siteSqlUtils).insertOrUpdateSite(siteA)
inOrder.verify(siteSqlUtils).insertOrUpdateSite(siteB)
inOrder.verify(siteSqlUtils).removeWPComRestSitesAbsentFromList(postSqlUtils, sitesModel.sites)
}
@Test
fun `fetchSites returns error`() = test {
val payload = FetchSitesPayload(listOf(WPCOM))
val sitesModel = SitesModel()
sitesModel.error = BaseNetworkError(PARSE_ERROR)
whenever(siteRestClient.fetchSites(payload.filters, false)).thenReturn(sitesModel)
val onSiteChanged = siteStore.fetchSites(payload)
assertThat(onSiteChanged.rowsAffected).isEqualTo(0)
assertThat(onSiteChanged.error).isEqualTo(SiteError(GENERIC_ERROR, null))
verifyNoInteractions(siteSqlUtils)
}
@Test
fun `creates a new site`() = test {
val dryRun = false
val payload = NewSitePayload("New site", "CZ", "Europe/London", PUBLIC, dryRun)
val newSiteRemoteId: Long = 123
val response = NewSiteResponsePayload(newSiteRemoteId, dryRun = dryRun)
whenever(
siteRestClient.newSite(
payload.siteName,
null,
payload.language,
payload.timeZoneId,
payload.visibility,
null,
null,
payload.dryRun
)
).thenReturn(response)
val result = siteStore.createNewSite(payload)
assertThat(result.dryRun).isEqualTo(dryRun)
assertThat(result.newSiteRemoteId).isEqualTo(newSiteRemoteId)
}
@Test
fun `fails to create a new site`() = test {
val dryRun = false
val payload = NewSitePayload("New site", "CZ", "Europe/London", PUBLIC, dryRun)
val response = NewSiteResponsePayload()
val newSiteError = NewSiteError(SITE_NAME_INVALID, "Site name invalid")
response.error = newSiteError
whenever(
siteRestClient.newSite(
payload.siteName,
null,
payload.language,
payload.timeZoneId,
payload.visibility,
null,
null,
payload.dryRun
)
).thenReturn(response)
val result = siteStore.createNewSite(payload)
assertThat(result.dryRun).isEqualTo(dryRun)
assertThat(result.newSiteRemoteId).isEqualTo(0)
assertThat(result.error).isEqualTo(newSiteError)
}
@Test
fun `fetches post formats for WPCom site`() = test {
val site = SiteModel()
site.setIsWPCom(true)
val postFormatModel = PostFormatModel(123)
postFormatModel.slug = "Slug"
postFormatModel.displayName = "Display name"
postFormatModel.siteId = 123
val postFormats = listOf(
postFormatModel
)
val payload = FetchedPostFormatsPayload(site, postFormats)
whenever(siteRestClient.fetchPostFormats(site)).thenReturn(payload)
assertPostFormatsFetched(site, payload)
}
@Test
fun `fetches post formats for XMLRPC site`() = test {
val site = SiteModel()
site.setIsWPCom(false)
val postFormatModel = PostFormatModel(123)
postFormatModel.slug = "Slug"
postFormatModel.displayName = "Display name"
postFormatModel.siteId = 123
val postFormats = listOf(
postFormatModel
)
val payload = FetchedPostFormatsPayload(site, postFormats)
whenever(siteXMLRPCClient.fetchPostFormats(site)).thenReturn(payload)
assertPostFormatsFetched(site, payload)
}
private suspend fun assertPostFormatsFetched(
site: SiteModel,
payload: FetchedPostFormatsPayload
) {
val onPostFormatsChanged: OnPostFormatsChanged = siteStore.fetchPostFormats(site)
assertThat(onPostFormatsChanged.site).isEqualTo(site)
assertThat(onPostFormatsChanged.error).isNull()
verify(siteSqlUtils).insertOrReplacePostFormats(payload.site, payload.postFormats)
}
@Test
fun `fails to fetch post formats for WPCom site`() = test {
val site = SiteModel()
site.setIsWPCom(true)
val payload = FetchedPostFormatsPayload(site, emptyList())
payload.error = PostFormatsError(INVALID_SITE, "Invalid site")
whenever(siteRestClient.fetchPostFormats(site)).thenReturn(payload)
assertPostFormatsFetchFailed(site, payload)
}
@Test
fun `fails to fetch post formats from XMLRPC`() = test {
val site = SiteModel()
site.setIsWPCom(false)
val payload = FetchedPostFormatsPayload(site, emptyList())
payload.error = PostFormatsError(INVALID_SITE, "Invalid site")
whenever(siteXMLRPCClient.fetchPostFormats(site)).thenReturn(payload)
assertPostFormatsFetchFailed(site, payload)
}
private suspend fun assertPostFormatsFetchFailed(
site: SiteModel,
payload: FetchedPostFormatsPayload
) {
val onPostFormatsChanged: OnPostFormatsChanged = siteStore.fetchPostFormats(site)
assertThat(onPostFormatsChanged.site).isEqualTo(site)
assertThat(onPostFormatsChanged.error).isEqualTo(payload.error)
verifyNoInteractions(siteSqlUtils)
}
@Test
fun `fetchSiteDomains from WPCom endpoint`() = test {
val site = SiteModel()
site.setIsWPCom(true)
whenever(siteRestClient.fetchSiteDomains(site)).thenReturn(successResponse)
whenever(successResponse.data).thenReturn(DomainsResponse(listOf()))
val onSiteDomainsFetched = siteStore.fetchSiteDomains(site)
assertThat(onSiteDomainsFetched.domains).isNotNull
assertThat(onSiteDomainsFetched.error).isNull()
}
@Test
fun `fetchSiteDomains error from WPCom endpoint returns error`() = test {
val site = SiteModel()
site.setIsWPCom(true)
whenever(siteRestClient.fetchSiteDomains(site)).thenReturn(errorResponse)
whenever(errorResponse.error).thenReturn(WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val onSiteDomainsFetched = siteStore.fetchSiteDomains(site)
assertThat(onSiteDomainsFetched.error).isEqualTo(SiteError(GENERIC_ERROR, null))
}
}
| gpl-2.0 | 91a69268d9f42d435a25852a2c26bf22 | 38.095679 | 104 | 0.699771 | 4.643328 | false | true | false | false |
inv3rse/ProxerTv | app/src/main/java/com/inverse/unofficial/proxertv/ui/player/PlayerOverlayFragment.kt | 1 | 16383 | package com.inverse.unofficial.proxertv.ui.player
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.AudioManager
import android.media.MediaMetadata
import android.media.session.MediaController
import android.media.session.MediaSession
import android.media.session.PlaybackState
import android.net.Uri
import android.os.Bundle
import android.support.v17.leanback.app.PlaybackFragment
import android.support.v17.leanback.widget.*
import android.view.SurfaceView
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.inverse.unofficial.proxertv.R
import com.inverse.unofficial.proxertv.base.App
import com.inverse.unofficial.proxertv.base.CrashReporting
import com.inverse.unofficial.proxertv.base.client.ProxerClient
import com.inverse.unofficial.proxertv.model.Episode
import com.inverse.unofficial.proxertv.model.Series
import com.inverse.unofficial.proxertv.model.ServerConfig
import com.inverse.unofficial.proxertv.model.Stream
import com.inverse.unofficial.proxertv.ui.util.ErrorFragment
import com.inverse.unofficial.proxertv.ui.util.StreamAdapter
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import timber.log.Timber
/**
* We use this fragment as an implementation detail of the PlayerActivity.
* Therefore it is somewhat strongly tied to it.
*/
class PlayerOverlayFragment : PlaybackFragment(), OnItemViewClickedListener {
private var seekLength = 10000 // 10 seconds, overridden once the video length is known
private val subscriptions = CompositeSubscription()
private val proxerRepository = App.component.getProxerRepository()
private lateinit var playbackControlsHelper: PlaybackControlsHelper
private lateinit var videoPlayer: VideoPlayer
private lateinit var mediaControllerCallback: MediaController.Callback
private lateinit var mediaSession: MediaSession
private lateinit var audioManager: AudioManager
private lateinit var rowsAdapter: ArrayObjectAdapter
private lateinit var streamAdapter: StreamAdapter
private lateinit var metadataBuilder: MediaMetadata.Builder
private var episode: Episode? = null
private var series: Series? = null
private var isTracked = false
private var hasAudioFocus: Boolean = false
private var pauseTransient: Boolean = false
private var progressSpinner: View? = null
private val mOnAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_LOSS -> {
abandonAudioFocus()
pause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> if (videoPlayer.isPlaying) {
pause()
pauseTransient = true
}
AudioManager.AUDIOFOCUS_GAIN, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK -> {
if (pauseTransient) {
play()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.d("onCreate")
audioManager = activity.getSystemService(Context.AUDIO_SERVICE) as AudioManager
// create a MediaSession
mediaSession = MediaSession(activity, "ProxerTv")
mediaSession.setCallback(MediaSessionCallback())
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS or MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS)
mediaSession.isActive = true
videoPlayer = VideoPlayer(activity, savedInstanceState)
videoPlayer.setStatusListener(PlayerListener())
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.d("onActivityCreated")
activity.mediaController = MediaController(activity, mediaSession.sessionToken)
progressSpinner = activity.findViewById(R.id.player_buffer_spinner)
// connect session to controls
playbackControlsHelper = PlaybackControlsHelper(activity, this)
mediaControllerCallback = playbackControlsHelper.createMediaControllerCallback()
activity.mediaController.registerCallback(mediaControllerCallback)
backgroundType = PlaybackFragment.BG_LIGHT
setupAdapter()
initEpisode()
}
override fun onResume() {
super.onResume()
Timber.d("onResume")
val surfaceView = activity.findViewById(R.id.player_surface_view) as SurfaceView
val aspectFrame = activity.findViewById(R.id.player_ratio_frame) as AspectRatioFrameLayout
videoPlayer.connectToUi(aspectFrame, surfaceView)
}
@SuppressLint("NewApi")
override fun onPause() {
super.onPause()
Timber.d("onPause")
if (videoPlayer.isPlaying) {
val isVisibleBehind = activity.requestVisibleBehind(true)
val isInPictureInPictureMode = PlayerActivity.supportsPictureInPicture(activity) &&
activity.isInPictureInPictureMode
if (!isVisibleBehind && !isInPictureInPictureMode) {
pause()
}
} else {
activity.requestVisibleBehind(false)
}
}
override fun onStop() {
super.onStop()
Timber.d("onStop")
videoPlayer.disconnectFromUi()
pause()
}
override fun onDestroy() {
super.onDestroy()
Timber.d("onDestroy")
activity.mediaController.unregisterCallback(mediaControllerCallback)
videoPlayer.destroy()
abandonAudioFocus()
mediaSession.release()
subscriptions.clear()
}
override fun onItemClicked(itemViewHolder: Presenter.ViewHolder?, item: Any?, rowViewHolder: RowPresenter.ViewHolder?, row: Row?) {
when (item) {
is StreamAdapter.StreamHolder -> setStream(item.stream)
}
}
/**
* Initializes episode based on intent extras
*/
fun initEpisode() {
val extras = activity.intent.extras
val episodeExtra = extras.getParcelable<Episode>(PlayerActivity.EXTRA_EPISODE)
val seriesExtra = extras.getParcelable<Series>(PlayerActivity.EXTRA_SERIES)
if ((episodeExtra != null) and (seriesExtra != null)) {
if ((episodeExtra != episode) or (seriesExtra != series)) {
episode = episodeExtra
series = seriesExtra
if (videoPlayer.isInitialized) {
videoPlayer.stop()
}
initMediaMetadata()
setPendingIntent()
loadStreams()
// check if the episode is already marked as watched
proxerRepository.getSeriesProgress(seriesExtra.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ isTracked = episodeExtra.episodeNum <= it },
{ CrashReporting.logException(it) })
}
} else {
Timber.d("missing extras, finishing!")
activity.finish()
}
}
fun updatePlaybackRow() {
rowsAdapter.notifyArrayItemRangeChanged(0, 1)
}
private fun setupAdapter() {
val controlsRowPresenter = playbackControlsHelper.controlsRowPresenter
val presenterSelector = ClassPresenterSelector()
presenterSelector.addClassPresenter(PlaybackControlsRow::class.java, controlsRowPresenter)
presenterSelector.addClassPresenter(ListRow::class.java, ListRowPresenter())
rowsAdapter = ArrayObjectAdapter(presenterSelector)
// first row (playback controls)
rowsAdapter.add(playbackControlsHelper.controlsRow)
// second row (stream selection)
streamAdapter = StreamAdapter()
rowsAdapter.add(ListRow(HeaderItem(getString(R.string.row_streams)), streamAdapter))
updatePlaybackRow()
adapter = rowsAdapter
setOnItemViewClickedListener(this)
}
private fun loadStreams() {
val client = App.component.getProxerClient()
streamAdapter.clear()
subscriptions.add(client.loadEpisodeStreams(series!!.id, episode!!.episodeNum, episode!!.languageType)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe({ stream ->
// add the stream to the adapter first
streamAdapter.addStream(stream)
if (streamAdapter.getCurrentStream() == null) {
setStream(stream)
}
}, { throwable ->
if (throwable is ProxerClient.SeriesCaptchaException) {
showErrorFragment(getString(R.string.stream_captcha_error))
} else {
CrashReporting.logException(throwable)
checkValidStreamsFound()
}
}, { checkValidStreamsFound() }))
}
private fun checkValidStreamsFound() {
if (streamAdapter.size() == 0) {
showErrorFragment(getString(R.string.no_streams_found))
}
}
private fun showErrorFragment(message: String) {
val errorFragment = ErrorFragment.newInstance(getString(R.string.stream_error), message)
errorFragment.dismissListener = object : ErrorFragment.ErrorDismissListener {
override fun onDismiss() {
activity.finish()
}
}
fragmentManager.beginTransaction()
.detach(this) // the error fragment would sometimes not keep the focus
.add(R.id.player_root_frame, errorFragment)
.commit()
}
private fun setStream(stream: Stream) {
streamAdapter.removeFailed(stream)
streamAdapter.setCurrentStream(stream)
videoPlayer.initPlayer(Uri.parse(stream.streamUrl.toString()), activity, true)
play()
}
private fun play() {
requestAudioFocus()
if (hasAudioFocus) {
videoPlayer.play()
}
}
private fun pause() {
pauseTransient = false
videoPlayer.pause()
}
private fun initMediaMetadata() {
val episodeText = getString(R.string.episode, episode!!.episodeNum)
metadataBuilder = MediaMetadata.Builder()
.putString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, series!!.name)
.putString(MediaMetadata.METADATA_KEY_DISPLAY_SUBTITLE, episodeText)
.putString(MediaMetadata.METADATA_KEY_TITLE, series!!.name)
.putString(MediaMetadata.METADATA_KEY_ARTIST, episodeText)
.putLong(MediaMetadata.METADATA_KEY_DURATION, 0L)
Glide.with(this).load(ServerConfig.coverUrl(series!!.id)).asBitmap().into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(bitmap: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap)
mediaSession.setMetadata(metadataBuilder.build())
}
})
}
private fun requestAudioFocus() {
if (hasAudioFocus) {
return
}
val result = audioManager.requestAudioFocus(mOnAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
hasAudioFocus = true
} else {
pause()
}
}
private fun abandonAudioFocus() {
hasAudioFocus = false
audioManager.abandonAudioFocus(mOnAudioFocusChangeListener)
}
private fun setPlaybackState(state: Int) {
val playbackState = PlaybackState.Builder()
.setState(state, videoPlayer.position, 1F)
.setBufferedPosition(videoPlayer.bufferedPosition)
.setActions(getStateActions(state))
.build()
mediaSession.setPlaybackState(playbackState)
}
private fun setPendingIntent() {
val intent = Intent(activity.intent)
intent.putExtra(PlayerActivity.EXTRA_EPISODE, episode)
val pi = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
mediaSession.setSessionActivity(pi)
}
private fun getStateActions(state: Int): Long {
return (if (state == PlaybackState.STATE_PLAYING)
PlaybackState.ACTION_PAUSE else
PlaybackState.ACTION_PLAY) or
PlaybackState.ACTION_FAST_FORWARD or
PlaybackState.ACTION_REWIND
}
/**
* Handles controls from MediaSession
*/
private inner class MediaSessionCallback : MediaSession.Callback() {
override fun onPlay() {
play()
tickle()
}
override fun onPause() {
pause()
tickle()
}
override fun onFastForward() {
videoPlayer.seekTo(videoPlayer.position + seekLength)
tickle()
}
override fun onRewind() {
videoPlayer.apply { seekTo(if (position > seekLength) position - seekLength else 0) }
tickle()
}
override fun onSeekTo(position: Long) {
videoPlayer.seekTo(position)
tickle()
}
}
/**
* Handles all player callbacks
*/
private inner class PlayerListener : VideoPlayer.StatusListener {
private var state: Int = PlaybackState.STATE_NONE
override fun playStatusChanged(isPlaying: Boolean, playbackState: Int) {
state = when (playbackState) {
ExoPlayer.STATE_IDLE -> PlaybackState.STATE_NONE
ExoPlayer.STATE_BUFFERING -> if (isPlaying)
PlaybackState.STATE_BUFFERING else
PlaybackState.STATE_PAUSED
ExoPlayer.STATE_READY -> if (isPlaying)
PlaybackState.STATE_PLAYING else
PlaybackState.STATE_PAUSED
ExoPlayer.STATE_ENDED -> PlaybackState.STATE_STOPPED
else -> PlaybackState.STATE_NONE
}
progressSpinner?.visibility = if (playbackState == ExoPlayer.STATE_BUFFERING && isPlaying)
View.VISIBLE else
View.INVISIBLE
if (playbackState == ExoPlayer.STATE_ENDED) {
activity.finish()
} else {
setPlaybackState(state)
}
}
override fun progressChanged(currentProgress: Long, bufferedProgress: Long) {
setPlaybackState(state)
if (!isTracked && videoPlayer.duration > 0) {
val progressPercent = currentProgress.toFloat() / videoPlayer.duration
if (progressPercent > TRACK_PERCENT) {
// track episode
isTracked = true
proxerRepository.setSeriesProgress(series!!.id, episode!!.episodeNum)
.subscribeOn(Schedulers.io())
.subscribe({ }, { it.printStackTrace() })
}
}
}
override fun videoDurationChanged(length: Long) {
seekLength = (length / SEEK_STEPS).toInt()
metadataBuilder.putLong(MediaMetadata.METADATA_KEY_DURATION, length)
mediaSession.setMetadata(metadataBuilder.build())
}
override fun onError(error: ExoPlaybackException) {
error.printStackTrace()
streamAdapter.getCurrentStream()?.let { currentStream ->
streamAdapter.addFailed(currentStream)
}
}
}
companion object {
private const val SEEK_STEPS = 100
private const val TRACK_PERCENT = 0.75F
}
} | mit | 55df36008f81a191f126dae5f8169524 | 35.984199 | 135 | 0.643472 | 5.315704 | false | false | false | false |
felsig/Underling | app/src/main/kotlin/com/nonnulldev/underling/ui/player/PlayerActivity.kt | 1 | 4767 | package com.nonnulldev.underling.ui.player
import android.os.Bundle
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.nonnulldev.underling.R
import com.nonnulldev.underling.UnderlingApp
import com.nonnulldev.underling.injection.component.DaggerPlayerComponent
import com.nonnulldev.underling.injection.component.PlayerComponent
import com.nonnulldev.underling.injection.module.PlayerModule
import com.nonnulldev.underling.ui.base.BaseActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_player.*
import javax.inject.Inject
class PlayerActivity : BaseActivity() {
companion object {
@JvmStatic val PLAYER_NAME = "PLAYER_NAME"
}
@BindView(R.id.tvLevel)
lateinit var tvLevel: TextView
@BindView(R.id.tvTotalLevel)
lateinit var tvTotalLevel: TextView
@BindView(R.id.tvName)
lateinit var tvName: TextView
lateinit private var playerComponent: PlayerComponent
@Inject
lateinit protected var viewModel: PlayerScreenViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player)
ButterKnife.bind(this)
initPlayerComponent()
playerComponent.inject(this)
initBindings()
initUi()
}
private fun initPlayerComponent() {
val playerName = intent.extras.getString(PLAYER_NAME)
if(playerName == null) {
throw NullPointerException("Player name in ${PlayerActivity::class.simpleName} cannot be null")
}
playerComponent = DaggerPlayerComponent.builder()
.appComponent(UnderlingApp.appComponent)
.playerModule(PlayerModule(playerName))
.build()
}
private fun initBindings() {
subscriptions.addAll(
viewModel.levelObservable()
.observeOn(AndroidSchedulers.mainThread())
.map { it -> "$it" }
.subscribe { it ->
run {
updateLevelText(it)
updateTotalLevel()
}
},
viewModel.gearObservable()
.observeOn(AndroidSchedulers.mainThread())
.map { it -> "$it" }
.subscribe { it ->
run {
updateGearText(it)
updateTotalLevel()
}
},
viewModel.totalLevelObservable()
.observeOn(AndroidSchedulers.mainThread())
.map { it -> "$it" }
.subscribe { it -> updateTotalLevelText(it) },
viewModel.getName()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> tvName.text = it }
)
}
private fun initUi() {
updateLevel()
updateGear()
updateTotalLevel()
}
private fun updateLevelText(level: String) {
tvLevel.text = level
}
private fun updateGearText(gear: String) {
tvGear.text = gear
}
private fun updateTotalLevelText(totalLevel: String) {
tvTotalLevel.text = totalLevel
}
private fun updateLevel() {
viewModel.getLevel()
.subscribeOn(Schedulers.io())
.subscribe()
}
private fun updateGear() {
viewModel.getGear()
.subscribeOn(Schedulers.io())
.subscribe()
}
private fun updateTotalLevel() {
viewModel.getTotalLevel()
.subscribeOn(Schedulers.io())
.subscribe()
}
@OnClick(R.id.btnRemoveLevel)
fun onRemoveLevelButtonClicked() {
viewModel.removeLevel()
.subscribeOn(Schedulers.io())
.subscribe()
}
@OnClick(R.id.btnAddLevel)
fun onAddLevelButtonClicked() {
viewModel.addLevel()
.subscribeOn(Schedulers.io())
.subscribe()
}
@OnClick(R.id.btnRemoveGear)
fun onRemoveGearButtonClicked() {
viewModel.removeGear()
.subscribeOn(Schedulers.io())
.subscribe()
}
@OnClick(R.id.btnAddGear)
fun onAddGearButtonClicked() {
viewModel.addGear()
.subscribeOn(Schedulers.io())
.subscribe()
}
}
| mit | a912bfd712b141d7c5f8cea46a33288f | 28.79375 | 107 | 0.571429 | 5.204148 | false | false | false | false |
wuan/rest-demo-jersey-kotlin | src/main/java/com/tngtech/demo/weather/resources/Paths.kt | 1 | 383 | package com.tngtech.demo.weather.resources
object Paths {
const val STATIONS = "/stations"
const val WEATHER = "/weather"
const val STATISTICS = "/statistics"
const val STATION_ID = "stationId"
const val LIMIT = "limit"
const val OFFSET = "offset"
const val LONGITUDE = "longitude"
const val LATITUDE = "latitude"
const val RADIUS = "radius"
}
| apache-2.0 | 7aaedf80a7cbe61191650011c0205074 | 24.533333 | 42 | 0.668407 | 3.908163 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/args/ContextResolvers.kt | 1 | 3903 | package me.mrkirby153.KirBot.command.args
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.inject.Injectable
import net.dv8tion.jda.api.sharding.ShardManager
import java.util.regex.Pattern
import javax.inject.Inject
import javax.inject.Singleton
@Injectable
@Singleton
class ContextResolvers @Inject constructor(private val shardManager: ShardManager) {
private val resolvers = mutableMapOf<String, (ArgumentList) -> Any?>()
init {
registerDefaultResolvers()
}
fun registerResolver(name: String, function: (ArgumentList) -> Any?) {
Bot.LOG.debug("Registered resolver ")
resolvers[name] = function
}
fun getResolver(name: String): ((ArgumentList) -> Any?)? {
return resolvers[name]
}
private fun registerDefaultResolvers() {
// String resolver
// TODO 2/24/18: Make "string..." as the thing that takes the rest
registerResolver("string") { args ->
// Return the string in quotes
if (args.peek().matches(Regex("^(?<!\\\\)\\\".*"))) {
Bot.LOG.debug("Found beginning quote, starting parse")
val string = buildString {
while (true) {
if (!args.hasNext()) {
throw ArgumentParseException("Unmatched quotes")
}
val next = args.popFirst()
append(next + " ")
if (next.matches(Regex(".*(?<!\\\\)\\\"\$"))) {
break
}
}
}
Bot.LOG.debug("Parse complete!")
string.trim().substring(1..(string.length - 3)).replace("\\\"", "\"")
} else {
args.popFirst()
}
}
registerResolver("string...") { args ->
return@registerResolver buildString {
while(args.peek() != null)
append(args.popFirst()+" ")
}.trim().replace(Regex("^(?<!\\\\)\\\""), "").replace(Regex("(?<!\\\\)\\\"\$"), "")
}
// Snowflake resolver
registerResolver("snowflake") { args ->
val first = args.popFirst()
val pattern = Pattern.compile("\\d{17,18}")
val matcher = pattern.matcher(first)
if(matcher.find()) {
try{
return@registerResolver matcher.group()
} catch (e: IllegalStateException) {
throw ArgumentParseException("`$first` is not a valid snowflake")
}
} else {
throw ArgumentParseException("`$first` is not a valid snowflake")
}
}
// User resolver
registerResolver("user") { args ->
val id = getResolver("snowflake")?.invoke(args) as? String
?: throw ArgumentParseException(
"Could not find user")
if (id.toLongOrNull() == null)
throw ArgumentParseException("Cannot convert `$id` to user")
return@registerResolver shardManager.getUserById(id)
?: throw ArgumentParseException(
"The user `$id` was not found")
}
// Number resolver
registerResolver("number") { args ->
val num = args.popFirst()
try {
val number = num.toDouble()
return@registerResolver number
} catch (e: NumberFormatException) {
throw ArgumentParseException("`$num` is not a number!")
}
}
// Int resolver
registerResolver("int") { args ->
(getResolver("number")?.invoke(args) as? Double)?.toInt()
?: throw ArgumentParseException("Could not parse")
}
}
} | mit | 16cb9a8c26470a4d5639b4f896dbac97 | 34.171171 | 95 | 0.507558 | 5.149077 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/settings/api/SettingsFormImpl.kt | 1 | 5513 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.settings.api
import com.intellij.openapi.util.Disposer
import com.intellij.uiDesigner.core.GridConstraints
import com.intellij.uiDesigner.core.GridLayoutManager
import com.vladsch.md.nav.settings.MdExtensionSpacer
import com.vladsch.md.nav.settings.MdRenderingProfileHolder
import com.vladsch.md.nav.settings.RenderingProfileSynchronizer
import java.util.*
import java.util.function.BiConsumer
import java.util.function.Consumer
import javax.swing.JPanel
abstract class SettingsFormImpl(myProfileSynchronizer: RenderingProfileSynchronizer) : SettingsFormBase(myProfileSynchronizer), MdSettingsComponent<MdRenderingProfileHolder> {
private val myExtensionsPanel: JPanel
@JvmField
protected val mySettingsExtensions = ArrayList<MdSettingsComponent<MdRenderingProfileHolder>>()
protected val mySettingsExtensionNames = ArrayList<String>()
companion object {
val settingsFormExtensionProviders: Array<MdSettingsFormExtensionProvider<*, *>> by lazy {
MdSettingsFormExtensionProvider.EP_NAME.extensions.sortedBy { it.extensionName }.toTypedArray()
}
}
init {
// allow extensions to add theirs
for (configurableEP in settingsFormExtensionProviders) {
// pass the container instance to constructor so it can be used for checking availability
if (configurableEP.isAvailable(this)) {
@Suppress("UNCHECKED_CAST")
mySettingsExtensions.add((configurableEP as MdSettingsFormExtensionProvider<MdRenderingProfileHolder, MdRenderingProfileHolder>)
.createComponent(myProfileSynchronizer, myProfileSynchronizer, this) as MdSettingsComponent<MdRenderingProfileHolder>)
mySettingsExtensionNames.add(configurableEP.extensionName)
}
}
val iMax: Int = mySettingsExtensions.size
if (iMax == 0) {
myExtensionsPanel = JPanel()
myExtensionsPanel.isVisible = false
} else {
myExtensionsPanel = JPanel(GridLayoutManager(iMax * 2, 1))
forEachExtension { i, component ->
val jComponent = component.component
val extensionSpacer = MdExtensionSpacer(mySettingsExtensionNames[i], jComponent).mainPanel
val constraintsLabel = GridConstraints(i * 2, 0, 1, 1
, GridConstraints.ANCHOR_CENTER
, GridConstraints.FILL_HORIZONTAL
, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK
, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK
, null, null, null)
myExtensionsPanel.add(extensionSpacer, constraintsLabel)
val constraints = GridConstraints(i * 2 + 1, 0, 1, 1
, GridConstraints.ANCHOR_CENTER
, GridConstraints.FILL_HORIZONTAL
, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK
, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK
, null, null, null)
myExtensionsPanel.add(jComponent, constraints)
}
}
}
fun getExtensionsPanel(): JPanel = myExtensionsPanel
fun forEachExtension(consumer: BiConsumer<Int, MdSettingsComponent<MdRenderingProfileHolder>>) {
for ((index, component) in mySettingsExtensions.withIndex()) {
consumer.accept(index, component)
}
}
fun forEachExtension(consumer: Consumer<MdSettingsComponent<MdRenderingProfileHolder>>) {
for (component in mySettingsExtensions) {
consumer.accept(component)
}
}
fun forEachExtension(consumer: (index: Int, form: MdSettingsComponent<MdRenderingProfileHolder>) -> Unit) {
forEachExtension(BiConsumer(consumer))
}
fun forEachExtension(consumer: (form: MdSettingsComponent<MdRenderingProfileHolder>) -> Unit) {
forEachExtension(Consumer(consumer))
}
fun updateExtensionsOptionalSettings() {
forEachExtension { component ->
component.updateOptionalSettings()
}
}
fun isModifiedExtensions(settings: MdRenderingProfileHolder): Boolean {
var isModified = false
forEachExtension { component ->
if (component.isModified(settings)) {
isModified = true
return@forEachExtension
}
}
return isModified
}
fun applyExtensions(settings: MdRenderingProfileHolder) {
forEachExtension { component ->
component.apply(settings)
}
}
fun resetExtensions(settings: MdRenderingProfileHolder) {
forEachExtension { component ->
component.reset(settings)
}
}
fun forExtensions(runnable: Runnable) {
if (mySettingsExtensions.isNotEmpty()) {
runnable.run()
}
}
fun forExtensions(runnable: () -> Unit) {
forExtensions(Runnable(runnable))
}
protected abstract fun disposeResources()
final override fun dispose() {
disposeResources()
forEachExtension { it -> Disposer.dispose(it) }
mySettingsExtensions.clear()
}
}
| apache-2.0 | f45ef241da93a64518cd0302ef45634f | 37.552448 | 177 | 0.672048 | 5.240494 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_csc/src/main/java/no/nordicsemi/android/csc/view/CSCContentView.kt | 1 | 4979 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.csc.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.csc.R
import no.nordicsemi.android.csc.data.CSCData
import no.nordicsemi.android.csc.data.WheelSize
import no.nordicsemi.android.theme.RadioButtonGroup
import no.nordicsemi.android.theme.ScreenSection
import no.nordicsemi.android.ui.view.SectionTitle
import no.nordicsemi.android.ui.view.dialog.FlowCanceled
import no.nordicsemi.android.ui.view.dialog.ItemSelectedResult
import no.nordicsemi.android.utils.exhaustive
@Composable
internal fun CSCContentView(state: CSCData, speedUnit: SpeedUnit, onEvent: (CSCViewEvent) -> Unit) {
val showDialog = rememberSaveable { mutableStateOf(false) }
if (showDialog.value) {
val wheelEntries = stringArrayResource(R.array.wheel_entries)
val wheelValues = stringArrayResource(R.array.wheel_values)
SelectWheelSizeDialog {
when (it) {
FlowCanceled -> showDialog.value = false
is ItemSelectedResult -> {
onEvent(OnWheelSizeSelected(WheelSize(wheelValues[it.index].toInt(),
wheelEntries[it.index])))
showDialog.value = false
}
}.exhaustive
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(16.dp)
) {
SettingsSection(state, speedUnit, onEvent) { showDialog.value = true }
Spacer(modifier = Modifier.height(16.dp))
SensorsReadingView(state = state, speedUnit)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = { onEvent(OnDisconnectButtonClick) }
) {
Text(text = stringResource(id = R.string.disconnect))
}
}
}
@Composable
private fun SettingsSection(
state: CSCData,
speedUnit: SpeedUnit,
onEvent: (CSCViewEvent) -> Unit,
onWheelButtonClick: () -> Unit,
) {
ScreenSection {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
SectionTitle(icon = Icons.Default.Settings,
title = stringResource(R.string.csc_settings))
Spacer(modifier = Modifier.height(16.dp))
WheelSizeView(state, onWheelButtonClick)
Spacer(modifier = Modifier.height(16.dp))
RadioButtonGroup(viewEntity = speedUnit.temperatureSettingsItems()) {
onEvent(OnSelectedSpeedUnitSelected(it.label.toSpeedUnit()))
}
}
}
}
@Preview
@Composable
private fun ConnectedPreview() {
CSCContentView(CSCData(), SpeedUnit.KM_H) { }
}
| bsd-3-clause | 5c088540dab2fb95ebbda7b90abb05e0 | 36.719697 | 100 | 0.72625 | 4.465471 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/AppJiyoujiaContentEntity.kt | 1 | 2279 | package cn.cloudself.model
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*
*
* change logs:
* 2017/5/16 HerbLuo 首次创建
*/
@Entity
@Table(name = "app_jiyoujia", schema = "shop")
@NamedNativeQueries(NamedNativeQuery(name = "AppJiyoujiaContentEntity.getData", query = "(SELECT * FROM app_jiyoujia WHERE `index` = 1 LIMIT ?1, ?2)" +
"UNION (SELECT * FROM app_jiyoujia WHERE `index` = 2 LIMIT ?1, ?2)" +
"UNION (SELECT * FROM app_jiyoujia WHERE `index` = 3 LIMIT ?1, ?2)" +
"UNION (SELECT * FROM app_jiyoujia WHERE `index` = 4 LIMIT ?1, ?2)", resultClass = AppJiyoujiaContentEntity::class), NamedNativeQuery(name = "AppJiyoujiaContentEntity.maxCount", query = "SELECT MAX(`group_count`) AS `id` FROM (" +
"(SELECT COUNT(*) AS `group_count` FROM app_jiyoujia WHERE `index` = 1)" +
"UNION(SELECT COUNT(*) FROM app_jiyoujia WHERE `index` = 2)" +
"UNION(SELECT COUNT(*) FROM app_jiyoujia WHERE `index` = 3)" +
"UNION(SELECT COUNT(*) FROM app_jiyoujia WHERE `index` = 4)" +
") as v_table;", resultClass = IntegerEntity::class))
class AppJiyoujiaContentEntity {
@get:Id
@get:Column(name = "id")
var id: Int = 0
@get:Basic
@get:Column(name = "index")
var index: Byte? = null
@get:Basic
@get:Column(name = "img")
var img: String? = null
@get:Basic
@get:Column(name = "link")
var link: String? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as AppJiyoujiaContentEntity?
if (id != that!!.id) return false
if (if (index != null) index != that.index else that.index != null) return false
if (if (img != null) img != that.img else that.img != null) return false
return if (if (link != null) link != that.link else that.link != null) false else true
}
override fun hashCode(): Int {
var result = id
result = 31 * result + if (index != null) index!!.hashCode() else 0
result = 31 * result + if (img != null) img!!.hashCode() else 0
result = 31 * result + if (link != null) link!!.hashCode() else 0
return result
}
}
| mit | 719609deb26bfa4e718cfdf0cfbe49b6 | 38.155172 | 238 | 0.608542 | 3.359467 | false | false | false | false |
alashow/music-android | modules/domain/src/main/java/tm/alashow/domain/models/Optional.kt | 1 | 1516 | /*
* Copyright (C) 2018, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.domain.models
sealed class Optional<out T> {
open operator fun invoke(): T? = null
fun isNone() = this is None
fun isSome() = this is Some
/**
* Will run [block] if this optional has [Some].
*/
fun optional(onNone: () -> Unit = {}, onSome: (T) -> Unit) {
when (this) {
is Some<T> -> onSome(value)
else -> onNone()
}
}
/**
* @Note: Call only if you're sure it's [Some]
*/
fun value() = (this as Some).value
data class Some<out T>(val value: T) : Optional<T>() {
override operator fun invoke(): T = value
}
object None : Optional<Nothing>()
}
typealias None = Optional.None
/**
* Returns [Optional.Some] with [T] if not null,
* or [Optional.None] when null
*/
fun <T> T?.orNone(): Optional<T> = when (this != null) {
true -> Optional.Some(this)
else -> None
}
fun <T> some(value: T?): Optional<T> = value.orNone()
fun <T> Optional<T>?.orNull(): T? = when (this) {
is Optional.Some -> value
else -> null
}
/**
* Returns [Optional.Some] if not null, or [Optional.None] when null.
*/
fun <T> Optional<T>?.orNone(): Optional<T> = when (this != null) {
true -> this
else -> None
}
/**
* Returns [Optional.Some] if not null, or [Optional.None] when null.
*/
infix fun <T> Optional<T>?.or(that: T): T = when (this != null && isSome()) {
true -> this.value()
else -> that
}
| apache-2.0 | 488a6aed7d2072372bda38d31d46a3df | 21.626866 | 77 | 0.563984 | 3.274298 | false | false | false | false |
krischik/Fit-Import | JavaLib/src/test/kotlin/com.krischik/fit_import/ReadKetfit_Test.kt | 1 | 4416 | /********************************************************** {{{1 ***********
* Copyright © 2015 … 2016 "Martin Krischik" «[email protected]»
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
********************************************************** }}}1 **********/
package com.krischik.fit_import
import java.time.Month;
import org.exparity.hamcrest.date.DateMatchers.isInstant
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual.equalTo
import org.hamcrest.core.IsNull.notNullValue
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
/**
* <p>
* Read ketfit file.
* </p>
*
* @author "Martin Krischik" «[email protected]»
* @version 1.0
* @since 1.0
*/
public class ReadKetfit_Test : org.jetbrains.spek.api.Spek(
{
/**
* <p>logging tag</p>
*/
val TAG = ReadKetfit_Test::class.qualifiedName
/**
* <p>logger</p>
*/
val logger = java.util.logging.Logger.getLogger (TAG);
Utilities.Init_Logger ()
given ("a stream with header")
{
val testData = ReadKetfit_Test::class.java.getResourceAsStream("/ketfit.csv")
on ("opening and closing the file")
{
val test = ReadKetfit (testData)
it ("should cause no error")
{
assertThat(test, notNullValue())
} // it
test.close ()
} // on
} // given
given ("a stream with test data")
{
val testData = ReadKetfit_Test::class.java.getResourceAsStream("/ketfit.csv")
val test = ReadKetfit (testData)
on ("reading first data")
{
val info = test.read();
it ("should return the expected value")
{
assertThat(info, notNullValue())
assertThat(info?.start, isInstant (2014, Month.FEBRUARY, 2, 18, 42, 0, 0))
assertThat(info?.end, isInstant (2014, Month.FEBRUARY, 2, 19, 22, 0, 0))
assertThat(info?.puls, equalTo(118))
assertThat(info?.uMin, equalTo(48))
assertThat(info?.kCal, equalTo(294))
assertThat(info?.watt, equalTo(88))
assertThat(info?.km, equalTo(6))
assertThat(info?.ω, equalTo(0))
} // it
} // on
on ("reading second data")
{
val info = test.read();
it ("should return the expected value")
{
assertThat(info, notNullValue())
assertThat(info?.start, isInstant (2014, Month.FEBRUARY, 3, 18, 29, 0, 0))
assertThat(info?.end, isInstant (2014, Month.FEBRUARY, 3, 19, 9, 0, 0))
assertThat(info?.puls, equalTo(94))
assertThat(info?.uMin, equalTo(61))
assertThat(info?.kCal, equalTo(294))
assertThat(info?.watt, equalTo(88))
assertThat(info?.km, equalTo(6))
assertThat(info?.ω, equalTo(0))
} // it
} // on
on ("closing the data stream")
{
test.close ()
} // on
} // given
given ("a stream with 13 rows of test data")
{
val testData = ReadKetfit_Test::class.java.getResourceAsStream("/ketfit.csv")
on ("reading all data")
{
val test = ReadKetfit (testData)
var recordCount = 0;
Read_Lines@ while (true)
{
val testRecord = test.read()
if (testRecord == null) break@Read_Lines
recordCount = recordCount + 1;
logger.log(java.util.logging.Level.FINE, "Read Record {1}: {2}", arrayOf (recordCount, testRecord))
} // when
it ("should return the 13 records")
{
assertThat(recordCount, equalTo(13))
} // it
test.close ()
} // on
} // given
}) // ReadKetfit_Test
// vim: set nowrap tabstop=8 shiftwidth=3 softtabstop=3 expandtab textwidth=96 :
// vim: set fileencoding=utf-8 filetype=kotlin foldmethod=syntax spell spelllang=en_gb :
| gpl-3.0 | 8522f0d2eb9b92d8cc272ef41c7a34a9 | 30.705036 | 107 | 0.609485 | 3.648179 | false | true | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/livestream/model/LiveShow.kt | 1 | 616 | package de.christinecoenen.code.zapp.app.livestream.model
import org.joda.time.DateTime
import org.joda.time.Duration
data class LiveShow(
var title: String,
var subtitle: String? = null,
var description: String? = null,
var startTime: DateTime? = null,
var endTime: DateTime? = null
) {
val progressPercent: Float
get() {
val showDuration = Duration(startTime, endTime)
val runningDuration = Duration(startTime, DateTime.now())
return runningDuration.standardSeconds.toFloat() / showDuration.standardSeconds
}
fun hasDuration(): Boolean {
return startTime != null && endTime != null
}
}
| mit | cbc79e8a8abc17e3b4ee80ac35796ab1 | 23.64 | 82 | 0.737013 | 3.560694 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/sched/DeckDueTreeNode.kt | 1 | 4824 | /*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki.sched
import com.ichi2.libanki.Collection
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import com.ichi2.utils.KotlinCleanup
import net.ankiweb.rsdroid.RustCleanup
import java.util.*
import kotlin.math.max
import kotlin.math.min
/**
* Holds the data for a single node (row) in the deck due tree (the user-visible list
* of decks and their counts). A node also contains a list of nodes that refer to the
* next level of sub-decks for that particular deck (which can be an empty list).
*
* The names field is an array of names that build a deck name from a hierarchy (i.e., a nested
* deck will have an entry for every level of nesting). While the python version interchanges
* between a string and a list of strings throughout processing, we always use an array for
* this field and use getNamePart(0) for those cases.
*/
@KotlinCleanup("maybe possible to remove gettres for revCount/lrnCount")
@KotlinCleanup("rename name -> fullDeckName")
@RustCleanup("after migration, consider dropping this and using backend tree structure directly")
class DeckDueTreeNode(
name: String,
did: DeckId,
override var revCount: Int,
override var lrnCount: Int,
override var newCount: Int,
// only set when defaultLegacySchema is false
override var collapsed: Boolean = false,
override var filtered: Boolean = false
) : AbstractDeckTreeNode(name, did, collapsed, filtered) {
override fun toString(): String {
return String.format(
Locale.US, "%s, %d, %d, %d, %d",
fullDeckName, did, revCount, lrnCount, newCount
)
}
private fun limitRevCount(limit: Int) {
revCount = max(0, min(revCount, limit))
}
private fun limitNewCount(limit: Int) {
newCount = max(0, min(newCount, limit))
}
override fun processChildren(col: Collection, children: List<AbstractDeckTreeNode>, addRev: Boolean) {
// tally up children counts
for (ch in children) {
lrnCount += ch.lrnCount
newCount += ch.newCount
if (addRev) {
revCount += ch.revCount
}
}
// limit the counts to the deck's limits
val conf = col.decks.confForDid(did)
if (conf.isStd) {
val deck = col.decks.get(did)
limitNewCount(conf.getJSONObject("new").getInt("perDay") - deck.getJSONArray("newToday").getInt(1))
if (addRev) {
limitRevCount(conf.getJSONObject("rev").getInt("perDay") - deck.getJSONArray("revToday").getInt(1))
}
}
}
override fun hashCode(): Int {
return fullDeckName.hashCode() + revCount + lrnCount + newCount
}
/**
* Whether both elements have the same structure and numbers.
* @param other
* @return
*/
override fun equals(other: Any?): Boolean {
if (other !is DeckDueTreeNode) {
return false
}
return Decks.equalName(fullDeckName, other.fullDeckName) &&
revCount == other.revCount &&
lrnCount == other.lrnCount &&
newCount == other.newCount
}
/** Line representing this string without its children. Used in timbers only. */
override fun toStringLine(): String {
return String.format(
Locale.US, "%s, %d, %d, %d, %d\n",
fullDeckName, did, revCount, lrnCount, newCount
)
}
override fun shouldDisplayCounts(): Boolean {
return true
}
override fun knownToHaveRep(): Boolean {
return revCount > 0 || newCount > 0 || lrnCount > 0
}
}
/** Locate node with a given deck ID in a list of nodes.
*
* This could be converted into a method if AnkiDroid returned a top-level
* node instead of a list of nodes.
*/
fun findInDeckTree(nodes: List<TreeNode<DeckDueTreeNode>>, deckId: Long): DeckDueTreeNode? {
for (node in nodes) {
if (node.value.did == deckId) {
return node.value
}
return findInDeckTree(node.children, deckId) ?: continue
}
return null
}
| gpl-3.0 | d7486310f55c14f3b13551c6469408e9 | 35 | 115 | 0.656095 | 4.077768 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/UnsyncedChangesCountSource.kt | 1 | 2516 | package de.westnordost.streetcomplete.data
import de.westnordost.streetcomplete.data.osm.edits.ElementEdit
import de.westnordost.streetcomplete.data.osm.edits.ElementEditsSource
import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEdit
import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEditsSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
/** Access and listen to how many unsynced (=uploadable) changes there are */
@Singleton class UnsyncedChangesCountSource @Inject constructor(
private val noteEditsSource: NoteEditsSource,
private val elementEditsSource: ElementEditsSource
) {
interface Listener {
fun onIncreased()
fun onDecreased()
}
private val listeners = CopyOnWriteArrayList<Listener>()
suspend fun getCount(): Int = withContext(Dispatchers.IO) {
elementEditsSource.getUnsyncedCount() + noteEditsSource.getUnsyncedCount()
}
/** count of unsynced changes that count towards the statistics. That is, unsynced note stuff
* doesn't count and reverts of changes count negative */
suspend fun getSolvedCount(): Int = withContext(Dispatchers.IO) {
elementEditsSource.getPositiveUnsyncedCount()
}
private val noteEditsListener = object : NoteEditsSource.Listener {
override fun onAddedEdit(edit: NoteEdit) { if (!edit.isSynced) onUpdate(+1) }
override fun onSyncedEdit(edit: NoteEdit) { onUpdate(-1) }
override fun onDeletedEdits(edits: List<NoteEdit>) { onUpdate(-edits.filter { !it.isSynced }.size) }
}
private val elementEditsListener = object : ElementEditsSource.Listener {
override fun onAddedEdit(edit: ElementEdit) { if (!edit.isSynced) onUpdate(+1) }
override fun onSyncedEdit(edit: ElementEdit) { onUpdate(-1) }
override fun onDeletedEdits(edits: List<ElementEdit>) { onUpdate(-edits.filter { !it.isSynced }.size) }
}
init {
elementEditsSource.addListener(elementEditsListener)
noteEditsSource.addListener(noteEditsListener)
}
private fun onUpdate(diff: Int) {
if (diff > 0) listeners.forEach { it.onIncreased() }
else if (diff < 0) listeners.forEach { it.onDecreased() }
}
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
}
| gpl-3.0 | 70372e200296a8ce9c98d48cb3761e7c | 38.936508 | 111 | 0.729332 | 4.398601 | false | false | false | false |
magnusja/libaums | httpserver/src/main/java/me/jahnen/libaums/server/http/UsbFileHttpServer.kt | 2 | 3151 | /*
* (C) Copyright 2016 mjahnen <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.server.http
import android.util.Log
import android.util.LruCache
import me.jahnen.libaums.core.fs.UsbFile
import me.jahnen.libaums.server.http.exception.NotAFileException
import me.jahnen.libaums.server.http.server.HttpServer
import java.io.FileNotFoundException
import java.io.IOException
/**
* This class allows to start a HTTP web server which can serve [com.github.mjdev.libaums.fs.UsbFile]s
* to another app.
*
* For instance it can make an image available to the Web Browser without copying it to the internal
* storage, or a video file to a video file as a HTTP stream.
*/
class UsbFileHttpServer(private val rootFile: UsbFile, private val server: HttpServer) : UsbFileProvider {
private val fileCache = LruCache<String, UsbFile>(100)
val baseUrl: String
get() {
var hostname: String? = server.hostname
if (hostname == null) {
hostname = "localhost"
}
return "http://" + hostname + ":" + server.listeningPort + "/"
}
val isAlive: Boolean
get() = server.isAlive
init {
server.usbFileProvider = this
}
@Throws(IOException::class)
fun start() {
server.start()
}
@Throws(IOException::class)
fun stop() {
server.stop()
fileCache.evictAll()
}
@Throws(IOException::class)
override fun determineFileToServe(uri: String): UsbFile {
var fileToServe: UsbFile? = fileCache.get(uri)
if (fileToServe == null) {
Log.d(TAG, "Searching file on USB (URI: $uri)")
if (!rootFile.isDirectory) {
Log.d(TAG, "Serving root file")
if ("/" != uri && "/" + rootFile.name != uri) {
Log.d(TAG, "Invalid request, respond with 404")
throw FileNotFoundException("Not found $uri")
}
fileToServe = rootFile
} else {
fileToServe = rootFile.search(uri.substring(1))
}
} else {
Log.d(TAG, "Using lru cache for $uri")
}
if (fileToServe == null) {
Log.d(TAG, "fileToServe == null")
throw FileNotFoundException("Not found $uri")
}
if (fileToServe.isDirectory) {
throw NotAFileException()
}
fileCache.put(uri, fileToServe)
return fileToServe
}
companion object {
private val TAG = UsbFileHttpServer::class.java.simpleName
}
}
| apache-2.0 | 5742fb5707e91a17f82fdea2fd4e0265 | 27.908257 | 106 | 0.620121 | 4.218206 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/view/dialogs/ValuePickerDialog.kt | 1 | 2231 | package de.westnordost.streetcomplete.view.dialogs
import android.content.Context
import android.content.DialogInterface
import androidx.appcompat.app.AlertDialog
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.EditText
import android.widget.NumberPicker
import androidx.annotation.LayoutRes
import androidx.core.view.children
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.spToPx
/** A dialog in which you can select one value from a range of values. If a custom layout is supplied,
* it must have a NumberPicker with the id "numberPicker". */
class ValuePickerDialog<T>(
context: Context,
private val values: List<T>,
selectedValue: T? = null,
title: CharSequence? = null,
@LayoutRes layoutResId: Int = R.layout.dialog_number_picker,
private val callback: (value: T) -> Unit
) : AlertDialog(context, R.style.Theme_Bubble_Dialog) {
init {
val view = LayoutInflater.from(context).inflate(layoutResId, null)
setView(view)
setTitle(title)
val numberPicker = view.findViewById<NumberPicker>(R.id.numberPicker)
setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok)) { _, _ ->
callback(values[numberPicker.value])
dismiss()
}
setButton(BUTTON_NEGATIVE, context.getString(android.R.string.cancel)) { _, _ ->
cancel()
}
numberPicker.wrapSelectorWheel = false
numberPicker.displayedValues = values.map { it.toString() }.toTypedArray()
numberPicker.minValue = 0
numberPicker.maxValue = values.size - 1
if (android.os.Build.VERSION.SDK_INT >= 29) {
numberPicker.textSize = 32f.spToPx(context)
}
selectedValue?.let { numberPicker.value = values.indexOf(it) }
// do not allow keyboard input
numberPicker.disableEditTextsFocus()
}
private fun ViewGroup.disableEditTextsFocus() {
for (child in children) {
if (child is ViewGroup) {
child.disableEditTextsFocus()
} else if (child is EditText) {
child.isFocusable = false
}
}
}
}
| gpl-3.0 | 7238ef91889a0d1684d656186cc3ea00 | 34.983871 | 102 | 0.674585 | 4.444223 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/state/property/StateProperties.kt | 1 | 11005 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.state.property
import org.lanternpowered.api.util.collections.toImmutableSet
import org.lanternpowered.server.state.StateKeyValueTransformer
import org.lanternpowered.server.state.identityStateKeyValueTransformer
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import org.spongepowered.api.state.BooleanStateProperty
import org.spongepowered.api.state.EnumStateProperty
import org.spongepowered.api.state.IntegerStateProperty
import java.util.function.Supplier
import kotlin.reflect.KClass
/**
* Creates a [BooleanStateProperty].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @return The constructed boolean state property
*/
fun booleanStatePropertyOf(key: NamespacedKey, valueKey: Supplier<out Key<out Value<Boolean>>>): BooleanStateProperty =
booleanStatePropertyOf(key, valueKey.get())
/**
* Creates a [BooleanStateProperty].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @return The constructed boolean state property
*/
fun booleanStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<Boolean>>): BooleanStateProperty =
LanternBooleanStateProperty(key, valueKey, identityStateKeyValueTransformer())
/**
* Creates a [BooleanStateProperty] with a [StateKeyValueTransformer].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param keyValueTransformer The transformer to translate between state and key values
* @return The constructed boolean state property
*/
fun <T> booleanStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<T>>,
keyValueTransformer: StateKeyValueTransformer<Boolean, T>): BooleanStateProperty
= LanternBooleanStateProperty(key, valueKey, keyValueTransformer)
// Enum state properties
/**
* Creates a [EnumStateProperty] with the given values.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed enum state property
*/
fun <E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<E>>, values: Iterable<E>): EnumStateProperty<E>
= LanternEnumStateProperty(key, values.iterator().next().javaClass, values.toImmutableSet(), valueKey)
/**
* Creates a [EnumStateProperty] with the given values.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed enum state property
*/
fun <E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Supplier<out Key<out Value<E>>>, vararg values: E): EnumStateProperty<E>
= enumStatePropertyOf(key, valueKey.get(), values.toImmutableSet())
/**
* Creates a [EnumStateProperty] with the given values.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed enum state property
*/
fun <E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<E>>, vararg values: E): EnumStateProperty<E>
= enumStatePropertyOf(key, valueKey, values.toImmutableSet())
/**
* Creates a [EnumStateProperty] with all the values of the given enum [Class].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param type The enum class
* @return The constructed enum state property
*/
fun <E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<E>>, type: Class<E>): EnumStateProperty<E>
= LanternEnumStateProperty(key, type, type.enumConstants.toImmutableSet(), valueKey)
/**
* Creates a [EnumStateProperty] with all the values of the given enum [KClass].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param type The enum class
* @return The constructed enum state property
*/
fun <E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<E>>, type: KClass<E>): EnumStateProperty<E>
= enumStatePropertyOf(key, valueKey, type.java)
/**
* Creates a [EnumStateProperty] with all the values of the given enum type [E].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param E The enum type
* @return The constructed enum state property
*/
inline fun <reified E : Enum<E>> enumStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<E>>): EnumStateProperty<E>
= enumStatePropertyOf(key, valueKey, E::class)
// Int state properties
/**
* Creates a [IntegerStateProperty] with all the values from the given collection.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<Int>>, values: Iterable<Int>): IntegerStateProperty
= LanternIntStateProperty(key, values.toImmutableSet(), valueKey, identityStateKeyValueTransformer())
/**
* Creates a [IntegerStateProperty] with all the values from the given array.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun intStatePropertyOf(key: NamespacedKey, valueKey: Supplier<out Key<out Value<Int>>>, vararg values: Int): IntegerStateProperty
= intStatePropertyOf(key, valueKey.get(), *values)
/**
* Creates a [IntegerStateProperty] with all the values from the given array.
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<Int>>, vararg values: Int): IntegerStateProperty
= LanternIntStateProperty(key, values.toImmutableSet(), valueKey, identityStateKeyValueTransformer())
/**
* Creates a [IntegerStateProperty] with all the values within the given [IntRange].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param valueRange The range of values that are available for the state property
* @return The constructed int state property
*/
fun intStatePropertyOf(key: NamespacedKey, valueKey: Supplier<out Key<out Value<Int>>>, valueRange: IntRange): IntegerStateProperty =
intStatePropertyOf(key, valueKey.get(), valueRange)
/**
* Creates a [IntegerStateProperty] with all the values within the given [IntRange].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param valueRange The range of values that are available for the state property
* @return The constructed int state property
*/
fun intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<Int>>, valueRange: IntRange): IntegerStateProperty
= LanternIntStateProperty(key, valueRange.toImmutableSet(), valueKey, identityStateKeyValueTransformer())
/**
* Creates a [IntegerStateProperty] with all the values from the given collection. An
* additional [StateKeyValueTransformer] can be used to translate between int and key
* based values of type [T].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun <T> intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<T>>, values: Iterable<Int>,
keyValueTransformer: StateKeyValueTransformer<Int, T>): IntegerStateProperty
= LanternIntStateProperty(key, values.toImmutableSet(), valueKey, keyValueTransformer)
/**
* Creates a [IntegerStateProperty] with all the values from the given collection. An
* additional [StateKeyValueTransformer] can be used to translate between int and key
* based values of type [T].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun <T> intStatePropertyOf(key: NamespacedKey, valueKey: Supplier<out Key<out Value<T>>>, values: Iterable<Int>,
keyValueTransformer: StateKeyValueTransformer<Int, T>): IntegerStateProperty
= intStatePropertyOf(key, valueKey.get(), values, keyValueTransformer)
/**
* Creates a [IntegerStateProperty] with all the values from the given array. An
* additional [StateKeyValueTransformer] can be used to translate between int and key
* based values of type [T].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param values The values that are available for the state property
* @return The constructed int state property
*/
fun <T> intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<T>>, vararg values: Int,
keyValueTransformer: StateKeyValueTransformer<Int, T>): IntegerStateProperty
= LanternIntStateProperty(key, values.toImmutableSet(), valueKey, keyValueTransformer)
/**
* Creates a [IntegerStateProperty] with all the values within the given [IntRange]. An
* additional [StateKeyValueTransformer] can be used to translate between int and key
* based values of type [T].
*
* @param key The catalog key of the state property
* @param valueKey The value key this property is mapped to
* @param valueRange The range of values that are available for the state property
* @return The constructed int state property
*/
fun <T> intStatePropertyOf(key: NamespacedKey, valueKey: Key<out Value<T>>, valueRange: IntRange,
keyValueTransformer: StateKeyValueTransformer<Int, T>): IntegerStateProperty
= LanternIntStateProperty(key, valueRange.toImmutableSet(), valueKey, keyValueTransformer)
| mit | b690a26eb41bb32123f57d8b999fbfb7 | 45.631356 | 140 | 0.751567 | 4.344651 | false | false | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/ui/dialog/SleepTimerDialog.kt | 1 | 3756 | package me.echeung.moemoekyun.ui.dialog
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import android.os.SystemClock
import android.widget.SeekBar
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.databinding.DialogSleepTimerBinding
import me.echeung.moemoekyun.service.RadioService
import me.echeung.moemoekyun.util.PreferenceUtil
import me.echeung.moemoekyun.util.ext.alarmManager
import me.echeung.moemoekyun.util.ext.getPluralString
import me.echeung.moemoekyun.util.ext.toast
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class SleepTimerDialog(private val activity: Activity) : KoinComponent {
private val preferenceUtil: PreferenceUtil by inject()
private var binding: DialogSleepTimerBinding =
DialogSleepTimerBinding.inflate(activity.layoutInflater, null, false)
init {
val sleepTimerText = binding.sleepTimerText
val sleepTimerSeekBar = binding.sleepTimerSeekbar
// Init seekbar + text
val prevSleepTimer = preferenceUtil.sleepTimer().get()
if (prevSleepTimer != 0) {
sleepTimerSeekBar.progress = prevSleepTimer
}
sleepTimerText.text = activity.getPluralString(R.plurals.minutes, prevSleepTimer)
sleepTimerSeekBar.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
sleepTimerText.text = activity.getPluralString(R.plurals.minutes, progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
},
)
// Build dialog
val sleepTimerDialog = MaterialAlertDialogBuilder(activity)
.setTitle(R.string.sleep_timer)
.setView(binding.root)
.setPositiveButton(R.string.set) { _, _ ->
val minutes = sleepTimerSeekBar.progress
setAlarm(minutes)
}
.setNegativeButton(R.string.close, null)
// Show cancel button if a timer is currently set
if (prevSleepTimer != 0) {
sleepTimerDialog.setNeutralButton(R.string.cancel_timer) { _, _ -> cancelAlarm() }
}
sleepTimerDialog.create().show()
}
private fun setAlarm(minutes: Int) {
if (minutes == 0) {
cancelAlarm()
return
}
preferenceUtil.sleepTimer().set(minutes)
val timerTime = SystemClock.elapsedRealtime() + minutes * 60 * 1000
val pendingIntent = makeTimerPendingIntent(PendingIntent.FLAG_CANCEL_CURRENT)
activity.alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timerTime, pendingIntent)
activity.toast(activity.getPluralString(R.plurals.sleep_timer_set, minutes))
}
private fun cancelAlarm() {
val previous = makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE)
if (previous != null) {
activity.alarmManager.cancel(previous)
previous.cancel()
preferenceUtil.sleepTimer().delete()
activity.toast(activity.getString(R.string.sleep_timer_canceled))
}
}
private fun makeTimerPendingIntent(flag: Int): PendingIntent? {
return PendingIntent.getService(activity, 0, makeTimerIntent(), flag or PendingIntent.FLAG_IMMUTABLE)
}
private fun makeTimerIntent(): Intent {
return Intent(activity, RadioService::class.java)
.setAction(RadioService.TIMER_STOP)
}
}
| mit | cdb356552529fa375edfbd4d0f8d26e1 | 35.466019 | 109 | 0.686368 | 4.790816 | false | false | false | false |
krazykira/VidEffects | app/src/main/java/com/videffects/sample/model/Shaders.kt | 1 | 1395 | package com.videffects.sample.model
import android.graphics.Color
import com.sherazkhilji.videffects.*
import com.sherazkhilji.videffects.filter.AutoFixFilter
import com.sherazkhilji.videffects.filter.GrainFilter
import com.sherazkhilji.videffects.filter.HueFilter
// TODO: Rewite to factory
class Shaders(width: Int, height: Int) {
companion object {
private const val SUFFIX = "Effect"
}
private val shaders = arrayOf(
// Filters
AutoFixFilter(),
GrainFilter(width, height),
HueFilter(),
// Effects
AutoFixEffect(0.0F),
BlackAndWhiteEffect(),
BrightnessEffect(0.5F),
ContrastEffect(0.5F),
CrossProcessEffect(),
DocumentaryEffect(),
DuotoneEffect(),
FillLightEffect(0.5F),
GammaEffect(1.0F),
GreyScaleEffect(),
InvertColorsEffect(),
LamoishEffect(),
PosterizeEffect(),
SaturationEffect(0.5F),
SepiaEffect(),
SharpnessEffect(0.5F),
TemperatureEffect(0.5F),
TintEffect(Color.GREEN),
VignetteEffect(0F)
)
val count = shaders.size
fun getShader(index: Int) = shaders[index]
fun getShaderName(index: Int) = shaders[index]::class.java.simpleName.removeSuffix(SUFFIX)
} | apache-2.0 | f2217760debf9d090646286c0f7cc026 | 27.489796 | 94 | 0.605018 | 3.963068 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/AnticipatedShowsViewModel.kt | 1 | 2667 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.suggestions.shows
import android.content.Context
import android.text.format.DateUtils
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import net.simonvt.cathode.actions.invokeAsync
import net.simonvt.cathode.actions.invokeSync
import net.simonvt.cathode.actions.shows.SyncAnticipatedShows
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.Show
import net.simonvt.cathode.entitymapper.ShowListMapper
import net.simonvt.cathode.entitymapper.ShowMapper
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.settings.SuggestionsTimestamps
import net.simonvt.cathode.ui.RefreshableViewModel
import net.simonvt.cathode.ui.suggestions.shows.AnticipatedShowsFragment.SortBy
import javax.inject.Inject
class AnticipatedShowsViewModel @Inject constructor(
private val context: Context,
private val syncAnticipatedShows: SyncAnticipatedShows
) : RefreshableViewModel() {
val anticipated: MappedCursorLiveData<List<Show>>
private var sortBy: SortBy? = null
init {
sortBy = SortBy.fromValue(
Settings.get(context).getString(
Settings.Sort.SHOW_ANTICIPATED,
SortBy.ANTICIPATED.key
)!!
)
anticipated = MappedCursorLiveData(
context,
Shows.SHOWS_ANTICIPATED,
ShowMapper.projection,
null,
null,
sortBy!!.sortOrder,
ShowListMapper
)
viewModelScope.launch {
if (System.currentTimeMillis() > SuggestionsTimestamps.get(context).getLong(
SuggestionsTimestamps.SHOWS_ANTICIPATED,
0L
) + SYNC_INTERNAL
) {
syncAnticipatedShows.invokeAsync(Unit)
}
}
}
fun setSortBy(sortBy: SortBy) {
this.sortBy = sortBy
anticipated.setSortOrder(sortBy.sortOrder)
}
override suspend fun onRefresh() {
syncAnticipatedShows.invokeSync(Unit)
}
companion object {
private const val SYNC_INTERNAL = DateUtils.DAY_IN_MILLIS
}
}
| apache-2.0 | 8bda2ce8515983b9ddd0926754e2e3d6 | 29.655172 | 82 | 0.753281 | 4.246815 | false | false | false | false |
PaulWoitaschek/Voice | scanner/src/main/kotlin/voice/app/scanner/FFProbeAnalyze.kt | 1 | 1255 | package voice.app.scanner
import android.content.Context
import androidx.documentfile.provider.DocumentFile
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import voice.ffmpeg.ffprobe
import voice.logging.core.Logger
import javax.inject.Inject
class FFProbeAnalyze
@Inject constructor(
private val context: Context,
) {
private val json = Json {
ignoreUnknownKeys = true
allowStructuredMapKeys = true
}
suspend fun analyze(file: DocumentFile): MetaDataScanResult? {
val result = ffprobe(
input = file.uri,
context = context,
command = listOf(
"-print_format", "json=c=1",
"-show_chapters",
"-loglevel", "quiet",
"-show_entries", "format=duration",
"-show_entries", "format_tags=artist,title,album",
"-show_entries", "stream_tags=artist,title,album",
"-select_streams", "a", // only select the audio stream
),
)
if (result == null) {
Logger.w("Unable to parse $file.")
return null
}
return try {
json.decodeFromString(MetaDataScanResult.serializer(), result)
} catch (e: SerializationException) {
Logger.w(e, "Unable to parse $file")
return null
}
}
}
| gpl-3.0 | 5d4d12aa255c53ec25837fe45a553d96 | 25.702128 | 68 | 0.664542 | 4.087948 | false | false | false | false |
colriot/anko | dsl/src/org/jetbrains/android/anko/generator/PropertyGenerator.kt | 1 | 3051 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.*
import org.jetbrains.android.anko.utils.MethodNodeWithClass
import org.jetbrains.android.anko.utils.fqName
import org.jetbrains.android.anko.utils.toProperty
import org.objectweb.asm.tree.MethodNode
class PropertyGenerator : Generator<PropertyElement> {
override fun generate(state: GenerationState) = with (state) {
val propertyGetters = availableMethods
.filter {
it.clazz.isView &&
it.method.isGetter() && !it.method.isOverridden && !it.method.isListenerGetter &&
!config.excludedProperties.contains(it.clazz.fqName + "#" + it.method.name) &&
!config.excludedProperties.contains(it.clazz.fqName + "#*")
}
.sortedBy { it.identifier }
val propertySetters = availableMethods
.filter { it.clazz.isView && it.method.isNonListenerSetter() && !it.method.isOverridden }
.groupBy { it.identifier }
genProperties(propertyGetters, propertySetters)
}
private fun GenerationState.genProperties(
getters: Collection<MethodNodeWithClass>,
setters: Map<String, List<MethodNodeWithClass>>): List<PropertyElement> {
val existingProperties = hashSetOf<String>()
val propertyWithGetters = getters.map { getter ->
val property = getter.toProperty()
val settersList = setters.get(property.setterIdentifier) ?: listOf()
val (best, others) = settersList.partition {
it.method.args.size == 1 && it.method.args[0] == getter.method.returnType
}
existingProperties.add(property.setterIdentifier)
PropertyElement(property.name, getter, best + others)
}
val propertyWithoutGetters = setters.values.map { setters ->
val property = setters.first().toProperty()
val id = property.setterIdentifier
if (property.propertyFqName in config.propertiesWithoutGetters && id !in existingProperties) {
PropertyElement(property.name, null, setters)
} else null
}.filterNotNull()
return propertyWithoutGetters + propertyWithGetters
}
private val MethodNode.isListenerGetter: Boolean
get() = name.startsWith("get") && name.endsWith("Listener")
} | apache-2.0 | 6d9a4064c1684915d495c52d2194473e | 40.808219 | 109 | 0.658473 | 4.737578 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/dialog/GenericErrorDialog.kt | 1 | 1538 | package za.org.grassroot2.view.dialog
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.dialog_generic_error.*
import kotlinx.android.synthetic.main.dialog_generic_error.view.*
import timber.log.Timber
import za.org.grassroot2.R
class GenericErrorDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = activity?.let { AlertDialog.Builder(it) }
val v = LayoutInflater.from(activity).inflate(R.layout.dialog_generic_error, null, false)
builder?.setView(v)
val d = builder?.create()
d?.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val errorMsgResID = arguments?.getInt(MSG_RES_ID_ARG)
errorMsgResID?.let { v?.title?.setText(it) }
v?.close?.setOnClickListener { dismiss() }
v?.done?.setOnClickListener { dismiss() }
return d
}
companion object {
private const val MSG_RES_ID_ARG = "MSG_RES_ID_ARG"
fun newInstance(dialogType: Int): DialogFragment {
val dialog = GenericErrorDialog()
val args = Bundle()
args.putInt(MSG_RES_ID_ARG, dialogType)
dialog.arguments = args
return dialog
}
}
}
| bsd-3-clause | 7cf413e07eb56f62935276e7563cfb11 | 32.434783 | 97 | 0.698309 | 4.202186 | false | false | false | false |
mattyway/PiBells | src/LedChaserTest.kt | 1 | 499 | fun main(args: Array<String>) {
val gpio = Gpio()
var increment = 1
var index = 0
var loops = 0
while (loops < 3) {
gpio.bellPins[index].pulse(150, true)
index += increment
if (index >= gpio.bellPins.size) {
index = gpio.bellPins.size - 2
increment = -1
}
if (index < 0) {
index = 1
increment = 1
loops++
}
}
println("Shutting down")
gpio.shutdown()
} | gpl-3.0 | 396aa67a8c33b90b0155093aa3a5f6df | 16.241379 | 45 | 0.466934 | 3.838462 | false | false | false | false |
JurajBegovac/RxKotlinTraits | testutils/src/main/kotlin/com/jurajbegovac/testutils/MyTestSubscriber.kt | 1 | 631 | package com.jurajbegovac.testutils
import rx.Subscriber
import rx.schedulers.TestScheduler
/** Created by juraj on 24/05/2017. */
class MyTestSubscriber<T>(private val scheduler: TestScheduler) : Subscriber<T>() {
private var values: List<Recorded<Event<T>>> = emptyList()
override fun onCompleted() {
values += Recorded(scheduler.now(), Event.Completed as Event<T>)
}
override fun onError(e: Throwable?) {
values += Recorded(scheduler.now(), Event.Error(e ?: Error("Unknown")))
}
override fun onNext(t: T) {
values += Recorded(scheduler.now(), Event.Next(t))
}
fun events() = values
}
| mit | 1a90a1936b04508253351fb9b17ec340 | 25.291667 | 83 | 0.679873 | 3.895062 | false | true | false | false |
jospint/Architecture-Components-DroidDevs | ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/view/forecast/ForecastActivity.kt | 1 | 3726 | package com.jospint.droiddevs.architecturecomponents.view.forecast
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.annotation.DrawableRes
import android.widget.Toast
import com.jospint.droiddevs.architecturecomponents.R
import com.jospint.droiddevs.architecturecomponents.data.googlemaps.model.PlaceResult
import com.jospint.droiddevs.architecturecomponents.model.Forecast
import com.jospint.droiddevs.architecturecomponents.util.Resource
import com.jospint.droiddevs.architecturecomponents.util.ResourceStatus
import com.jospint.droiddevs.architecturecomponents.util.extension.toPlace
import com.jospint.droiddevs.architecturecomponents.view.BaseActivity
import com.jospint.droiddevs.architecturecomponents.viewmodel.ForecastViewModel
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_forecast.*
import org.jetbrains.anko.act
import javax.inject.Inject
class ForecastActivity : BaseActivity() {
companion object {
private const val EXTRA_PLACE: String = "place";
fun buildIntent(context: Context, place: PlaceResult): Intent {
val intent = Intent(context, ForecastActivity::class.java)
intent.putExtra(EXTRA_PLACE, place);
return intent;
}
}
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
lateinit var forecastViewModel: ForecastViewModel
lateinit var placeResult: PlaceResult
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_forecast)
placeResult = intent.getParcelableExtra<PlaceResult>(EXTRA_PLACE)
forecastViewModel = ViewModelProviders.of(this, viewModelFactory).get(ForecastViewModel::class.java)
val location = placeResult.geometry!!.location!!;
forecastViewModel.getForecast(location.lat!!, location.lng!!).observe(this, Observer<Resource<Forecast>> { resource ->
when (resource!!.resourceStatus) {
ResourceStatus.SUCCESS -> {
forecastViewModel.saveForecast(placeResult.toPlace(), resource.data!!)
updateUI(resource.data)
}
ResourceStatus.ERROR -> Toast.makeText(this@ForecastActivity, "No forecast!!! :(", Toast.LENGTH_SHORT).show();
ResourceStatus.LOADING -> Toast.makeText(this@ForecastActivity, "Loading!", Toast.LENGTH_SHORT).show();
}
})
}
private fun updateUI(forecast: Forecast) {
forecast_locality.text = placeResult.name
forecast_weather_icon.setImageResource(iconFromIconId(forecast.iconId))
forecast_weather_description.text = forecast.description
forecast_temperature_text.text = forecast.temperature.toString()
forecast_wind_text.text = forecast.windSpeed.toString()
forecast_summary_text.text = forecast.prediction
}
@DrawableRes private fun iconFromIconId(iconId: String): Int {
return when (iconId) {
"clear-day" -> R.drawable.clear_day
"clear-night" -> R.drawable.clear_night
"rain" -> R.drawable.rain
"snow" -> R.drawable.snow
"sleet" -> R.drawable.sleet
"wind" -> R.drawable.wind
"fog" -> R.drawable.fog
"cloudy" -> R.drawable.cloudy
"partly-cloudy-day" -> R.drawable.partly_cloudy_day
"partly-cloudy-night" -> R.drawable.partly_cloudy_night
else -> R.mipmap.ic_launcher
}
}
} | apache-2.0 | 8c3ce9e47c5db0bb0877defa7ebf7193 | 42.847059 | 126 | 0.709608 | 4.680905 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/crafting/RefineryCraftingProcess.kt | 2 | 2000 | package com.cout970.magneticraft.misc.crafting
import com.cout970.magneticraft.api.MagneticraftApi
import com.cout970.magneticraft.api.registries.machines.refinery.IRefineryRecipe
import com.cout970.magneticraft.misc.fluid.Tank
import net.minecraftforge.fluids.FluidStack
class RefineryCraftingProcess(
val inputTank: Tank,
val outputTank0: Tank,
val outputTank1: Tank,
val outputTank2: Tank
) : ICraftingProcess {
private var cacheKey: FluidStack? = null
private var cacheValue: IRefineryRecipe? = null
private fun getRecipe(input: FluidStack): IRefineryRecipe? {
cacheKey?.let { key ->
if (key.fluid == input.fluid) return cacheValue
}
val recipe = MagneticraftApi.getRefineryRecipeManager().findRecipe(input)
cacheKey = input
cacheValue = recipe
return recipe
}
override fun craft() {
val input = inputTank.fluid ?: return
val recipe = getRecipe(input) ?: return
inputTank.drain(recipe.input.amount, true)
recipe.output0?.let { outputTank0.fill(it, true) }
recipe.output1?.let { outputTank1.fill(it, true) }
recipe.output2?.let { outputTank2.fill(it, true) }
}
override fun canCraft(): Boolean {
val input = inputTank.fluid ?: return false
//check recipe
val recipe = getRecipe(input) ?: return false
if (inputTank.fluidAmount < recipe.input.amount) return false
recipe.output0?.let { out ->
if ((outputTank0.capacity - outputTank0.fluidAmount) < out.amount) return false
}
recipe.output1?.let { out ->
if ((outputTank1.capacity - outputTank1.fluidAmount) < out.amount) return false
}
recipe.output2?.let { out ->
if ((outputTank2.capacity - outputTank2.fluidAmount) < out.amount) return false
}
return true
}
override fun duration(): Float = inputTank.fluid?.let { getRecipe(it) }?.duration ?: 10f
} | gpl-2.0 | c9c2a13192c9296d2926a444f60dec69 | 31.803279 | 92 | 0.6595 | 4.158004 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/command/repository/RedisTableEventRepository.kt | 1 | 1475 | package com.flexpoker.table.command.repository
import com.flexpoker.config.ProfileNames
import com.flexpoker.exception.FlexPokerException
import com.flexpoker.table.command.events.TableEvent
import org.springframework.context.annotation.Profile
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Repository
import java.util.UUID
import javax.inject.Inject
@Profile(ProfileNames.REDIS, ProfileNames.TABLE_COMMAND_REDIS)
@Repository
class RedisTableEventRepository @Inject constructor(
private val redisTemplate: RedisTemplate<String, TableEvent>
) : TableEventRepository {
companion object {
private const val TABLE_EVENT_NAMESPACE = "table-event:"
}
override fun fetchAll(id: UUID): List<TableEvent> {
return redisTemplate.opsForList().range(TABLE_EVENT_NAMESPACE + id, 0, Long.MAX_VALUE)
}
override fun setEventVersionsAndSave(basedOnVersion: Int, events: List<TableEvent>): List<TableEvent> {
val aggregateId = events[0].aggregateId
val existingEvents = fetchAll(aggregateId)
if (existingEvents.size != basedOnVersion) {
throw FlexPokerException("events to save are based on a different version of the aggregate")
}
for (i in events.indices) {
events[i].version = basedOnVersion + i + 1
}
redisTemplate.opsForList().rightPushAll(TABLE_EVENT_NAMESPACE + aggregateId, events)
return events
}
} | gpl-2.0 | effd9e3886cb3530cf89094543c07600 | 36.846154 | 107 | 0.741695 | 4.338235 | false | false | false | false |
wiltonlazary/kotlin-native | endorsedLibraries/kotlinx.cli/src/main/kotlin/kotlinx/cli/ArgParser.kt | 1 | 27083 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlinx.cli
import kotlin.reflect.KProperty
internal expect fun exitProcess(status: Int): Nothing
/**
* Queue of arguments descriptors.
* Arguments can have several values, so one descriptor can be returned several times.
*/
internal class ArgumentsQueue(argumentsDescriptors: List<ArgDescriptor<*, *>>) {
/**
* Map of arguments descriptors and their current usage number.
*/
private val argumentsUsageNumber = linkedMapOf(*argumentsDescriptors.map { it to 0 }.toTypedArray())
/**
* Get next descriptor from queue.
*/
fun pop(): String? {
if (argumentsUsageNumber.isEmpty())
return null
val (currentDescriptor, usageNumber) = argumentsUsageNumber.iterator().next()
currentDescriptor.number?.let {
// Parse all arguments for current argument description.
if (usageNumber + 1 >= currentDescriptor.number) {
// All needed arguments were provided.
argumentsUsageNumber.remove(currentDescriptor)
} else {
argumentsUsageNumber[currentDescriptor] = usageNumber + 1
}
}
return currentDescriptor.fullName
}
}
/**
* A property delegate that provides access to the argument/option value.
*/
interface ArgumentValueDelegate<T> {
/**
* The value of an option or argument parsed from command line.
*
* Accessing this value before [ArgParser.parse] method is called will result in an exception.
*
* @see CLIEntity.value
*/
var value: T
/** Provides the value for the delegated property getter. Returns the [value] property.
* @throws IllegalStateException in case of accessing the value before [ArgParser.parse] method is called.
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
/** Sets the [value] to the [ArgumentValueDelegate.value] property from the delegated property setter.
* This operation is possible only after command line arguments were parsed with [ArgParser.parse]
* @throws IllegalStateException in case of resetting value before command line arguments are parsed.
*/
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
/**
* Abstract base class for subcommands.
*/
@ExperimentalCli
abstract class Subcommand(val name: String, val actionDescription: String): ArgParser(name) {
/**
* Execute action if subcommand was provided.
*/
abstract fun execute()
val helpMessage: String
get() = " $name - $actionDescription\n"
}
/**
* Argument parsing result.
* Contains name of subcommand which was called.
*
* @property commandName name of command which was called.
*/
class ArgParserResult(val commandName: String)
/**
* Arguments parser.
*
* @property programName the name of the current program.
* @property useDefaultHelpShortName specifies whether to register "-h" option for printing the usage information.
* @property prefixStyle the style of option prefixing.
* @property skipExtraArguments specifies whether the extra unmatched arguments in a command line string
* can be skipped without producing an error message.
*/
open class ArgParser(
val programName: String,
var useDefaultHelpShortName: Boolean = true,
var prefixStyle: OptionPrefixStyle = OptionPrefixStyle.LINUX,
var skipExtraArguments: Boolean = false
) {
/**
* Map of options: key - full name of option, value - pair of descriptor and parsed values.
*/
private val options = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Map of arguments: key - full name of argument, value - pair of descriptor and parsed values.
*/
private val arguments = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Map with declared options.
*/
private val declaredOptions = mutableListOf<CLIEntityWrapper>()
/**
* Map with declared arguments.
*/
private val declaredArguments = mutableListOf<CLIEntityWrapper>()
/**
* State of parser. Stores last parsing result or null.
*/
private var parsingState: ArgParserResult? = null
/**
* Map of subcommands.
*/
@OptIn(ExperimentalCli::class)
protected val subcommands = mutableMapOf<String, Subcommand>()
/**
* Mapping for short options names for quick search.
*/
private val shortNames = mutableMapOf<String, ParsingValue<*, *>>()
/**
* Used prefix form for full option form.
*/
private val optionFullFormPrefix = if (prefixStyle == OptionPrefixStyle.JVM) "-" else "--"
/**
* Used prefix form for short option form.
*/
private val optionShortFromPrefix = "-"
/**
* Name with all commands that should be executed.
*/
protected val fullCommandName = mutableListOf(programName)
/**
* Flag to recognize if CLI entities can be treated as options.
*/
protected var treatAsOption = true
/**
* The way an option/argument has got its value.
*/
enum class ValueOrigin {
/* The value was parsed from command line arguments. */
SET_BY_USER,
/* The value was missing in command line, therefore the default value was used. */
SET_DEFAULT_VALUE,
/* The value is not initialized by command line values or by default values. */
UNSET,
/* The value was redefined after parsing manually (usually with the property setter). */
REDEFINED,
/* The value is undefined, because parsing wasn't called. */
UNDEFINED
}
/**
* The style of option prefixing.
*/
enum class OptionPrefixStyle {
/* Linux style: the full name of an option is prefixed with two hyphens "--" and the short name — with one "-". */
LINUX,
/* JVM style: both full and short names are prefixed with one hyphen "-". */
JVM,
/* GNU style: the full name of an option is prefixed with two hyphens "--" and "=" between options and value
and the short name — with one "-".
Detailed information https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
*/
GNU
}
@Deprecated("OPTION_PREFIX_STYLE is deprecated. Please, use OptionPrefixStyle.",
ReplaceWith("OptionPrefixStyle", "kotlinx.cli.OptionPrefixStyle"))
@Suppress("TOPLEVEL_TYPEALIASES_ONLY")
typealias OPTION_PREFIX_STYLE = OptionPrefixStyle
/**
* Declares a named option and returns an object which can be used to access the option value
* after all arguments are parsed or to delegate a property for accessing the option value to.
*
* By default, the option supports only a single value, is optional, and has no default value,
* therefore its value's type is `T?`.
*
* You can alter the option properties by chaining extensions for the option type on the returned object:
* - [AbstractSingleOption.default] to provide a default value that is used when the option is not specified;
* - [SingleNullableOption.required] to make the option non-optional;
* - [AbstractSingleOption.delimiter] to allow specifying multiple values in one command line argument with a delimiter;
* - [AbstractSingleOption.multiple] to allow specifying the option several times.
*
* @param type The type describing how to parse an option value from a string,
* an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice].
* @param fullName the full name of the option, can be omitted if the option name is inferred
* from the name of a property delegated to this option.
* @param shortName the short name of the option, `null` if the option cannot be specified in a short form.
* @param description the description of the option used when rendering the usage information.
* @param deprecatedWarning the deprecation message for the option.
* Specifying anything except `null` makes this option deprecated. The message is rendered in a help message and
* issued as a warning when the option is encountered when parsing command line arguments.
*/
fun <T : Any> option(
type: ArgType<T>,
fullName: String? = null,
shortName: String ? = null,
description: String? = null,
deprecatedWarning: String? = null
): SingleNullableOption<T> {
if (prefixStyle == OptionPrefixStyle.GNU && shortName != null)
require(shortName.length == 1) {
"""
GNU standart for options allow to use short form whuch consists of one character.
For more information, please, see https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
""".trimIndent()
}
val option = SingleNullableOption(OptionDescriptor(optionFullFormPrefix, optionShortFromPrefix, type,
fullName, shortName, description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper())
option.owner.entity = option
declaredOptions.add(option.owner)
return option
}
/**
* Check usage of required property for arguments.
* Make sense only for several last arguments.
*/
private fun inspectRequiredAndDefaultUsage() {
var previousArgument: ParsingValue<*, *>? = null
arguments.forEach { (_, currentArgument) ->
previousArgument?.let { previous ->
// Previous argument has default value.
if (previous.descriptor.defaultValueSet) {
if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) {
error("Default value of argument ${previous.descriptor.fullName} will be unused, " +
"because next argument ${currentArgument.descriptor.fullName} is always required and has no default value.")
}
}
// Previous argument is optional.
if (!previous.descriptor.required) {
if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) {
error("Argument ${previous.descriptor.fullName} will be always required, " +
"because next argument ${currentArgument.descriptor.fullName} is always required.")
}
}
}
previousArgument = currentArgument
}
}
/**
* Declares an argument and returns an object which can be used to access the argument value
* after all arguments are parsed or to delegate a property for accessing the argument value to.
*
* By default, the argument supports only a single value, is required, and has no default value,
* therefore its value's type is `T`.
*
* You can alter the argument properties by chaining extensions for the argument type on the returned object:
* - [AbstractSingleArgument.default] to provide a default value that is used when the argument is not specified;
* - [SingleArgument.optional] to allow omitting the argument;
* - [AbstractSingleArgument.multiple] to require the argument to have exactly the number of values specified;
* - [AbstractSingleArgument.vararg] to allow specifying an unlimited number of values for the _last_ argument.
*
* @param type The type describing how to parse an option value from a string,
* an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice].
* @param fullName the full name of the argument, can be omitted if the argument name is inferred
* from the name of a property delegated to this argument.
* @param description the description of the argument used when rendering the usage information.
* @param deprecatedWarning the deprecation message for the argument.
* Specifying anything except `null` makes this argument deprecated. The message is rendered in a help message and
* issued as a warning when the argument is encountered when parsing command line arguments.
*/
fun <T : Any> argument(
type: ArgType<T>,
fullName: String? = null,
description: String? = null,
deprecatedWarning: String? = null
) : SingleArgument<T, DefaultRequiredType.Required> {
val argument = SingleArgument<T, DefaultRequiredType.Required>(ArgDescriptor(type, fullName, 1,
description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper())
argument.owner.entity = argument
declaredArguments.add(argument.owner)
return argument
}
/**
* Registers one or more subcommands.
*
* @param subcommandsList subcommands to add.
*/
@ExperimentalCli
fun subcommands(vararg subcommandsList: Subcommand) {
subcommandsList.forEach {
if (it.name in subcommands) {
error("Subcommand with name ${it.name} was already defined.")
}
// Set same settings as main parser.
it.prefixStyle = prefixStyle
it.useDefaultHelpShortName = useDefaultHelpShortName
fullCommandName.forEachIndexed { index, namePart ->
it.fullCommandName.add(index, namePart)
}
subcommands[it.name] = it
}
}
/**
* Outputs an error message adding the usage information after it.
*
* @param message error message.
*/
fun printError(message: String): Nothing {
error("$message\n${makeUsage()}")
}
/**
* Save value as argument value.
*
* @param arg string with argument value.
* @param argumentsQueue queue with active argument descriptors.
*/
private fun saveAsArg(arg: String, argumentsQueue: ArgumentsQueue): Boolean {
// Find next uninitialized arguments.
val name = argumentsQueue.pop()
name?.let {
val argumentValue = arguments[name]!!
argumentValue.descriptor.deprecatedWarning?.let { printWarning(it) }
argumentValue.addValue(arg)
return true
}
return false
}
/**
* Treat value as argument value.
*
* @param arg string with argument value.
* @param argumentsQueue queue with active argument descriptors.
*/
private fun treatAsArgument(arg: String, argumentsQueue: ArgumentsQueue) {
if (!saveAsArg(arg, argumentsQueue)) {
printError("Too many arguments! Couldn't process argument $arg!")
}
}
/**
* Save value as option value.
*/
private fun <T : Any, U: Any> saveAsOption(parsingValue: ParsingValue<T, U>, value: String) {
parsingValue.addValue(value)
}
/**
* Try to recognize and save command line element as full form of option.
*
* @param candidate string with candidate in options.
* @param argIterator iterator over command line arguments.
*/
private fun recognizeAndSaveOptionFullForm(candidate: String, argIterator: Iterator<String>): Boolean {
if (prefixStyle == OptionPrefixStyle.GNU && candidate == optionFullFormPrefix) {
// All other arguments after `--` are treated as non-option arguments.
treatAsOption = false
return false
}
if (!candidate.startsWith(optionFullFormPrefix))
return false
val optionString = candidate.substring(optionFullFormPrefix.length)
val argValue = if (prefixStyle == OptionPrefixStyle.GNU) null else options[optionString]
if (argValue != null) {
saveStandardOptionForm(argValue, argIterator)
return true
} else {
// Check GNU style of options.
if (prefixStyle == OptionPrefixStyle.GNU) {
// Option without a parameter.
if (options[optionString]?.descriptor?.type?.hasParameter == false) {
saveOptionWithoutParameter(options[optionString]!!)
return true
}
// Option with parameters.
val optionParts = optionString.split('=', limit = 2)
if (optionParts.size != 2)
return false
if (options[optionParts[0]] != null) {
saveAsOption(options[optionParts[0]]!!, optionParts[1])
return true
}
}
}
return false
}
/**
* Save option without parameter.
*
* @param argValue argument value with all information about option.
*/
private fun saveOptionWithoutParameter(argValue: ParsingValue<*, *>) {
// Boolean flags.
if (argValue.descriptor.fullName == "help") {
println(makeUsage())
exitProcess(0)
}
saveAsOption(argValue, "true")
}
/**
* Save option described with standard separated form `--name value`.
*
* @param argValue argument value with all information about option.
* @param argIterator iterator over command line arguments.
*/
private fun saveStandardOptionForm(argValue: ParsingValue<*, *>, argIterator: Iterator<String>) {
if (argValue.descriptor.type.hasParameter) {
if (argIterator.hasNext()) {
saveAsOption(argValue, argIterator.next())
} else {
// An error, option with value without value.
printError("No value for ${argValue.descriptor.textDescription}")
}
} else {
saveOptionWithoutParameter(argValue)
}
}
/**
* Try to recognize and save command line element as short form of option.
*
* @param candidate string with candidate in options.
* @param argIterator iterator over command line arguments.
*/
private fun recognizeAndSaveOptionShortForm(candidate: String, argIterator: Iterator<String>): Boolean {
if (!candidate.startsWith(optionShortFromPrefix) ||
optionFullFormPrefix != optionShortFromPrefix && candidate.startsWith(optionFullFormPrefix)) return false
// Try to find exact match.
val option = candidate.substring(optionShortFromPrefix.length)
val argValue = shortNames[option]
if (argValue != null) {
saveStandardOptionForm(argValue, argIterator)
} else {
if (prefixStyle != OptionPrefixStyle.GNU || option.isEmpty())
return false
// Try to find collapsed form.
val firstOption = shortNames["${option[0]}"] ?: return false
// Form with value after short form without separator.
if (firstOption.descriptor.type.hasParameter) {
saveAsOption(firstOption, option.substring(1))
} else {
// Form with several short forms as one string.
val otherBooleanOptions = option.substring(1)
saveOptionWithoutParameter(firstOption)
for (opt in otherBooleanOptions) {
shortNames["$opt"]?.let {
if (it.descriptor.type.hasParameter) {
printError(
"Option $optionShortFromPrefix$opt can't be used in option combination $candidate, " +
"because parameter value of type ${it.descriptor.type.description} should be " +
"provided for current option."
)
}
}?: printError("Unknown option $optionShortFromPrefix$opt in option combination $candidate.")
saveOptionWithoutParameter(shortNames["$opt"]!!)
}
}
}
return true
}
/**
* Parses the provided array of command line arguments.
* After a successful parsing, the options and arguments declared in this parser get their values and can be accessed
* with the properties delegated to them.
*
* @param args the array with command line arguments.
*
* @return an [ArgParserResult] if all arguments were parsed successfully.
* Otherwise, prints the usage information and terminates the program execution.
* @throws IllegalStateException in case of attempt of calling parsing several times.
*/
fun parse(args: Array<String>): ArgParserResult = parse(args.asList())
protected fun parse(args: List<String>): ArgParserResult {
check(parsingState == null) { "Parsing of command line options can be called only once." }
// Add help option.
val helpDescriptor = if (useDefaultHelpShortName) OptionDescriptor<Boolean, Boolean>(
optionFullFormPrefix,
optionShortFromPrefix, ArgType.Boolean,
"help", "h", "Usage info"
)
else OptionDescriptor(
optionFullFormPrefix, optionShortFromPrefix,
ArgType.Boolean, "help", description = "Usage info"
)
val helpOption = SingleNullableOption(helpDescriptor, CLIEntityWrapper())
helpOption.owner.entity = helpOption
declaredOptions.add(helpOption.owner)
// Add default list with arguments if there can be extra free arguments.
if (skipExtraArguments) {
argument(ArgType.String, "").vararg()
}
// Clean options and arguments maps.
options.clear()
arguments.clear()
// Map declared options and arguments to maps.
declaredOptions.forEachIndexed { index, option ->
val value = option.entity?.delegate as ParsingValue<*, *>
value.descriptor.fullName?.let {
// Add option.
if (options.containsKey(it)) {
error("Option with full name $it was already added.")
}
with(value.descriptor as OptionDescriptor) {
if (shortName != null && shortNames.containsKey(shortName)) {
error("Option with short name ${shortName} was already added.")
}
shortName?.let {
shortNames[it] = value
}
}
options[it] = value
} ?: error("Option was added, but unnamed. Added option under №${index + 1}")
}
declaredArguments.forEachIndexed { index, argument ->
val value = argument.entity?.delegate as ParsingValue<*, *>
value.descriptor.fullName?.let {
// Add option.
if (arguments.containsKey(it)) {
error("Argument with full name $it was already added.")
}
arguments[it] = value
} ?: error("Argument was added, but unnamed. Added argument under №${index + 1}")
}
// Make inspections for arguments.
inspectRequiredAndDefaultUsage()
listOf(arguments, options).forEach {
it.forEach { (_, value) ->
value.valueOrigin = ValueOrigin.UNSET
}
}
val argumentsQueue = ArgumentsQueue(arguments.map { it.value.descriptor as ArgDescriptor<*, *> })
val argIterator = args.listIterator()
try {
while (argIterator.hasNext()) {
val arg = argIterator.next()
// Check for subcommands.
@OptIn(ExperimentalCli::class)
subcommands.forEach { (name, subcommand) ->
if (arg == name) {
// Use parser for this subcommand.
subcommand.parse(args.slice(argIterator.nextIndex() until args.size))
subcommand.execute()
parsingState = ArgParserResult(name)
return parsingState!!
}
}
// Parse arguments from command line.
if (treatAsOption && arg.startsWith('-')) {
// Candidate in being option.
// Option is found.
if (!(recognizeAndSaveOptionShortForm(arg, argIterator) ||
recognizeAndSaveOptionFullForm(arg, argIterator))) {
// State is changed so next options are arguments.
if (!treatAsOption) {
// Argument is found.
treatAsArgument(argIterator.next(), argumentsQueue)
} else {
// Try save as argument.
if (!saveAsArg(arg, argumentsQueue)) {
printError("Unknown option $arg")
}
}
}
} else {
// Argument is found.
treatAsArgument(arg, argumentsQueue)
}
}
// Postprocess results of parsing.
options.values.union(arguments.values).forEach { value ->
// Not inited, append default value if needed.
if (value.isEmpty()) {
value.addDefaultValue()
}
if (value.valueOrigin != ValueOrigin.SET_BY_USER && value.descriptor.required) {
printError("Value for ${value.descriptor.textDescription} should be always provided in command line.")
}
}
} catch (exception: ParsingException) {
printError(exception.message!!)
}
parsingState = ArgParserResult(programName)
return parsingState!!
}
/**
* Creates a message with the usage information.
*/
internal fun makeUsage(): String {
val result = StringBuilder()
result.append("Usage: ${fullCommandName.joinToString(" ")} options_list\n")
if (subcommands.isNotEmpty()) {
result.append("Subcommands: \n")
subcommands.forEach { (_, subcommand) ->
result.append(subcommand.helpMessage)
}
result.append("\n")
}
if (arguments.isNotEmpty()) {
result.append("Arguments: \n")
arguments.forEach {
result.append(it.value.descriptor.helpMessage)
}
}
if (options.isNotEmpty()) {
result.append("Options: \n")
options.forEach {
result.append(it.value.descriptor.helpMessage)
}
}
return result.toString()
}
}
/**
* Output warning.
*
* @param message warning message.
*/
internal fun printWarning(message: String) {
println("WARNING $message")
} | apache-2.0 | ffade9cac8abfff512ad5b679c7deb25 | 39.777108 | 140 | 0.609086 | 5.259324 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/doc/lexer/RsDocHighlightingLexer.kt | 1 | 1172 | package org.rust.lang.doc.lexer
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.lexer.MergeFunction
import com.intellij.lexer.MergingLexerAdapter
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.psi.tree.TokenSet
import org.rust.lang.doc.psi.RsDocElementTypes.*
import org.rust.lang.doc.psi.RsDocKind
class RsDocHighlightingLexer(kind: RsDocKind) :
MergingLexerAdapter(
FlexAdapter(_RustDocHighlightingLexer(null, kind.isBlock)),
TOKENS_TO_MERGE) {
override fun getMergeFunction() = MergeFunction { type, lexer ->
if (type == DOC_TEXT) {
while (lexer.tokenType == type || isOnNonEolWS(lexer)) {
lexer.advance()
}
type
} else {
super.getMergeFunction().merge(type, lexer)
}
}
private fun isOnNonEolWS(lexer: Lexer) =
lexer.tokenType == WHITE_SPACE && !StringUtil.containsLineBreak(lexer.tokenSequence)
companion object {
private val TOKENS_TO_MERGE = TokenSet.create(WHITE_SPACE, DOC_CODE_SPAN, DOC_CODE_FENCE)
}
}
| mit | 3d32a02e058879810706107f2c11a9dd | 31.555556 | 97 | 0.692833 | 3.946128 | false | false | false | false |
d9n/intellij-rust | src/test/kotlin/org/rust/lang/core/completion/RsCompletionTestBase.kt | 1 | 4540 | package org.rust.lang.core.completion
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
abstract class RsCompletionTestBase : RsTestBase() {
protected fun checkSingleCompletion(target: String, @Language("Rust") code: String) {
InlineFile(code).withCaret()
singleCompletionCheck(target)
}
protected fun checkSingleCompletionWithMultipleFiles(target: String, @Language("Rust") code: String) {
val files = ProjectFile.parseFileCollection(code)
for ((path, text) in files) {
myFixture.tempDirFixture.createFile(path, replaceCaretMarker(text))
}
openFileInEditor(files[0].path)
singleCompletionCheck(target)
}
protected fun singleCompletionCheck(target: String) {
val variants = myFixture.completeBasic()
fun LookupElement.debug(): String = "$lookupString ($psiElement)"
check(variants == null) {
"Expected a single completion, but got ${variants.size}:\n" +
variants.map { it.debug() }.joinToString("\n")
}
val normName = target
.substringBeforeLast("()")
.substringBeforeLast(" {}")
.substringAfterLast("::")
.substringAfterLast(".")
val shift = when {
target.endsWith("()") || target.endsWith("::") -> 3
target.endsWith(" {}") -> 4
else -> 2
}
val element = myFixture.file.findElementAt(myFixture.caretOffset - shift)!!
val skipTextCheck = normName.isEmpty() || normName.contains(' ')
check((skipTextCheck || element.text == normName) && (element.fitsHierarchically(target) || element.fitsLinearly(target))) {
"Wrong completion, expected `$target`, but got\n${myFixture.file.text}"
}
}
protected fun checkContainsCompletion(text: String, @Language("Rust") code: String) {
InlineFile(code).withCaret()
val variants = myFixture.completeBasic()
checkNotNull(variants) {
"Expected completions that contain $text, but no completions found"
}
variants.filter { it.lookupString == text }.forEach { return }
error("Expected completions that contain $text, but got ${variants.toList()}")
}
protected fun checkNoCompletion(@Language("Rust") code: String) {
InlineFile(code).withCaret()
noCompletionCheck()
}
protected fun checkNoCompletionWithMultipleFiles(@Language("Rust") code: String) {
val files = ProjectFile.parseFileCollection(code)
for ((path, text) in files) {
myFixture.tempDirFixture.createFile(path, replaceCaretMarker(text))
}
openFileInEditor(files[0].path)
noCompletionCheck()
}
protected fun noCompletionCheck() {
val variants = myFixture.completeBasic()
checkNotNull(variants) {
val element = myFixture.file.findElementAt(myFixture.caretOffset - 1)
"Expected zero completions, but one completion was auto inserted: `${element?.text}`."
}
check(variants.isEmpty()) {
"Expected zero completions, got ${variants.size}."
}
}
protected fun executeSoloCompletion() {
val variants = myFixture.completeBasic()
if (variants != null) {
error("Expected a single completion, but got ${variants.size}\n" +
"${variants.toList()}")
}
}
private fun PsiElement.fitsHierarchically(target: String): Boolean = when {
text == target -> true
text.length > target.length -> false
parent != null -> parent.fitsHierarchically(target)
else -> false
}
private fun PsiElement.fitsLinearly(target: String) =
checkLinearly(target, Direction.LEFT) || checkLinearly(target, Direction.RIGHT)
private fun PsiElement.checkLinearly(target: String, direction: Direction): Boolean {
var el = this
var text = ""
while (text.length < target.length) {
text = if (direction == Direction.LEFT) el.text + text else text + el.text
if (text == target) return true
el = (if (direction == Direction.LEFT) PsiTreeUtil.prevVisibleLeaf(el) else PsiTreeUtil.nextVisibleLeaf(el)) ?: break
}
return false
}
private enum class Direction {
LEFT,
RIGHT
}
}
| mit | d9db0f7a1320263afbbcddadc3d33adc | 36.833333 | 132 | 0.630617 | 4.814422 | false | false | false | false |
ivaneye/kt-jvm | src/com/ivaneye/ktjvm/model/constant/ConstantFieldRef.kt | 1 | 858 | package com.ivaneye.ktjvm.model.constant
import com.ivaneye.ktjvm.model.ClassInfo
import com.ivaneye.ktjvm.type.U1
import com.ivaneye.ktjvm.type.U2
/**
* Created by wangyifan on 2017/5/22.
*/
class ConstantFieldRef(val tag: U1, val classIndex: U2, val nameAndTypeIndex: U2, val classInfo: ClassInfo) : Constant {
override fun type(): String {
return "Field"
}
override fun value(): String {
val clzIdx = classIndex.toInt()
val nameIdx = nameAndTypeIndex.toInt()
val clzVal = classInfo.cpInfos[clzIdx]!!.value()
val nameVal = classInfo.cpInfos[nameIdx]!!.value()
return "$clzVal.$nameVal"
}
override fun toString(): String {
val clzIdx = classIndex.toInt()
val nameIdx = nameAndTypeIndex.toInt()
return "${type()} #$clzIdx.#$nameIdx // ${value()}"
}
} | apache-2.0 | 15ece908aa6a167b2d3f4565276b3719 | 29.678571 | 120 | 0.646853 | 3.746725 | false | false | false | false |
pyamsoft/padlock | padlock-base/src/main/java/com/pyamsoft/padlock/base/PackageManagerWrapperImpl.kt | 1 | 6699 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.base
import android.content.ComponentName
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.annotation.CheckResult
import com.pyamsoft.padlock.api.packagemanager.PackageActivityManager
import com.pyamsoft.padlock.api.packagemanager.PackageApplicationManager
import com.pyamsoft.padlock.api.packagemanager.PackageLabelManager
import com.pyamsoft.padlock.api.preferences.LockListPreferences
import com.pyamsoft.padlock.model.ApplicationItem
import com.pyamsoft.padlock.model.Excludes
import com.pyamsoft.pydroid.core.optional.Optional.Present
import com.pyamsoft.pydroid.core.optional.asOptional
import com.pyamsoft.pydroid.core.threads.Enforcer
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.exceptions.Exceptions
import timber.log.Timber
import java.util.ArrayList
import javax.inject.Inject
import javax.inject.Singleton
internal class PackageManagerWrapperImpl @Inject internal constructor(
context: Context,
private val enforcer: Enforcer,
private val listPreferences: LockListPreferences
) : PackageActivityManager, PackageApplicationManager, PackageLabelManager {
private val packageManager = context.applicationContext.packageManager
private val defaultIcon: Drawable by lazy { packageManager.defaultActivityIcon }
override fun getDefaultActivityIcon(): Drawable {
return defaultIcon
}
override fun getActivityListForPackage(packageName: String): Single<List<String>> {
return Single.fromCallable {
enforcer.assertNotOnMainThread()
val activityEntries: MutableList<String> = ArrayList()
try {
val packageInfo = packageManager.getPackageInfo(
packageName,
PackageManager.GET_ACTIVITIES
)
packageInfo.activities?.mapTo(activityEntries) { it.name }
} catch (e: Exception) {
Timber.e(e, "PackageManager error, return what we have for %s", packageName)
}
return@fromCallable activityEntries
}
.flatMapObservable {
enforcer.assertNotOnMainThread()
return@flatMapObservable Observable.fromIterable(it)
}
.filter { !Excludes.isLockScreen(packageName, it) }
.filter { !Excludes.isPackageExcluded(packageName) }
.filter { !Excludes.isClassExcluded(it) }
.toSortedList()
}
@CheckResult
private fun getInstalledApplications(): Observable<ApplicationItem> {
return Single.fromCallable {
enforcer.assertNotOnMainThread()
return@fromCallable packageManager.getInstalledApplications(0)
}
.flatMapObservable {
enforcer.assertNotOnMainThread()
return@flatMapObservable Observable.fromIterable(it)
}
.flatMapSingle {
enforcer.assertNotOnMainThread()
return@flatMapSingle getApplicationInfo(it)
}
.filter { !it.isEmpty() }
}
override fun getActiveApplications(): Single<List<ApplicationItem>> {
return getInstalledApplications().flatMap {
enforcer.assertNotOnMainThread()
return@flatMap when {
!it.enabled -> Observable.empty()
it.system && !listPreferences.isSystemVisible() -> Observable.empty()
Excludes.isPackageExcluded(it.packageName) -> Observable.empty()
else -> Observable.just(it)
}
}
.toList()
}
@CheckResult
private fun getApplicationInfo(info: ApplicationInfo?): Single<ApplicationItem> {
return Single.fromCallable {
enforcer.assertNotOnMainThread()
return@fromCallable when (info) {
null -> ApplicationItem.EMPTY
else -> ApplicationItem.create(info.packageName, info.icon, info.system(), info.enabled)
}
}
}
override fun getApplicationInfo(packageName: String): Single<ApplicationItem> {
return Single.defer {
enforcer.assertNotOnMainThread()
var info: ApplicationInfo?
try {
info = packageManager.getApplicationInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
Timber.e(e, "Error getApplicationInfo: '$packageName'")
info = null
}
return@defer getApplicationInfo(info)
}
}
@CheckResult
private fun ApplicationInfo.system(): Boolean = flags and ApplicationInfo.FLAG_SYSTEM != 0
override fun loadPackageLabel(packageName: String): Single<String> {
return Single.defer {
enforcer.assertNotOnMainThread()
try {
return@defer Single.just(
packageManager.getApplicationInfo(packageName, 0).asOptional()
)
} catch (e: PackageManager.NameNotFoundException) {
Timber.e(e, "Error loadPackageLabel: '$packageName'")
throw Exceptions.propagate(e)
}
}
.flatMap {
enforcer.assertNotOnMainThread()
return@flatMap when (it) {
is Present -> loadPackageLabel(it.value)
else -> Single.just("")
}
}
}
@CheckResult
private fun loadPackageLabel(info: ApplicationInfo): Single<String> = Single.fromCallable {
enforcer.assertNotOnMainThread()
return@fromCallable info.loadLabel(packageManager)
.toString()
}
override fun isValidActivity(
packageName: String,
activityName: String
): Single<Boolean> {
return Single.defer {
enforcer.assertNotOnMainThread()
if (packageName.isEmpty() || activityName.isEmpty()) {
return@defer Single.just(false)
}
val componentName = ComponentName(packageName, activityName)
try {
val info: ActivityInfo? = packageManager.getActivityInfo(componentName, 0)
return@defer Single.just(info != null)
} catch (e: PackageManager.NameNotFoundException) {
// We intentionally leave out the throwable in the call to Timber or logs get too noisy
Timber.e("Could not get ActivityInfo for: '$packageName', '$activityName'")
return@defer Single.just(false)
}
}
}
}
| apache-2.0 | 5a0d03efcc51abf83af4a1c3fd6d8a4d | 34.444444 | 96 | 0.712047 | 4.89693 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/platform/SpannableExtensionsTest.kt | 3 | 22343 | /*
* 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.compose.ui.text.platform
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.matchers.assertThat
import androidx.compose.ui.text.platform.extensions.flattenFontStylesAndApply
import androidx.compose.ui.text.platform.extensions.setSpanStyles
import androidx.compose.ui.text.platform.style.ShaderBrushSpan
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.sp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argThat
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyInt
@RunWith(AndroidJUnit4::class)
@SmallTest
class SpannableExtensionsTest {
@Test
fun flattenStylesAndApply_emptyList() {
val spanStyles = listOf<AnnotatedString.Range<SpanStyle>>()
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
verify(block, never()).invoke(any(), anyInt(), anyInt())
}
@Test
fun flattenStylesAndApply_oneStyle() {
val spanStyle = SpanStyle(fontWeight = FontWeight(123))
val start = 4
val end = 10
val spanStyles = listOf(
AnnotatedString.Range(spanStyle, start, end)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
verify(block, times(1)).invoke(spanStyle, start, end)
}
@Test
fun flattenStylesAndApply_containedByOldStyle() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 4, 6)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1, 3, 4)
verify(block).invoke(spanStyle1.merge(spanStyle2), 4, 6)
verify(block).invoke(spanStyle1, 6, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_containedByOldStyle_sharedStart() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 3, 6)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1.merge(spanStyle2), 3, 6)
verify(block).invoke(spanStyle1, 6, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_containedByOldStyle_sharedEnd() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 5, 10)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1, 3, 5)
verify(block).invoke(spanStyle1.merge(spanStyle2), 5, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_sameRange() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 3, 10)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1.merge(spanStyle2), 3, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_overlappingStyles() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 6, 19)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1, 3, 6)
verify(block).invoke(spanStyle1.merge(spanStyle2), 6, 10)
verify(block).invoke(spanStyle2, 10, 19)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_notIntersectedStyles() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 4),
AnnotatedString.Range(spanStyle2, 8, 10)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1, 3, 4)
verify(block).invoke(spanStyle2, 8, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_containedByOldStyle_appliedInOrder() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontWeight = FontWeight(200))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 3, 10),
AnnotatedString.Range(spanStyle2, 5, 9)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle1, 3, 5)
// spanStyle2 will overwrite spanStyle1 in [5, 9).
verify(block).invoke(spanStyle2, 5, 9)
verify(block).invoke(spanStyle1, 9, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_containsOldStyle_appliedInOrder() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(123))
val spanStyle2 = SpanStyle(fontWeight = FontWeight(200))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 5, 7),
AnnotatedString.Range(spanStyle2, 3, 10)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
// Ideally we can only have 1 spanStyle, but it will overcomplicate the code.
verify(block).invoke(spanStyle2, 3, 5)
// spanStyle2 will overwrite spanStyle1 in [5, 7).
verify(block).invoke(spanStyle2, 5, 7)
verify(block).invoke(spanStyle2, 7, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_notIntersected_appliedInIndexOrder() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(100))
val spanStyle2 = SpanStyle(fontWeight = FontWeight(200))
val spanStyle3 = SpanStyle(fontWeight = FontWeight(300))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle3, 7, 8),
AnnotatedString.Range(spanStyle2, 3, 4),
AnnotatedString.Range(spanStyle1, 1, 2)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
// Despite that spanStyle3 is applied first, the spanStyles are applied in the index order.
inOrder(block) {
verify(block).invoke(spanStyle1, 1, 2)
verify(block).invoke(spanStyle2, 3, 4)
verify(block).invoke(spanStyle3, 7, 8)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_intersected_appliedInIndexOrder() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(100))
val spanStyle2 = SpanStyle(fontWeight = FontWeight(200))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 5, 9),
AnnotatedString.Range(spanStyle2, 3, 6)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle2, 3, 5)
// SpanStyles are applied in index order, but since spanStyle2 is applied later, it
// will overwrite spanStyle1's fontWeight.
verify(block).invoke(spanStyle2, 5, 6)
verify(block).invoke(spanStyle1, 6, 9)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_allEmptyRanges_notApplied() {
val contextSpanStyle = SpanStyle(fontWeight = FontWeight(400))
val spanStyle1 = SpanStyle(fontWeight = FontWeight(100))
val spanStyle2 = SpanStyle(fontWeight = FontWeight(200))
val spanStyle3 = SpanStyle(fontWeight = FontWeight(300))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 2, 2),
AnnotatedString.Range(spanStyle2, 4, 4),
AnnotatedString.Range(spanStyle3, 0, 0),
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = contextSpanStyle,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(contextSpanStyle, 0, 2)
verify(block).invoke(contextSpanStyle, 2, 4)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_emptySpanRange_shouldNotApply() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(100))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyle3 = SpanStyle(fontWeight = FontWeight(200))
val spanStyles = listOf(
AnnotatedString.Range(spanStyle3, 4, 10),
AnnotatedString.Range(spanStyle2, 1, 7),
AnnotatedString.Range(spanStyle1, 3, 3)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle2, 1, 3)
verify(block).invoke(spanStyle2, 3, 4)
verify(block).invoke(spanStyle3.merge(spanStyle2), 4, 7)
verify(block).invoke(spanStyle3, 7, 10)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_emptySpanRangeBeginning_shouldNotApply() {
val spanStyle1 = SpanStyle(fontWeight = FontWeight(100))
val spanStyle2 = SpanStyle(fontStyle = FontStyle.Italic)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 0, 0),
AnnotatedString.Range(spanStyle2, 0, 7)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = null,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(spanStyle2, 0, 7)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_withContextSpanStyle_inheritContext() {
val color = Color.Red
val fontStyle = FontStyle.Italic
val fontWeight = FontWeight(200)
val contextSpanStyle = SpanStyle(color = color, fontStyle = fontStyle)
val spanStyle = SpanStyle(fontWeight = fontWeight)
val spanStyles = listOf(
AnnotatedString.Range(spanStyle, 3, 6)
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = contextSpanStyle,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(
argThat {
this == SpanStyle(
color = color,
fontStyle = fontStyle,
fontWeight = fontWeight
)
},
eq(3),
eq(6)
)
verifyNoMoreInteractions()
}
}
@Test
fun flattenStylesAndApply_withContextSpanStyle_multipleSpanStyles_inheritContext() {
val contextColor = Color.Red
val contextFontWeight = FontWeight.Light
val contextFontStyle = FontStyle.Normal
val contextFontSize = 18.sp
val fontWeight = FontWeight.Bold
val fontStyle = FontStyle.Italic
val fontSize = 24.sp
val contextSpanStyle = SpanStyle(
color = contextColor,
fontWeight = contextFontWeight,
fontStyle = contextFontStyle,
fontSize = contextFontSize
)
val spanStyle1 = SpanStyle(fontWeight = fontWeight)
val spanStyle2 = SpanStyle(fontStyle = fontStyle)
val spanStyle3 = SpanStyle(fontSize = fontSize)
// There will be 5 ranges:
// [2, 4) contextColor, fontWeight, contextFontStyle, contextFontSize
// [4, 6) contextColor, fontWeight, fontStyle, contextFontSize
// [6, 8) contextColor, fontWeight, fontStyle, fontSize
// [8, 10) contextColor, contextFontWeight, fontStyle, fontSize
// [10, 12) contextColor, contextFontWeight, contextFontStyle, fontSize
val spanStyles = listOf(
AnnotatedString.Range(spanStyle1, 2, 8),
AnnotatedString.Range(spanStyle2, 4, 10),
AnnotatedString.Range(spanStyle3, 6, 12),
)
val block = mock<(SpanStyle, Int, Int) -> Unit>()
flattenFontStylesAndApply(
contextFontSpanStyle = contextSpanStyle,
spanStyles = spanStyles,
block = block
)
inOrder(block) {
verify(block).invoke(
argThat {
this == contextSpanStyle.copy(fontWeight = fontWeight)
},
eq(2),
eq(4)
)
verify(block).invoke(
argThat {
this == contextSpanStyle.copy(fontWeight = fontWeight, fontStyle = fontStyle)
},
eq(4),
eq(6)
)
verify(block).invoke(
argThat {
this == contextSpanStyle.copy(
fontWeight = fontWeight,
fontStyle = fontStyle,
fontSize = fontSize
)
},
eq(6),
eq(8)
)
verify(block).invoke(
argThat {
this == contextSpanStyle.copy(
fontStyle = fontStyle,
fontSize = fontSize
)
},
eq(8),
eq(10)
)
verify(block).invoke(
argThat {
this == contextSpanStyle.copy(fontSize = fontSize)
},
eq(10),
eq(12)
)
verifyNoMoreInteractions()
}
}
@OptIn(ExperimentalTextApi::class)
@Test
fun shaderBrush_shouldAdd_shaderBrushSpan_whenApplied() {
val text = "abcde abcde"
val brush = Brush.linearGradient(listOf(Color.Red, Color.Blue))
val spanStyle = SpanStyle(brush = brush)
val spannable = SpannableStringBuilder().apply { append(text) }
spannable.setSpanStyles(
contextTextStyle = TextStyle(),
spanStyles = listOf(AnnotatedString.Range(spanStyle, 0, text.length)),
density = Density(1f, 1f),
resolveTypeface = { _, _, _, _ -> Typeface.DEFAULT }
)
assertThat(spannable).hasSpan(ShaderBrushSpan::class, 0, text.length) {
it.shaderBrush == brush && it.alpha.isNaN()
}
}
@OptIn(ExperimentalTextApi::class)
@Test
fun shaderBrush_shouldAdd_shaderBrushSpan_whenApplied_withSpecifiedAlpha() {
val text = "abcde abcde"
val brush = Brush.linearGradient(listOf(Color.Red, Color.Blue))
val spanStyle = SpanStyle(brush = brush, alpha = 0.6f)
val spannable = SpannableStringBuilder().apply { append(text) }
spannable.setSpanStyles(
contextTextStyle = TextStyle(),
spanStyles = listOf(AnnotatedString.Range(spanStyle, 0, text.length)),
density = Density(1f, 1f),
resolveTypeface = { _, _, _, _ -> Typeface.DEFAULT }
)
assertThat(spannable).hasSpan(ShaderBrushSpan::class, 0, text.length) {
it.shaderBrush == brush && it.alpha == 0.6f
}
}
@OptIn(ExperimentalTextApi::class)
@Test
fun solidColorBrush_shouldAdd_ForegroundColorSpan_whenApplied() {
val text = "abcde abcde"
val spanStyle = SpanStyle(brush = SolidColor(Color.Red))
val spannable = SpannableStringBuilder().apply { append(text) }
spannable.setSpanStyles(
contextTextStyle = TextStyle(),
spanStyles = listOf(AnnotatedString.Range(spanStyle, 0, text.length)),
density = Density(1f, 1f),
resolveTypeface = { _, _, _, _ -> Typeface.DEFAULT }
)
}
@OptIn(ExperimentalTextApi::class)
@Test
fun whenColorAndShaderBrushSpansCollide_bothShouldApply() {
val text = "abcde abcde"
val brush = Brush.linearGradient(listOf(Color.Red, Color.Blue))
val brushStyle = SpanStyle(brush = brush)
val colorStyle = SpanStyle(color = Color.Red)
val spannable = SpannableStringBuilder().apply { append(text) }
spannable.setSpanStyles(
contextTextStyle = TextStyle(),
spanStyles = listOf(
AnnotatedString.Range(brushStyle, 0, text.length),
AnnotatedString.Range(colorStyle, 0, text.length)
),
density = Density(1f, 1f),
resolveTypeface = { _, _, _, _ -> Typeface.DEFAULT }
)
assertThat(spannable).hasSpan(ShaderBrushSpan::class, 0, text.length) {
it.shaderBrush == brush
}
assertThat(spannable).hasSpan(ForegroundColorSpan::class, 0, text.length)
}
@OptIn(ExperimentalTextApi::class)
@Test
fun whenColorAndSolidColorBrushSpansCollide_bothShouldApply() {
val text = "abcde abcde"
val brush = SolidColor(Color.Blue)
val brushStyle = SpanStyle(brush = brush)
val colorStyle = SpanStyle(color = Color.Red)
val spannable = SpannableStringBuilder().apply { append(text) }
spannable.setSpanStyles(
contextTextStyle = TextStyle(),
spanStyles = listOf(
AnnotatedString.Range(brushStyle, 0, text.length),
AnnotatedString.Range(colorStyle, 0, text.length)
),
density = Density(1f, 1f),
resolveTypeface = { _, _, _, _ -> Typeface.DEFAULT }
)
assertThat(spannable).hasSpan(ForegroundColorSpan::class, 0, text.length) {
it.foregroundColor == Color.Blue.toArgb()
}
assertThat(spannable).hasSpan(ForegroundColorSpan::class, 0, text.length) {
it.foregroundColor == Color.Red.toArgb()
}
}
} | apache-2.0 | 07971f8e476bd1ef1a2d1222ef66cc9d | 35.689655 | 99 | 0.599024 | 4.686032 | false | false | false | false |
ioc1778/incubator | incubator-events/src/main/java/com/riaektiv/lob/Order.kt | 2 | 443 | package com.riaektiv.lob
/**
* Coding With Passion Since 1991
* Created: 11/19/2017, 9:40 AM Eastern Time
* @author Sergey Chuykov
*/
class Order(
val id: Long,
val side: Int,
val qty: Int,
val iid: Long,
val price: Double
) {
var mts: Long = 0L
var nts: Long = 0L
override fun toString(): String {
return "Order(id=$id, side=$side, qty=$qty, iid=$iid, price=$price)"
}
} | bsd-3-clause | 40782490997730100473fb0efb428ecf | 18.304348 | 76 | 0.571106 | 3.330827 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/notifications/NoCargoProjectNotificationProvider.kt | 1 | 3523 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.notifications
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.LinkLabel
import com.intellij.openapi.vfs.VirtualFile
import org.rust.RsBundle
import org.rust.cargo.project.model.AttachCargoProjectAction
import org.rust.cargo.project.model.CargoProjectsService
import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.model.isCargoToml
import org.rust.lang.core.psi.isRustFile
import org.rust.openapiext.isDispatchThread
import org.rust.openapiext.isUnitTestMode
class NoCargoProjectNotificationProvider(project: Project) : RsNotificationProvider(project) {
init {
project.messageBus.connect().apply {
subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ ->
updateAllNotifications()
})
}
}
override val VirtualFile.disablingKey: String
get() = NOTIFICATION_STATUS_KEY + path
override fun createNotificationPanel(
file: VirtualFile,
editor: FileEditor,
project: Project
): RsEditorNotificationPanel? {
if (isUnitTestMode && !isDispatchThread) return null
if (!(file.isRustFile || file.isCargoToml) || isNotificationDisabled(file)) return null
@Suppress("UnstableApiUsage")
if (!project.isTrusted()) return null
val cargoProjects = project.cargoProjects
if (!cargoProjects.initialized) return null
if (!cargoProjects.hasAtLeastOneValidProject) {
return createNoCargoProjectsPanel(file)
}
if (file.isCargoToml) {
if (AttachCargoProjectAction.canBeAttached(project, file)) {
return createNoCargoProjectForFilePanel(file)
}
} else if (cargoProjects.findProjectForFile(file) == null) {
//TODO: more precise check here
return createNoCargoProjectForFilePanel(file)
}
return null
}
private fun createNoCargoProjectsPanel(file: VirtualFile): RsEditorNotificationPanel =
createAttachCargoProjectPanel(NO_CARGO_PROJECTS, file, RsBundle.message("notification.no.cargo.projects.found"))
private fun createNoCargoProjectForFilePanel(file: VirtualFile): RsEditorNotificationPanel =
createAttachCargoProjectPanel(FILE_NOT_IN_CARGO_PROJECT, file, RsBundle.message("notification.file.not.belong.to.cargo.project"))
@Suppress("UnstableApiUsage")
private fun createAttachCargoProjectPanel(debugId: String, file: VirtualFile, @LinkLabel message: String): RsEditorNotificationPanel =
RsEditorNotificationPanel(debugId).apply {
text = message
createActionLabel(RsBundle.message("notification.action.attach.text"), "Cargo.AttachCargoProject")
createActionLabel(RsBundle.message("notification.action.do.not.show.again.text")) {
disableNotification(file)
updateAllNotifications()
}
}
companion object {
private const val NOTIFICATION_STATUS_KEY = "org.rust.hideNoCargoProjectNotifications"
const val NO_CARGO_PROJECTS = "NoCargoProjects"
const val FILE_NOT_IN_CARGO_PROJECT = "FileNotInCargoProject"
}
}
| mit | 1ecb37ae0b781e5cd08014c1dc9459c9 | 39.494253 | 138 | 0.718422 | 4.839286 | false | false | false | false |
rwinch/spring-security | config/src/main/kotlin/org/springframework/security/config/annotation/web/AbstractRequestMatcherDsl.kt | 2 | 2948 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web
import org.springframework.http.HttpMethod
import org.springframework.security.authorization.AuthorizationManager
import org.springframework.security.web.access.intercept.RequestAuthorizationContext
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
/**
* A base class that provides authorization rules for [RequestMatcher]s and patterns.
*
* @author Eleftheria Stein
* @since 5.3
*/
@SecurityMarker
abstract class AbstractRequestMatcherDsl {
/**
* Matches any request.
*/
val anyRequest: RequestMatcher = AnyRequestMatcher.INSTANCE
protected data class MatcherAuthorizationRule(val matcher: RequestMatcher,
override val rule: String) : AuthorizationRule(rule)
protected data class MatcherAuthorizationManagerRule(val matcher: RequestMatcher,
override val rule: AuthorizationManager<RequestAuthorizationContext>) : AuthorizationManagerRule(rule)
protected data class PatternAuthorizationRule(val pattern: String,
val patternType: PatternType,
val servletPath: String? = null,
val httpMethod: HttpMethod? = null,
override val rule: String) : AuthorizationRule(rule)
protected data class PatternAuthorizationManagerRule(val pattern: String,
val patternType: PatternType,
val servletPath: String? = null,
val httpMethod: HttpMethod? = null,
override val rule: AuthorizationManager<RequestAuthorizationContext>) : AuthorizationManagerRule(rule)
protected abstract class AuthorizationRule(open val rule: String)
protected abstract class AuthorizationManagerRule(open val rule: AuthorizationManager<RequestAuthorizationContext>)
protected enum class PatternType {
ANT, MVC
}
}
| apache-2.0 | 0884122bf8533a0eee18196104cf17b6 | 45.793651 | 159 | 0.64654 | 5.64751 | false | false | false | false |
androidx/androidx | collection/collection/src/jvmMain/kotlin/androidx/collection/ArraySet.jvm.kt | 3 | 10287 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import androidx.collection.internal.EMPTY_INTS
import androidx.collection.internal.EMPTY_OBJECTS
/**
* ArraySet is a generic set data structure that is designed to be more memory efficient than a
* traditional [HashSet]. The design is very similar to
* [ArrayMap], with all of the caveats described there. This implementation is
* separate from ArrayMap, however, so the Object array contains only one item for each
* entry in the set (instead of a pair for a mapping).
*
* Note that this implementation is not intended to be appropriate for data structures
* that may contain large numbers of items. It is generally slower than a traditional
* HashSet, since lookups require a binary search and adds and removes require inserting
* and deleting entries in the array. For containers holding up to hundreds of items,
* the performance difference is not significant, less than 50%.
*
* Because this container is intended to better balance memory use, unlike most other
* standard Java containers it will shrink its array as items are removed from it. Currently
* you have no control over this shrinking -- if you set a capacity and then remove an
* item, it may reduce the capacity to better match the current size. In the future an
* explicit call to set the capacity should turn off this aggressive shrinking behavior.
*
* This structure is **NOT** thread-safe.
*
* @constructor Creates a new empty ArraySet. The default capacity of an array map is 0, and
* will grow once items are added to it.
*/
public actual class ArraySet<E>
// TODO(b/237405792): Default value for optional argument is required here to workaround Metalava's
// lack of support for expect / actual.
@Suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
// TODO(b/237405286): @JvmOverloads is redundant in this actual, but is necessary here to workaround
// Metalava's lack of support for expect / actual.
@JvmOverloads actual constructor(capacity: Int = 0) : MutableCollection<E>, MutableSet<E> {
internal actual var hashes: IntArray = EMPTY_INTS
internal actual var array: Array<Any?> = EMPTY_OBJECTS
internal actual var _size = 0
actual override val size: Int
get() = _size
/**
* Create a new ArraySet with the mappings from the given ArraySet.
*/
public actual constructor(set: ArraySet<out E>?) : this(capacity = 0) {
if (set != null) {
addAll(set)
}
}
/**
* Create a new ArraySet with the mappings from the given [Collection].
*/
public actual constructor(set: Collection<E>?) : this(capacity = 0) {
if (set != null) {
addAll(set)
}
}
/**
* Create a new ArraySet with items from the given array.
*/
public actual constructor(array: Array<out E>?) : this(capacity = 0) {
if (array != null) {
for (value in array) {
add(value)
}
}
}
init {
if (capacity > 0) {
allocArrays(capacity)
}
}
/**
* Make the array map empty. All storage is released.
*
* @throws ConcurrentModificationException if concurrent modifications detected.
*/
actual override fun clear() {
clearInternal()
}
/**
* Ensure the array map can hold at least [minimumCapacity]
* items.
*
* @throws ConcurrentModificationException if concurrent modifications detected.
*/
public actual fun ensureCapacity(minimumCapacity: Int) {
ensureCapacityInternal(minimumCapacity)
}
/**
* Check whether a value exists in the set.
*
* @param element The value to search for.
* @return Returns true if the value exists, else false.
*/
actual override operator fun contains(element: E): Boolean {
return containsInternal(element)
}
/**
* Returns the index of a value in the set.
*
* @param key The value to search for.
* @return Returns the index of the value if it exists, else a negative integer.
*/
public actual fun indexOf(key: Any?): Int {
return indexOfInternal(key)
}
/**
* Return the value at the given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1.
* @return Returns the value stored at the given index.
*/
public actual fun valueAt(index: Int): E {
return valueAtInternal(index)
}
/**
* Return `true` if the array map contains no items.
*/
actual override fun isEmpty(): Boolean {
return isEmptyInternal()
}
/**
* Adds the specified object to this set. The set is not modified if it
* already contains the object.
*
* @param element the object to add.
* @return `true` if this set is modified, `false` otherwise.
* @throws ConcurrentModificationException if concurrent modifications detected.
*/
actual override fun add(element: E): Boolean {
return addInternal(element)
}
/**
* Perform a [add] of all values in [array]
*
* @param array The array whose contents are to be retrieved.
* @throws ConcurrentModificationException if concurrent modifications detected.
*/
public actual fun addAll(array: ArraySet<out E>) {
addAllInternal(array)
}
/**
* Removes the specified object from this set.
*
* @param element the object to remove.
* @return `true` if this set was modified, `false` otherwise.
*/
actual override fun remove(element: E): Boolean {
return removeInternal(element)
}
/**
* Remove the key/value mapping at the given index.
*
* @param index The desired index, must be between 0 and [size]-1.
* @return Returns the value that was stored at this index.
* @throws ConcurrentModificationException if concurrent modifications detected.
*/
public actual fun removeAt(index: Int): E {
return removeAtInternal(index)
}
/**
* Perform a [remove] of all values in [array]
*
* @param array The array whose contents are to be removed.
*/
public actual fun removeAll(array: ArraySet<out E>): Boolean {
return removeAllInternal(array)
}
@Suppress("ArrayReturn")
public fun toArray(): Array<Any?> {
return array.copyOfRange(fromIndex = 0, toIndex = _size)
}
@Suppress("ArrayReturn")
public fun <T> toArray(array: Array<T>): Array<T> {
val result = ArraySetJvmUtil.resizeForToArray(array, _size)
@Suppress("UNCHECKED_CAST")
this.array.copyInto(result as Array<Any?>, 0, 0, _size)
return result
}
/**
* This implementation returns false if the object is not a set, or
* if the sets have different sizes. Otherwise, for each value in this
* set, it checks to make sure the value also exists in the other set.
* If any value doesn't exist, the method returns false; otherwise, it
* returns true.
*
* @see Any.equals
*/
actual override fun equals(other: Any?): Boolean {
return equalsInternal(other)
}
/**
* @see Any.hashCode
*/
actual override fun hashCode(): Int {
return hashCodeInternal()
}
/**
* This implementation composes a string by iterating over its values. If
* this set contains itself as a value, the string "(this Set)"
* will appear in its place.
*/
actual override fun toString(): String {
return toStringInternal()
}
/**
* Return a [MutableIterator] over all values in the set.
*
* **Note:** this is a less efficient way to access the array contents compared to
* looping from 0 until [size] and calling [valueAt].
*/
actual override fun iterator(): MutableIterator<E> = ElementIterator()
private inner class ElementIterator : IndexBasedArrayIterator<E>(_size) {
override fun elementAt(index: Int): E = valueAt(index)
override fun removeAt(index: Int) {
[email protected](index)
}
}
/**
* Determine if the array set contains all of the values in the given collection.
*
* @param elements The collection whose contents are to be checked against.
* @return Returns true if this array set contains a value for every entry
* in [elements] else returns false.
*/
actual override fun containsAll(elements: Collection<E>): Boolean {
return containsAllInternal(elements)
}
/**
* Perform an [add] of all values in [elements]
*
* @param elements The collection whose contents are to be retrieved.
*/
actual override fun addAll(elements: Collection<E>): Boolean {
return addAllInternal(elements)
}
/**
* Remove all values in the array set that exist in the given collection.
*
* @param elements The collection whose contents are to be used to remove values.
* @return Returns true if any values were removed from the array set, else false.
*/
actual override fun removeAll(elements: Collection<E>): Boolean {
return removeAllInternal(elements)
}
/**
* Remove all values in the array set that do **not** exist in the given collection.
*
* @param elements The collection whose contents are to be used to determine which
* values to keep.
* @return Returns true if any values were removed from the array set, else false.
*/
actual override fun retainAll(elements: Collection<E>): Boolean {
return retainAllInternal(elements)
}
}
| apache-2.0 | 27b9e9e35e225a45857b13674cb93239 | 33.062914 | 100 | 0.657821 | 4.507888 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCFirstJoin.kt | 1 | 2058 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.querydsl.QSeen
import com.demonwav.statcraft.transformTime
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
import java.sql.Connection
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
class SCFirstJoin(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("firstjoin", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.firstjoin")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return "${ChatColor.valueOf(plugin.config.colors.playerName)}$name" +
"${ChatColor.valueOf(plugin.config.colors.statValue)} has not been seen on this server."
val s = QSeen.seen
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val result = query.from(s).where(s.id.eq(id)).uniqueResult(s.firstJoinTime) ?: throw Exception()
val date = Date(result.toLong() * 1000L)
val format = SimpleDateFormat("EEE, dd MMM yyyy, hh:mm aa zzz")
format.timeZone = TimeZone.getTimeZone(plugin.timeZone)
var time = format.format(date)
val now = Date()
val difference = now.time - date.time
time = "$time (${transformTime((difference / 1000L).toInt()).split(",".toRegex())[0]} ago)"
return "${ChatColor.valueOf(plugin.config.colors.playerName)}$name" +
"${ChatColor.valueOf(plugin.config.colors.statTitle)} - First Join - " +
"${ChatColor.valueOf(plugin.config.colors.statValue)}$time"
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String? {
return null
}
}
| mit | 740897d434b08a874e1ab5699cd67f78 | 35.105263 | 130 | 0.695335 | 4.099602 | false | true | false | false |
googlecodelabs/wear-tiles | finished/src/main/java/com/example/wear/tiles/messaging/tile/MessagingTileRenderer.kt | 1 | 7072 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.wear.tiles.messaging.tile
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.wear.tiles.DeviceParametersBuilders
import androidx.wear.tiles.LayoutElementBuilders
import androidx.wear.tiles.ModifiersBuilders
import androidx.wear.tiles.ResourceBuilders
import androidx.wear.tiles.material.Button
import androidx.wear.tiles.material.ButtonColors
import androidx.wear.tiles.material.ChipColors
import androidx.wear.tiles.material.CompactChip
import androidx.wear.tiles.material.layouts.MultiButtonLayout
import androidx.wear.tiles.material.layouts.PrimaryLayout
import com.example.wear.tiles.R
import com.example.wear.tiles.messaging.Contact
import com.example.wear.tiles.messaging.MessagingRepo
import com.example.wear.tiles.tools.IconSizePreview
import com.example.wear.tiles.tools.WearDevicePreview
import com.example.wear.tiles.tools.emptyClickable
import com.google.android.horologist.compose.tools.LayoutElementPreview
import com.google.android.horologist.compose.tools.TileLayoutPreview
import com.google.android.horologist.tiles.images.drawableResToImageResource
import com.google.android.horologist.tiles.images.toImageResource
import com.google.android.horologist.tiles.render.SingleTileLayoutRenderer
class MessagingTileRenderer(context: Context) :
SingleTileLayoutRenderer<MessagingTileState, Map<Contact, Bitmap>>(context) {
override fun renderTile(
state: MessagingTileState,
deviceParameters: DeviceParametersBuilders.DeviceParameters
): LayoutElementBuilders.LayoutElement {
return messagingTileLayout(
context = context,
deviceParameters = deviceParameters,
state = state,
contactClickableFactory = { contact ->
launchActivityClickable(
clickableId = contact.id.toString(),
androidActivity = openConversation(contact)
)
},
searchButtonClickable = launchActivityClickable("search_button", openSearch()),
newButtonClickable = launchActivityClickable("new_button", openNewConversation())
)
}
override fun ResourceBuilders.Resources.Builder.produceRequestedResources(
resourceState: Map<Contact, Bitmap>,
deviceParameters: DeviceParametersBuilders.DeviceParameters,
resourceIds: MutableList<String>
) {
addIdToImageMapping(ID_IC_SEARCH, drawableResToImageResource(R.drawable.ic_search_24))
resourceState.forEach { (contact, bitmap) ->
addIdToImageMapping(
/* id = */ contact.imageResourceId(),
/* image = */ bitmap.toImageResource()
)
}
}
companion object {
internal const val ID_IC_SEARCH = "ic_search"
}
}
/**
* Layout definition for the Messaging Tile.
*
* By separating the layout completely, we can pass fake data for the [MessageTilePreview] so it can
* be rendered in Android Studio (use the "Split" or "Design" editor modes).
*/
private fun messagingTileLayout(
context: Context,
deviceParameters: DeviceParametersBuilders.DeviceParameters,
state: MessagingTileState,
contactClickableFactory: (Contact) -> ModifiersBuilders.Clickable,
searchButtonClickable: ModifiersBuilders.Clickable,
newButtonClickable: ModifiersBuilders.Clickable
) = PrimaryLayout.Builder(deviceParameters)
.setContent(
MultiButtonLayout.Builder()
.apply {
// In a PrimaryLayout with a compact chip at the bottom, we can fit 5 buttons.
// We're only taking the first 4 contacts so that we can fit a Search button too.
state.contacts.take(4).forEach { contact ->
addButtonContent(
contactLayout(
context = context,
contact = contact,
clickable = contactClickableFactory(contact)
)
)
}
}
.addButtonContent(searchLayout(context, searchButtonClickable))
.build()
).setPrimaryChipContent(
CompactChip.Builder(
/* context = */ context,
/* text = */ context.getString(R.string.tile_messaging_create_new),
/* clickable = */ newButtonClickable,
/* deviceParameters = */ deviceParameters
)
.setChipColors(ChipColors.primaryChipColors(MessagingTileTheme.colors))
.build()
)
.build()
private fun contactLayout(
context: Context,
contact: Contact,
clickable: ModifiersBuilders.Clickable,
) = Button.Builder(context, clickable)
.setContentDescription(contact.name)
.apply {
if (contact.avatarUrl != null) {
setImageContent(contact.imageResourceId())
} else {
setTextContent(contact.initials)
setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
}
}
.build()
private fun searchLayout(
context: Context,
clickable: ModifiersBuilders.Clickable,
) = Button.Builder(context, clickable)
.setContentDescription(context.getString(R.string.tile_messaging_search))
.setIconContent(MessagingTileRenderer.ID_IC_SEARCH)
.setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
.build()
@WearDevicePreview
@Composable
fun MessagingTileRendererPreview() {
val state = MessagingTileState(MessagingRepo.knownContacts)
val context = LocalContext.current
TileLayoutPreview(
state = state,
resourceState = mapOf(
state.contacts[1] to (context.getDrawable(R.drawable.ali) as BitmapDrawable).bitmap,
state.contacts[2] to (context.getDrawable(R.drawable.taylor) as BitmapDrawable).bitmap,
),
renderer = MessagingTileRenderer(context)
)
}
@IconSizePreview
@Composable
private fun SearchButtonPreview() {
LayoutElementPreview(
searchLayout(
context = LocalContext.current,
clickable = emptyClickable
)
) {
addIdToImageMapping(
MessagingTileRenderer.ID_IC_SEARCH,
drawableResToImageResource(R.drawable.ic_search_24)
)
}
}
| apache-2.0 | d9004a13b3db0b0e7a5be091faf5d215 | 37.227027 | 100 | 0.694853 | 4.917942 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/conference/ConferenceFragment.kt | 2 | 8663 | package me.proxer.app.chat.prv.conference
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.core.os.bundleOf
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.transition.TransitionManager
import com.jakewharton.rxbinding3.appcompat.queryTextChangeEvents
import com.jakewharton.rxbinding3.view.actionViewEvents
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotterknife.bindView
import me.proxer.app.GlideApp
import me.proxer.app.R
import me.proxer.app.base.BaseContentFragment
import me.proxer.app.chat.prv.ConferenceWithMessage
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.chat.prv.create.CreateConferenceActivity
import me.proxer.app.chat.prv.sync.MessengerNotifications
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.ErrorUtils.ErrorAction
import me.proxer.app.util.ErrorUtils.ErrorAction.Companion.ACTION_MESSAGE_HIDE
import me.proxer.app.util.extension.doAfterAnimations
import me.proxer.app.util.extension.enableFastScroll
import me.proxer.app.util.extension.isAtTop
import me.proxer.app.util.extension.scrollToTop
import me.proxer.app.util.extension.unsafeLazy
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class ConferenceFragment : BaseContentFragment<List<ConferenceWithMessage>>(R.layout.fragment_conferences) {
companion object {
private const val SEARCH_QUERY_ARGUMENT = "search_query"
private const val INITIAL_MESSAGE_ARGUMENT = "initial_message"
fun newInstance(initialMessage: String? = null) = ConferenceFragment().apply {
arguments = bundleOf(INITIAL_MESSAGE_ARGUMENT to initialMessage)
}
}
override val viewModel by viewModel<ConferenceViewModel> { parametersOf(searchQuery ?: "") }
private val layoutManager by unsafeLazy {
StaggeredGridLayoutManager(
DeviceUtils.calculateSpanAmount(requireActivity()),
StaggeredGridLayoutManager.VERTICAL
)
}
private var adapter by Delegates.notNull<ConferenceAdapter>()
override val contentContainer: ViewGroup
get() = recyclerView
private val toolbar by unsafeLazy { requireActivity().findViewById<Toolbar>(R.id.toolbar) }
private val recyclerView: RecyclerView by bindView(R.id.recyclerView)
private val adapterDataObserver = object : RecyclerView.AdapterDataObserver() {
override fun onChanged() = scrollToTopIfRequested()
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) = scrollToTopIfRequested()
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) = scrollToTopIfRequested()
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) = scrollToTopIfRequested()
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
if (shouldScrollToTop) {
scrollToTopIfRequested()
} else if (recyclerView.isAtTop() && toPosition == 0) {
recyclerView.smoothScrollToPosition(0)
}
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (shouldScrollToTop) {
scrollToTopIfRequested()
} else if (recyclerView.isAtTop() && positionStart == 0) {
recyclerView.smoothScrollToPosition(0)
}
}
private fun scrollToTopIfRequested() {
if (shouldScrollToTop) {
recyclerView.doAfterAnimations {
recyclerView.scrollToTop()
}
shouldScrollToTop = false
}
}
}
private val initialMessage: String?
get() = requireArguments().getString(INITIAL_MESSAGE_ARGUMENT, null)
private var searchQuery: String?
get() = requireArguments().getString(SEARCH_QUERY_ARGUMENT, null)
set(value) {
requireArguments().putString(SEARCH_QUERY_ARGUMENT, value)
shouldScrollToTop = true
viewModel.searchQuery = value ?: ""
}
private var shouldScrollToTop = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = ConferenceAdapter(storageHelper)
adapter.clickSubject
.autoDisposable(this.scope())
.subscribe { (conference) ->
PrvMessengerActivity.navigateTo(requireActivity(), conference, initialMessage)
}
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter.glide = GlideApp.with(this)
adapter.registerAdapterDataObserver(adapterDataObserver)
recyclerView.setHasFixedSize(true)
recyclerView.enableFastScroll()
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
}
override fun onResume() {
super.onResume()
MessengerNotifications.cancel(requireContext())
bus.register(ConferenceFragmentPingEvent::class.java)
.autoDisposable(this.scope())
.subscribe()
}
override fun onDestroyView() {
adapter.unregisterAdapterDataObserver(adapterDataObserver)
recyclerView.layoutManager = null
recyclerView.adapter = null
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
if (initialMessage == null) {
IconicsMenuInflaterUtil.inflate(inflater, requireContext(), R.menu.fragment_conferences, menu, true)
} else {
IconicsMenuInflaterUtil.inflate(inflater, requireContext(), R.menu.fragment_share_receiver, menu, true)
}
menu.findItem(R.id.search).let { searchItem ->
val searchView = searchItem.actionView as SearchView
searchItem.actionViewEvents()
.autoDisposable(viewLifecycleOwner.scope(Lifecycle.Event.ON_DESTROY))
.subscribe {
if (it.menuItem.isActionViewExpanded) {
searchQuery = null
}
TransitionManager.endTransitions(toolbar)
TransitionManager.beginDelayedTransition(toolbar)
}
searchView.queryTextChangeEvents()
.skipInitialValue()
.debounce(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(viewLifecycleOwner.scope(Lifecycle.Event.ON_DESTROY))
.subscribe {
searchQuery = it.queryText.toString().trim()
if (it.isSubmitted) {
searchView.clearFocus()
}
}
if (searchQuery.isNullOrBlank().not()) {
searchItem.expandActionView()
searchView.setQuery(searchQuery, false)
searchView.clearFocus()
}
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.create_chat -> CreateConferenceActivity.navigateTo(requireActivity(), false)
R.id.new_group -> CreateConferenceActivity.navigateTo(requireActivity(), true)
}
return super.onOptionsItemSelected(item)
}
override fun showData(data: List<ConferenceWithMessage>) {
super.showData(data)
adapter.swapDataAndNotifyWithDiffing(data)
if (adapter.isEmpty()) {
when (searchQuery.isNullOrBlank()) {
true -> showError(ErrorAction(R.string.error_no_data_conferences, ACTION_MESSAGE_HIDE))
false -> showError(ErrorAction(R.string.error_no_data_search, ACTION_MESSAGE_HIDE))
}
}
}
override fun hideData() {
adapter.swapDataAndNotifyWithDiffing(emptyList())
super.hideData()
}
}
| gpl-3.0 | 456f6ecc8f8fec0bcce846fea7972c70 | 35.39916 | 117 | 0.678518 | 5.228123 | false | false | false | false |
ThomasVadeSmileLee/cyls | src/main/kotlin/org/smileLee/cyls/cyls/CylsFriend.kt | 1 | 2401 | package org.smileLee.cyls.cyls
import com.alibaba.fastjson.annotation.JSONType
import com.scienjus.smartqq.model.Friend
import org.smileLee.cyls.qqbot.MatchingVerifier
import org.smileLee.cyls.qqbot.QQBotFriend
import org.smileLee.cyls.qqbot.TreeNode
import org.smileLee.cyls.qqbot.anyOf
import org.smileLee.cyls.qqbot.contain
import org.smileLee.cyls.qqbot.createTree
import org.smileLee.cyls.qqbot.createVerifier
import org.smileLee.cyls.qqbot.equal
@JSONType(ignores = arrayOf(
"friend",
"admin",
"owner",
"ignored"
))
class CylsFriend(
override var markName: String = "",
var adminLevel: AdminLevel = AdminLevel.NORMAL,
var ignoreLevel: IgnoreLevel = IgnoreLevel.RECOGNIZED,
var isRepeated: Boolean = false,
var repeatFrequency: Double = 0.0,
var isMoha: Boolean = false,
override var friend: Friend? = null,
override var status: ChattingStatus = CylsFriend.ChattingStatus.COMMON
) : QQBotFriend<Cyls>() {
enum class AdminLevel {
NORMAL,
ADMIN,
OWNER
}
enum class IgnoreLevel {
RECOGNIZED,
IGNORED
}
val isAdmin get() = adminLevel == AdminLevel.ADMIN || adminLevel == AdminLevel.OWNER
val isOwner get() = adminLevel == AdminLevel.OWNER
val isIgnored get() = ignoreLevel == IgnoreLevel.IGNORED
fun authorityGreaterThan(other: CylsFriend) = isOwner || (isAdmin && !other.isAdmin) || this == other
override fun equals(other: Any?) = other is CylsFriend && markName == other.markName
override fun hashCode() = markName.hashCode()
companion object {
val commonCommand = createTree<Cyls> {
}
val commonVerifier = createVerifier<Cyls> {
anyOf({
equal("早")
contain("早安")
}) { _, cyls ->
PredefinedReplyInfo.GoodMorning()
.replyTo(cyls.currentFriendReplier)
}
contain("晚安", { _, cyls ->
PredefinedReplyInfo.GoodNight()
.replyTo(cyls.currentFriendReplier)
})
}
}
enum class ChattingStatus(
override val commandTree: TreeNode<Cyls>,
override val replyVerifier: MatchingVerifier<Cyls>
) : QQBotChattingStatus<Cyls> {
COMMON(commonCommand, commonVerifier);
}
} | mit | 26baaae1f4debfaa359ecc4846035cf8 | 31.324324 | 105 | 0.633208 | 4.052542 | false | false | false | false |
JavaEden/Orchid | OrchidCore/src/main/kotlin/com/eden/orchid/utilities/StreamUtils.kt | 2 | 2649 | package com.eden.orchid.utilities
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.tasks.TaskService
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
class InputStreamCollector(private val inputStream: InputStream) : Runnable {
var output = StringBuffer()
override fun run() {
output = StringBuffer()
inputStream
.bufferedReader()
.lineSequence()
.forEach { output.appendln(it) }
}
override fun toString(): String {
return output.toString()
}
}
class InputStreamPrinter
@JvmOverloads
constructor(
private val inputStream: InputStream,
val tag: String? = null,
val transform: ((String) -> String)? = null
) : Runnable {
override fun run() {
inputStream
.bufferedReader()
.lineSequence()
.forEach {
val actualMessage = transform?.invoke(it) ?: it
if (tag != null) {
Clog.tag(tag).log(actualMessage)
} else {
Clog.noTag().log(actualMessage)
}
}
}
}
class InputStreamIgnorer(private val inputStream: InputStream) : Runnable {
override fun run() {
inputStream
.bufferedReader()
.lineSequence()
.forEach { /* do nothing with it */ }
}
}
fun convertOutputStream(context: OrchidContext, writer: (OutputStream) -> Unit): InputStream {
if (context.taskType == TaskService.TaskType.SERVE) {
// in serve mode, we get errors trying to convert the streams using pipes, because the server stream is closed
// before the thread can finish. So we need to do it all in memory.
//
// TODO: look into a coroutine-based small-buffered solution to write/read bytes on the same thread, and avoid
// having to load it all into memory at once, and avoid having to spawn separate threads for this, too
val os = ByteArrayOutputStream()
writer(os)
return ByteArrayInputStream(os.toByteArray())
} else {
// when not in serve mode, we can safely use pipes for copying streams, to conserve
val pipedInputStreamPrinter = PipedInputStream()
val pipedOutputStream = PipedOutputStream(pipedInputStreamPrinter)
Thread {
pipedOutputStream.use(writer)
}.start()
return pipedInputStreamPrinter
}
}
| lgpl-3.0 | 96fa76d68df291205935f4c65192580b | 30.915663 | 118 | 0.641374 | 4.781588 | false | false | false | false |
ligee/kotlin-jupyter | src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/testUtil.kt | 1 | 8197 | package org.jetbrains.kotlinx.jupyter.test
import io.kotest.assertions.fail
import jupyter.kotlin.DependsOn
import jupyter.kotlin.JavaRuntime
import org.jetbrains.kotlinx.jupyter.CodeCellImpl
import org.jetbrains.kotlinx.jupyter.ReplRuntimeProperties
import org.jetbrains.kotlinx.jupyter.api.CodeCell
import org.jetbrains.kotlinx.jupyter.api.DisplayContainer
import org.jetbrains.kotlinx.jupyter.api.DisplayResultWithCell
import org.jetbrains.kotlinx.jupyter.api.JREInfoProvider
import org.jetbrains.kotlinx.jupyter.api.JupyterClientType
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.RenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.ResultsAccessor
import org.jetbrains.kotlinx.jupyter.api.VariableState
import org.jetbrains.kotlinx.jupyter.api.VariableStateImpl
import org.jetbrains.kotlinx.jupyter.api.libraries.ExecutionHost
import org.jetbrains.kotlinx.jupyter.api.libraries.JupyterIntegration
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryReference
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import org.jetbrains.kotlinx.jupyter.defaultRepositories
import org.jetbrains.kotlinx.jupyter.defaultRuntimeProperties
import org.jetbrains.kotlinx.jupyter.libraries.AbstractLibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.libraries.ChainedLibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES
import org.jetbrains.kotlinx.jupyter.libraries.LibraryDescriptor
import org.jetbrains.kotlinx.jupyter.libraries.LibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryDescriptors
import org.jetbrains.kotlinx.jupyter.log
import org.jetbrains.kotlinx.jupyter.messaging.DisplayHandler
import org.jetbrains.kotlinx.jupyter.repl.CompletionResult
import java.io.File
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
import kotlin.test.assertEquals
val testDataDir = File("src/test/testData")
const val standardResolverBranch = "master"
val testRepositories = defaultRepositories
val standardResolverRuntimeProperties = object : ReplRuntimeProperties by defaultRuntimeProperties {
override val currentBranch: String
get() = standardResolverBranch
}
val classpath = scriptCompilationClasspathFromContext(
"lib",
"api",
"shared-compiler",
"kotlin-stdlib",
"kotlin-reflect",
"kotlin-script-runtime",
classLoader = DependsOn::class.java.classLoader
)
val testLibraryResolver: LibraryResolver
get() = getResolverFromNamesMap(parseLibraryDescriptors(readLibraries()))
fun assertUnit(value: Any?) = assertEquals(Unit, value)
fun assertStartsWith(expectedPrefix: String, actual: String) {
if (actual.startsWith(expectedPrefix)) return
val actualStart = actual.substring(0, minOf(expectedPrefix.length, actual.length))
throw AssertionError("Expected a string to start with '$expectedPrefix', but it starts with '$actualStart")
}
fun Collection<Pair<String, String>>.toLibraries(): LibraryResolver {
val libJsons = associate { it.first to it.second }
return getResolverFromNamesMap(parseLibraryDescriptors(libJsons))
}
@JvmName("toLibrariesStringLibraryDefinition")
fun Collection<Pair<String, LibraryDefinition>>.toLibraries() = getResolverFromNamesMap(definitions = toMap())
fun getResolverFromNamesMap(
descriptors: Map<String, LibraryDescriptor>? = null,
definitions: Map<String, LibraryDefinition>? = null,
): LibraryResolver {
return InMemoryLibraryResolver(
null,
descriptors?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
definitions?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
)
}
fun readLibraries(basePath: String? = null): Map<String, String> {
return KERNEL_LIBRARIES.homeLibrariesDir(basePath?.let(::File))
.listFiles()?.filter(KERNEL_LIBRARIES::isLibraryDescriptor)
?.map {
log.info("Loading '${it.nameWithoutExtension}' descriptor from '${it.canonicalPath}'")
it.nameWithoutExtension to it.readText()
}
.orEmpty()
.toMap()
}
fun CompletionResult.getOrFail(): CompletionResult.Success = when (this) {
is CompletionResult.Success -> this
else -> fail("Result should be success")
}
fun Map<String, VariableState>.mapToStringValues(): Map<String, String?> {
return mapValues { it.value.stringValue }
}
fun Map<String, VariableState>.getStringValue(variableName: String): String? {
return get(variableName)?.stringValue
}
fun Map<String, VariableState>.getValue(variableName: String): Any? {
return get(variableName)?.value?.getOrNull()
}
class InMemoryLibraryResolver(
parent: LibraryResolver?,
initialDescriptorsCache: Map<LibraryReference, LibraryDescriptor>? = null,
initialDefinitionsCache: Map<LibraryReference, LibraryDefinition>? = null,
) : ChainedLibraryResolver(parent) {
private val definitionsCache = hashMapOf<LibraryReference, LibraryDefinition>()
private val descriptorsCache = hashMapOf<LibraryReference, LibraryDescriptor>()
init {
initialDescriptorsCache?.forEach { (key, value) ->
descriptorsCache[key] = value
}
initialDefinitionsCache?.forEach { (key, value) ->
definitionsCache[key] = value
}
}
override fun shouldResolve(reference: LibraryReference): Boolean {
return reference.shouldBeCachedInMemory
}
override fun tryResolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
return definitionsCache[reference] ?: descriptorsCache[reference]?.convertToDefinition(arguments)
}
override fun save(reference: LibraryReference, definition: LibraryDefinition) {
definitionsCache[reference] = definition
}
}
class TestDisplayHandler(val list: MutableList<Any> = mutableListOf()) : DisplayHandler {
override fun handleDisplay(value: Any, host: ExecutionHost) {
list.add(value)
}
override fun handleUpdate(value: Any, host: ExecutionHost, id: String?) {
// TODO: Implement correct updating
}
}
object NotebookMock : Notebook {
private val cells = hashMapOf<Int, CodeCellImpl>()
override val cellsList: Collection<CodeCell>
get() = emptyList()
override val variablesState = mutableMapOf<String, VariableStateImpl>()
override val cellVariables = mapOf<Int, Set<String>>()
override val resultsAccessor = ResultsAccessor { getResult(it) }
override fun getCell(id: Int): CodeCellImpl {
return cells[id] ?: throw ArrayIndexOutOfBoundsException(
"There is no cell with number '$id'"
)
}
override fun getResult(id: Int): Any? {
return getCell(id).result
}
private val displays: DisplayContainer
get() = error("Not supposed to be called")
override fun getAllDisplays(): List<DisplayResultWithCell> {
return displays.getAll()
}
override fun getDisplaysById(id: String?): List<DisplayResultWithCell> {
return displays.getById(id)
}
override fun history(before: Int): CodeCell? {
error("Not supposed to be called")
}
override val kernelVersion: KotlinKernelVersion
get() = defaultRuntimeProperties.version!!
override val jreInfo: JREInfoProvider
get() = JavaRuntime
override val renderersProcessor: RenderersProcessor
get() = error("Not supposed to be called")
override val libraryRequests: Collection<LibraryResolutionRequest>
get() = error("Not supposed to be called")
override val jupyterClientType: JupyterClientType
get() = JupyterClientType.UNKNOWN
}
fun library(builder: JupyterIntegration.Builder.() -> Unit): LibraryDefinition {
val o = object : JupyterIntegration() {
override fun Builder.onLoaded() {
builder()
}
}
return o.getDefinitions(NotebookMock).single()
}
| apache-2.0 | dffe9ab125721001b11c48ed406fec3d | 37.125581 | 111 | 0.7543 | 4.516253 | false | false | false | false |
Benestar/focus-android | app/src/main/java/org/mozilla/focus/fragment/UrlInputFragment.kt | 1 | 18947 | /* -*- 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.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import kotlinx.android.synthetic.main.fragment_urlinput.*
import org.mozilla.focus.R
import org.mozilla.focus.activity.InfoActivity
import org.mozilla.focus.autocomplete.UrlAutoCompleteFilter
import org.mozilla.focus.locale.LocaleAwareAppCompatActivity
import org.mozilla.focus.locale.LocaleAwareFragment
import org.mozilla.focus.menu.home.HomeMenu
import org.mozilla.focus.session.Session
import org.mozilla.focus.session.SessionManager
import org.mozilla.focus.session.Source
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.*
import org.mozilla.focus.whatsnew.WhatsNew
import org.mozilla.focus.widget.InlineAutocompleteEditText
/**
* Fragment for displaying he URL input controls.
*/
class UrlInputFragment : LocaleAwareFragment(), View.OnClickListener, InlineAutocompleteEditText.OnCommitListener, InlineAutocompleteEditText.OnFilterListener {
companion object {
@JvmField
val FRAGMENT_TAG = "url_input"
private val ARGUMENT_ANIMATION = "animation"
private val ARGUMENT_X = "x"
private val ARGUMENT_Y = "y"
private val ARGUMENT_WIDTH = "width"
private val ARGUMENT_HEIGHT = "height"
private val ARGUMENT_SESSION_UUID = "sesssion_uuid"
private val ANIMATION_BROWSER_SCREEN = "browser_screen"
private val PLACEHOLDER = "5981086f-9d45-4f64-be99-7d2ffa03befb";
private val ANIMATION_DURATION = 200
@JvmStatic
fun createWithoutSession(): UrlInputFragment {
val arguments = Bundle()
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
@JvmStatic
fun createWithSession(session: Session, urlView: View): UrlInputFragment {
val arguments = Bundle()
arguments.putString(ARGUMENT_SESSION_UUID, session.uuid)
arguments.putString(ARGUMENT_ANIMATION, ANIMATION_BROWSER_SCREEN)
val screenLocation = IntArray(2)
urlView.getLocationOnScreen(screenLocation)
arguments.putInt(ARGUMENT_X, screenLocation[0])
arguments.putInt(ARGUMENT_Y, screenLocation[1])
arguments.putInt(ARGUMENT_WIDTH, urlView.width)
arguments.putInt(ARGUMENT_HEIGHT, urlView.height)
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
/**
* Create a new UrlInputFragment with a gradient background (and the Focus logo). This configuration
* is usually shown if there's no content to be shown below (e.g. the current website).
*/
@JvmStatic
fun createWithBackground(): UrlInputFragment {
val arguments = Bundle()
val fragment = UrlInputFragment()
fragment.arguments = arguments
return fragment
}
}
private val urlAutoCompleteFilter: UrlAutoCompleteFilter = UrlAutoCompleteFilter()
private var displayedPopupMenu: HomeMenu? = null
@Volatile private var isAnimating: Boolean = false
private var session: Session? = null
private val isOverlay: Boolean
get() = session != null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Get session from session manager if there's a session UUID in the fragment's arguments
arguments?.getString(ARGUMENT_SESSION_UUID)?.let {
session = SessionManager.getInstance().getSessionByUUID(it)
}
context?.let {
urlAutoCompleteFilter.initialize(it.applicationContext)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_urlinput, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
listOf(dismissView, clearView, searchView).forEach { it.setOnClickListener(this) }
urlView.setOnFilterListener(this)
urlView.imeOptions = urlView.imeOptions or ViewUtils.IME_FLAG_NO_PERSONALIZED_LEARNING
urlInputContainerView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
urlInputContainerView.viewTreeObserver.removeOnPreDrawListener(this)
animateFirstDraw()
return true
}
})
if (isOverlay) {
keyboardLinearLayout.visibility = View.GONE
} else {
backgroundView.setBackgroundResource(R.drawable.background_gradient)
dismissView.visibility = View.GONE
toolbarBackgroundView.visibility = View.GONE
menuView.visibility = View.VISIBLE
menuView.setOnClickListener(this)
}
urlView.setOnCommitListener(this)
session?.let {
urlView.setText(if (it.isSearch) it.searchTerms else it.url.value)
clearView.visibility = View.VISIBLE
searchViewContainer.visibility = View.GONE
}
}
override fun applyLocale() {
if (isOverlay) {
activity?.supportFragmentManager
?.beginTransaction()
?.replace(R.id.container, UrlInputFragment.createWithSession(session!!, urlView), UrlInputFragment.FRAGMENT_TAG)
?.commit()
} else {
activity?.supportFragmentManager
?.beginTransaction()
?.replace(R.id.container, UrlInputFragment.createWithBackground(), UrlInputFragment.FRAGMENT_TAG)
?.commit()
}
}
fun onBackPressed(): Boolean {
if (isOverlay) {
animateAndDismiss()
return true
}
return false
}
override fun onStart() {
super.onStart()
if (!Settings.getInstance(context).shouldShowFirstrun()) {
// Only show keyboard if we are not displaying the first run tour on top.
showKeyboard()
}
}
override fun onStop() {
super.onStop()
// Reset the keyboard layout to avoid a jarring animation when the view is started again. (#1135)
keyboardLinearLayout.reset()
}
fun showKeyboard() {
ViewUtils.showKeyboard(urlView)
}
override fun onClick(view: View) {
when (view.id) {
R.id.clearView -> clear()
R.id.searchView -> onSearch()
R.id.dismissView -> if (isOverlay) {
animateAndDismiss()
} else {
clear()
}
R.id.menuView -> context?.let {
val menu = HomeMenu(it, this)
menu.show(view)
displayedPopupMenu = menu
}
R.id.whats_new -> context?.let {
TelemetryWrapper.openWhatsNewEvent(WhatsNew.shouldHighlightWhatsNew(it))
WhatsNew.userViewedWhatsNew(it)
SessionManager.getInstance()
.createSession(Source.MENU, SupportUtils.getWhatsNewUrl(context))
}
R.id.settings -> (activity as LocaleAwareAppCompatActivity).openPreferences()
R.id.help -> {
val helpIntent = InfoActivity.getHelpIntent(activity)
startActivity(helpIntent)
}
else -> throw IllegalStateException("Unhandled view in onClick()")
}
}
private fun clear() {
urlView.setText("")
urlView.requestFocus()
}
override fun onDetach() {
super.onDetach()
// On detach, the PopupMenu is no longer relevant to other content (e.g. BrowserFragment) so dismiss it.
// Note: if we don't dismiss the PopupMenu, its onMenuItemClick method references the old Fragment, which now
// has a null Context and will cause crashes.
displayedPopupMenu?.dismiss()
}
private fun animateFirstDraw() {
if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) {
playVisibilityAnimation(false)
}
}
private fun animateAndDismiss() {
ThreadUtils.assertOnUiThread()
if (isAnimating) {
// We are already animating some state change. Ignore all other requests.
return
}
// Don't allow any more clicks: dismissView is still visible until the animation ends,
// but we don't want to restart animations and/or trigger hiding again (which could potentially
// cause crashes since we don't know what state we're in). Ignoring further clicks is the simplest
// solution, since dismissView is about to disappear anyway.
dismissView.isClickable = false
if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) {
playVisibilityAnimation(true)
} else {
dismiss()
}
}
/**
* This animation is quite complex. The 'reverse' flag controls whether we want to show the UI
* (false) or whether we are going to hide it (true). Additionally the animation is slightly
* different depending on whether this fragment is shown as an overlay on top of other fragments
* or if it draws its own background.
*/
private fun playVisibilityAnimation(reverse: Boolean) {
if (isAnimating) {
// We are already animating, let's ignore another request.
return
}
isAnimating = true
val xyOffset = (if (isOverlay)
(urlInputContainerView.layoutParams as FrameLayout.LayoutParams).bottomMargin
else
0).toFloat()
val width = urlInputBackgroundView.width.toFloat()
val height = urlInputBackgroundView.height.toFloat()
val widthScale = if (isOverlay)
(width + 2 * xyOffset) / width
else
1f
val heightScale = if (isOverlay)
(height + 2 * xyOffset) / height
else
1f
if (!reverse) {
urlInputBackgroundView.pivotX = 0f
urlInputBackgroundView.pivotY = 0f
urlInputBackgroundView.scaleX = widthScale
urlInputBackgroundView.scaleY = heightScale
urlInputBackgroundView.translationX = -xyOffset
urlInputBackgroundView.translationY = -xyOffset
clearView.alpha = 0f
}
// Let the URL input use the full width/height and then shrink to the actual size
urlInputBackgroundView.animate()
.setDuration(ANIMATION_DURATION.toLong())
.scaleX(if (reverse) widthScale else 1f)
.scaleY(if (reverse) heightScale else 1f)
.alpha((if (reverse && isOverlay) 0 else 1).toFloat())
.translationX(if (reverse) -xyOffset else 0f)
.translationY(if (reverse) -xyOffset else 0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
if (reverse) {
clearView.alpha = 0f
}
}
override fun onAnimationEnd(animation: Animator) {
if (reverse) {
if (isOverlay) {
dismiss()
}
} else {
clearView?.alpha = 1f
}
isAnimating = false
}
})
// We only need to animate the toolbar if we are an overlay.
if (isOverlay) {
val screenLocation = IntArray(2)
urlView.getLocationOnScreen(screenLocation)
val leftDelta = arguments!!.getInt(ARGUMENT_X) - screenLocation[0] - urlView.paddingLeft
if (!reverse) {
urlView.pivotX = 0f
urlView.pivotY = 0f
urlView.translationX = leftDelta.toFloat()
}
// The URL moves from the right (at least if the lock is visible) to it's actual position
urlView.animate()
.setDuration(ANIMATION_DURATION.toLong())
.translationX((if (reverse) leftDelta else 0).toFloat())
}
if (!reverse) {
toolbarBackgroundView.alpha = 0f
clearView.alpha = 0f
}
// The darker background appears with an alpha animation
toolbarBackgroundView.animate()
.setDuration(ANIMATION_DURATION.toLong())
.alpha((if (reverse) 0 else 1).toFloat())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
toolbarBackgroundView.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animator) {
if (reverse) {
toolbarBackgroundView.visibility = View.GONE
if (!isOverlay) {
dismissView.visibility = View.GONE
menuView.visibility = View.VISIBLE
}
}
}
})
}
private fun dismiss() {
// This method is called from animation callbacks. In the short time frame between the animation
// starting and ending the activity can be paused. In this case this code can throw an
// IllegalStateException because we already saved the state (of the activity / fragment) before
// this transaction is committed. To avoid this we commit while allowing a state loss here.
// We do not save any state in this fragment (It's getting destroyed) so this should not be a problem.
activity?.supportFragmentManager
?.beginTransaction()
?.remove(this)
?.commitAllowingStateLoss()
}
override fun onCommit() {
val input = urlView.text.toString()
if (!input.trim { it <= ' ' }.isEmpty()) {
ViewUtils.hideKeyboard(urlView)
val isUrl = UrlUtils.isUrl(input)
val url = if (isUrl)
UrlUtils.normalize(input)
else
UrlUtils.createSearchUrl(context, input)
val searchTerms = if (isUrl)
null
else
input.trim { it <= ' ' }
openUrl(url, searchTerms)
TelemetryWrapper.urlBarEvent(isUrl)
}
}
private fun onSearch() {
val searchTerms = urlView.originalText
val searchUrl = UrlUtils.createSearchUrl(context, searchTerms)
openUrl(searchUrl, searchTerms)
TelemetryWrapper.searchSelectEvent()
}
private fun openUrl(url: String, searchTerms: String?) {
session?.searchTerms = searchTerms
val fragmentManager = activity!!.supportFragmentManager
// Replace all fragments with a fresh browser fragment. This means we either remove the
// HomeFragment with an UrlInputFragment on top or an old BrowserFragment with an
// UrlInputFragment.
val browserFragment = fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG)
if (browserFragment != null && browserFragment is BrowserFragment && browserFragment.isVisible) {
// Reuse existing visible fragment - in this case we know the user is already browsing.
// The fragment might exist if we "erased" a browsing session, hence we need to check
// for visibility in addition to existence.
browserFragment.loadUrl(url)
// And this fragment can be removed again.
fragmentManager.beginTransaction()
.remove(this)
.commit()
} else {
if (!TextUtils.isEmpty(searchTerms)) {
SessionManager.getInstance().createSearchSession(Source.USER_ENTERED, url, searchTerms)
} else {
SessionManager.getInstance().createSession(Source.USER_ENTERED, url)
}
}
}
override fun onFilter(searchText: String, view: InlineAutocompleteEditText?) {
// If the UrlInputFragment has already been hidden, don't bother with filtering. Because of the text
// input architecture on Android it's possible for onFilter() to be called after we've already
// hidden the Fragment, see the relevant bug for more background:
// https://github.com/mozilla-mobile/focus-android/issues/441#issuecomment-293691141
if (!isVisible) {
return
}
urlAutoCompleteFilter.onFilter(searchText, view)
if (searchText.trim { it <= ' ' }.isEmpty()) {
clearView.visibility = View.GONE
searchViewContainer.visibility = View.GONE
if (!isOverlay) {
playVisibilityAnimation(true)
}
} else {
clearView.visibility = View.VISIBLE
menuView.visibility = View.GONE
if (!isOverlay && dismissView.visibility != View.VISIBLE) {
playVisibilityAnimation(false)
dismissView.visibility = View.VISIBLE
}
// LTR languages sometimes have grammar where the search terms are displayed to the left
// of the hint string. To take care of LTR, RTL, and special LTR cases, we use a
// placeholder to know the start and end indices of where we should bold the search text
val hint = getString(R.string.search_hint, PLACEHOLDER)
val start = hint.indexOf(PLACEHOLDER)
val content = SpannableString(hint.replace(PLACEHOLDER, searchText))
content.setSpan(StyleSpan(Typeface.BOLD), start, start + searchText.length, 0)
searchView.text = content
searchViewContainer.visibility = View.VISIBLE
}
}
}
| mpl-2.0 | 869923d4f975560275100eebc8f878dc | 35.506744 | 160 | 0.610123 | 5.199506 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/seven/MyConcernModelImpl.kt | 1 | 5196 | package com.intfocus.template.subject.seven
import android.content.Context
import com.alibaba.fastjson.JSON
import com.intfocus.template.model.DaoUtil
import com.intfocus.template.model.entity.Report
import com.intfocus.template.model.gen.AttentionItemDao
import com.intfocus.template.model.response.attention.Test2
import com.intfocus.template.subject.one.ModeImpl
import com.intfocus.template.subject.one.ModeModel
import com.intfocus.template.subject.one.entity.Filter
import com.intfocus.template.util.LoadAssetsJsonUtil
import com.intfocus.template.util.LogUtil
import com.zbl.lib.baseframe.utils.TimeUtil
import rx.Observable
import rx.Observer
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
/**
* ****************************************************
* author jameswong
* created on: 17/12/18 上午11:28
* e-mail: [email protected]
* name: 模板七 数据处理类
* desc:
* ****************************************************
*/
class MyConcernModelImpl : MyConcernModel {
private val mDao = DaoUtil.getAttentionItemDao()
/**
* 默认只有一个页签
*/
private val pageId = 0
companion object {
private val TAG = "MyConcernModelImpl"
private var INSTANCE: MyConcernModelImpl? = null
private var observable: Subscription? = null
/**
* Returns the single instance of this class, creating it if necessary.
*/
@JvmStatic
fun getInstance(): MyConcernModelImpl {
return INSTANCE ?: MyConcernModelImpl()
.apply { INSTANCE = this }
}
/**
* Used to force [getInstance] to create a new instance
* next time it's called.
*/
@JvmStatic
fun destroyInstance() {
unSubscribe()
INSTANCE = null
}
/**
* 取消订阅
*/
private fun unSubscribe() {
observable?.unsubscribe() ?: return
}
}
override fun getData(userNum: String, filterId: String, callback: MyConcernModel.LoadDataCallback) {
val assetsJsonData = LoadAssetsJsonUtil.getAssetsJsonData("template7_main_attention_data.json")
val data = JSON.parseObject(assetsJsonData, Test2::class.java)
observable = Observable.just(data.data)
.subscribeOn(Schedulers.io())
.flatMap { it ->
mDao.deleteAll()
mDao.insertInTx(it?.attention_list)
Observable.from(data.data.attentioned_data)
}
.subscribe(object : Observer<Test2.DataBeanXX.AttentionedDataBean> {
override fun onError(e: Throwable?) {
LogUtil.d(this@MyConcernModelImpl, "数据库处理错误 ::: " + e?.message)
}
override fun onNext(it: Test2.DataBeanXX.AttentionedDataBean?) {
it?.let {
val attentionItem = mDao.queryBuilder().where(AttentionItemDao.Properties.Attention_item_id.eq(it.attention_item_id)).unique()
attentionItem.isAttentioned = true
mDao.update(attentionItem)
}
}
override fun onCompleted() {
LogUtil.d(this@MyConcernModelImpl, "数据库处理完成")
}
})
callback.onDataLoaded(data, data.data.filter)
}
override fun getData(ctx: Context, groupId: String, templateId: String, reportId: String, callback: MyConcernModel.LoadReportsDataCallback) {
ModeImpl.getInstance().getData(reportId, templateId, groupId, object : ModeModel.LoadDataCallback {
override fun onDataLoaded(reports: List<String>, filter: Filter) {
callback.onFilterDataLoaded(filter)
getData(reportId + templateId + groupId, pageId, callback)
}
override fun onDataNotAvailable(e: Throwable) {
}
})
}
fun getData(uuid: String, pageId: Int, callback: MyConcernModel.LoadReportsDataCallback) {
LogUtil.d(TAG, "StartAnalysisTime:" + TimeUtil.getNowTime())
observable = Observable.just("")
.subscribeOn(Schedulers.io())
.map {
ModeImpl.getInstance().queryPageData(uuid, pageId)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<List<Report>> {
override fun onError(e: Throwable?) {
e?.let {
callback.onDataNotAvailable(it)
}
}
override fun onNext(t: List<Report>?) {
t?.let {
callback.onReportsDataLoaded(it)
}
}
override fun onCompleted() {
LogUtil.d(TAG, "EndAnalysisTime:" + TimeUtil.getNowTime())
}
})
}
} | gpl-3.0 | ce68cc65657c819fa2097caa46ca31dd | 35.607143 | 154 | 0.565183 | 4.908046 | false | false | false | false |
kohesive/klutter | db-jdbi-v2/src/main/kotlin/uy/klutter/db/jdbi/v2/KotlinBinder.kt | 1 | 3429 | @file:Suppress("UNUSED_PARAMETER")
package uy.klutter.db.jdbi.v2
import org.skife.jdbi.v2.*
import org.skife.jdbi.v2.SQLStatement
import org.skife.jdbi.v2.sqlobject.Bind
import org.skife.jdbi.v2.sqlobject.*
import uy.klutter.reflect.erasedType
import java.lang.reflect.Method
import java.lang.reflect.Parameter
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.javaType
import kotlin.reflect.jvm.kotlinFunction
class KotlinBinder(val method: Method, val paramIdx: Int) : Binder<Bind, Any> {
val parameter = method.parameters[paramIdx]
override fun bind(q: SQLStatement<*>, bind: Bind?, arg: Any?) {
bind(q, parameter, bind, arg)
}
private fun Type.findGenericParameter(ofSuper: Class<*>): Type {
val genericSuperFirstType = erasedType().getGenericSuperclass().let { superClass ->
if (superClass !is ParameterizedType) {
throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information")
}
superClass.getActualTypeArguments()[0]
}
return genericSuperFirstType
}
private fun bind(q: SQLStatement<*>, parameter: Parameter, bind: Bind?, arg: Any?) {
val paramType = parameter.getParameterizedType()
val bindName = if (parameter.isNamePresent()) {
parameter.getName()
} else {
method.kotlinFunction?.parameters?.dropWhile { it.kind != KParameter.Kind.VALUE }?.toList()?.get(paramIdx)?.name
} ?: throw UnsupportedOperationException("A parameter was not given a name, "
+ "and parameter name data is not present in the class file, for: "
+ parameter.getDeclaringExecutable() + " :: " + parameter)
fun bind(q: SQLStatement<*>, bindToParm: String?, bindAsType: Type, value: Any?, prefix: String = "") {
val type = if (q is PreparedBatchPart) {
// FIXME BatchHandler should extract the iterable/iterator element type and pass it to the binder
val erasedType = bindAsType.erasedType()
if (Iterable::class.java.isAssignableFrom(erasedType)) {
bindAsType.findGenericParameter(Iterable::class.java)
} else if (Iterator::class.java.isAssignableFrom(erasedType)) {
bindAsType.findGenericParameter(Iterator::class.java)
} else {
bindAsType
}
} else {
bindAsType
}
val erasedType = type.erasedType()
if (erasedType.isKotlinClass()) {
@Suppress("UNCHECKED_CAST")
erasedType.kotlin.declaredMemberProperties.forEach { subProp ->
bind(q, subProp.name, subProp.returnType.javaType, if (value == null) null else subProp.get(value), "${prefix}${bindToParm}.")
}
} else {
if (bindToParm != null) {
q.bind("${prefix}${bindToParm}", value)
} else if (prefix.isNullOrBlank()) {
// we can't really bind sub items by order
q.bind(paramIdx, value)
}
}
}
bind(q, bindName, paramType, arg)
}
} | mit | 80f4d10a9c9eac0628dc8bcb214474fe | 41.345679 | 146 | 0.619423 | 4.596515 | false | false | false | false |
funkyg/funkytunes | app/src/main/kotlin/com/github/funkyg/funkytunes/network/SkyTorrentsAdapter.kt | 1 | 10146 | package com.github.funkyg.funkytunes.network
import android.content.Context
import android.util.Log
import com.android.volley.toolbox.HttpHeaderParser
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.NetworkResponse
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.frostwire.jlibtorrent.*
import com.github.funkyg.funkytunes.Album
import com.github.funkyg.funkytunes.FunkyApplication
import com.github.funkyg.funkytunes.R
import com.google.common.io.Files
import java.io.IOException
import java.net.URLEncoder
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
/**
* Parses SkyTorrents search results from HTML.
*/
class SkyTorrentsAdapter(context: Context) {
private val Tag = "SkyTorrentsAdapter"
private val DOMAINS = arrayOf("https://www.skytorrents.in")
private val QUERYURL = "/search/all/ss/1/?l=en_us&q=%s"
@Inject lateinit var volleyQueue: RequestQueue
init {
(context.applicationContext as FunkyApplication).component.inject(this)
}
fun search(album: Album, resultCollector:SearchResultCollector) {
search_mirror(0, album, resultCollector)
}
fun search_mirror(retry: Int, album: Album, resultCollector: SearchResultCollector) {
val query = album.getQuery()
if(retry < DOMAINS.size) {
val domain = DOMAINS[retry]
// Build full URL string
val url = String.format(domain + QUERYURL, URLEncoder.encode(query, "UTF-8"))
Log.i(Tag, "Trying URL: " + url)
// Get the results page
val request = object : StringRequest(Method.GET, url, Response.Listener<String> { reply ->
val parsedResults = parseHtml(reply, domain)
// Fetch torrent files for results
for (item in parsedResults) {
Log.i(Tag, "Trying torrent URL: " + item.torrentUrl)
val torrentRequest = object : Request<TorrentInfo>(Method.GET, item.torrentUrl, Response.ErrorListener { error ->
Log.i(Tag, "Volley error '" + error.message + "' for URL: " + item.torrentUrl)
val lowerTitle = item.title.toLowerCase()
// Add magnet if it has a supported file format in name
if(lowerTitle.indexOf("mp3") != -1 || lowerTitle.indexOf("ogg") != -1 || lowerTitle.indexOf("m4a") != -1) {
resultCollector.addResult(item)
} else if(lowerTitle.indexOf("flac") != -1) {
item.flacDetected()
resultCollector.addResult(item)
} else {
resultCollector.addFailed()
}
}){
override fun parseNetworkResponse(response: NetworkResponse) : Response<TorrentInfo> {
if (response.statusCode == 429) {
resultCollector.notify429()
return Response.error(VolleyError("Error 429 getting torrent from " + item.torrentUrl))
}
else
{
val bytes = response.data
if (bytes != null) {
val tmp = createTempFile("funkytunes", ".torrent")
Files.write(bytes, tmp)
try {
val ti = TorrentInfo(tmp)
return Response.success(ti, HttpHeaderParser.parseCacheHeaders(response))
} catch (e: IllegalArgumentException) {
return Response.error(VolleyError("Error " + e.message + " parsing torrent from " + item.torrentUrl))
} catch (e: IOException) {
return Response.error(VolleyError("Error " + e.message + " parsing torrent from " + item.torrentUrl))
} finally {
tmp.delete()
}
} else {
Log.i(Tag, "Empty bytes returned from URL: " + item.torrentUrl)
return Response.error(VolleyError("Empty bytes returned from URL: " + item.torrentUrl))
}
}
}
override fun deliverResponse(response: TorrentInfo) {
val ti = response
item.torrentInfo = ti
val origFiles = ti.origFiles()
var fileUsable = false
try {
Log.i(Tag, "Parsing torrent from URL: " + item.torrentUrl)
for (fileNum in 0..origFiles.numFiles()-1) {
val fileName = origFiles.filePath(fileNum)
if(fileName.endsWith(".mp3") || fileName.endsWith(".flac") || fileName.endsWith(".ogg") || fileName.endsWith(".m4a")) {
if(!fileUsable) {
Log.i(Tag, "Torrent usable: " + item.torrentUrl)
resultCollector.addResult(item)
}
if(fileName.endsWith(".flac")) {
item.flacDetected()
}
fileUsable = true
}
}
if(!fileUsable) {
resultCollector.addFailed()
}
}
catch (e: Exception) {
Log.w(Tag, "Error " + e.message + " parsing torrent URL: " + item.torrentUrl)
resultCollector.addFailed()
}
}
}
torrentRequest.tag = query
resultCollector.watchRequest(torrentRequest)
Log.i(Tag, "Added torrent request to watch ${item.torrentUrl}")
volleyQueue.add(torrentRequest)
}
Log.i(Tag, "GO()!!!!")
resultCollector.go()
}, Response.ErrorListener { error ->
Log.i(Tag, error.message ?: "(No message from volley)")
search_mirror(retry + 1, album, resultCollector)
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("User-agent", "FunkyTunes")
return headers
}
}
volleyQueue.add(request)
} else {
Log.i(Tag, "GO()!!!! [err]")
resultCollector.go()
}
}
private fun parseHtml(html: String, prefixDetails: String): List<SearchResult> {
// Texts to find subsequently
val RESULTS = "<tbody>"
val TORRENT = "<td style=\"word-wrap: break-word;\">"
// Parse the search results from HTML by looking for the identifying texts
val results = ArrayList<SearchResult>()
val resultsStart = html.indexOf(RESULTS) + RESULTS.length
var torStart = html.indexOf(TORRENT, resultsStart)
while (torStart >= 0) {
val nextTorrentIndex = html.indexOf(TORRENT, torStart + TORRENT.length)
if (nextTorrentIndex >= 0) {
results.add(parseHtmlItem(html.substring(torStart + TORRENT.length, nextTorrentIndex), prefixDetails))
} else {
results.add(parseHtmlItem(html.substring(torStart + TORRENT.length), prefixDetails))
}
torStart = nextTorrentIndex
}
return results.slice(0..Math.min(5, results.size - 1))
}
private fun parseHtmlItem(htmlItem: String, prefixDetails: String): SearchResult {
// TODO: parse XML file instead?
// Texts to find subsequently
val DETAILS = "<a href=\""
val DETAILS_END = "\" title=\""
val NAME = "\">"
val NAME_END = "</a>"
val MAGNET_LINK = "<a href=\""
val MAGNET_LINK_END = "\" rel=\"nofollow\""
val SIZE = "<td class=\"is-hidden-touch\" >"
val SIZE_END = "</td>"
val NUMFILES = "<td class=\"is-hidden-touch\" style=\"text-align: center;\" >"
val NUMFILES_END = "</td>"
val DATE = "<td class=\"is-hidden-touch\" style=\"text-align: center;\">"
val DATE_END = "</td>"
val SEEDERS = "<td style=\"text-align: center;\">"
val SEEDERS_END = "</td>"
val LEECHERS = "<td style=\"text-align: center;\">"
val LEECHERS_END = "</td>"
val prefixYear = (Calendar.getInstance().get(Calendar.YEAR)).toString() + " " // Date.getYear() gives the current year - 1900
val df1 = SimpleDateFormat("yyyy MM-dd HH:mm", Locale.US)
val df2 = SimpleDateFormat("MM-dd yyyy", Locale.US)
val detailsStart = htmlItem.indexOf(DETAILS) + DETAILS.length
var details = htmlItem.substring(detailsStart, htmlItem.indexOf(DETAILS_END, detailsStart))
details = prefixDetails + details
val nameStart = htmlItem.indexOf(NAME, detailsStart) + NAME.length
val name = htmlItem.substring(nameStart, htmlItem.indexOf(NAME_END, nameStart))
val torrentLink = ""
// Magnet link is second
val magnetLinkStart = htmlItem.indexOf(MAGNET_LINK, nameStart) + MAGNET_LINK.length
val magnetLink = htmlItem.substring(magnetLinkStart, htmlItem.indexOf(MAGNET_LINK_END, magnetLinkStart))
val sizeStart = htmlItem.indexOf(SIZE, magnetLinkStart) + SIZE.length
var size = htmlItem.substring(sizeStart, htmlItem.indexOf(SIZE_END, sizeStart))
size = size.replace(" ", " ")
val numFilesStart = htmlItem.indexOf(NUMFILES, sizeStart) + NUMFILES.length
var numFiles = htmlItem.substring(numFilesStart, htmlItem.indexOf(NUMFILES_END, numFilesStart))
numFiles = numFiles.replace(" ", " ")
val dateStart = htmlItem.indexOf(DATE, numFilesStart) + DATE.length
var dateText = htmlItem.substring(dateStart, htmlItem.indexOf(DATE_END, dateStart))
dateText = dateText.replace(" ", " ")
var date: Date? = null
if (dateText.startsWith("Today")) {
date = Date()
} else if (dateText.startsWith("Y-day")) {
date = Date(Date().time - 86400000L)
} else {
try {
date = df1.parse(prefixYear + dateText)
} catch (e: ParseException) {
try {
date = df2.parse(dateText)
} catch (e1: ParseException) {
// Not parsable at all; just leave it at null
}
}
}
val seedersStart = htmlItem.indexOf(SEEDERS, dateStart) + SEEDERS.length
val seedersText = htmlItem.substring(seedersStart, htmlItem.indexOf(SEEDERS_END, seedersStart))
val seeders = Integer.parseInt(seedersText)
val leechersStart = htmlItem.indexOf(LEECHERS, seedersStart) + LEECHERS.length
val leechersText = htmlItem.substring(leechersStart, htmlItem.indexOf(LEECHERS_END, leechersStart))
val leechers = Integer.parseInt(leechersText)
return SearchResult(name, magnetLink, torrentLink, details,
size, date, seeders, leechers,
null)
}
}
| gpl-3.0 | 32ad3057fdfd704da8babb7145d1221b | 38.478599 | 133 | 0.635521 | 3.754996 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/data/ServerConfig.kt | 1 | 6113 | package com.msc.serverbrowser.data
import com.msc.serverbrowser.data.entites.SampServer
import com.msc.serverbrowser.severe
import java.sql.SQLException
import java.util.*
/**
* Allows controller over server specific settings. TODO(MSC) I could still improve the setter
* methods in case the table gets more fields.
*
* @author marcel
* @since Jan 17, 2018
*/
object ServerConfig {
/**
* Sets the username to use when connect to to that specific server.
*
* @param ip server ip
* @param port server port
* @param username the username to be set
* @return true if the action was a success, otherwise false
*/
fun setUsernameForServer(ip: String, port: Int, username: String): Boolean {
val query = ("INSERT OR REPLACE INTO serverconfig (ip, port, username, lastJoin ) values (" + "?," // IP
+ "?," // Port
+ "?," // Username
+ "(select lastjoin from serverconfig where ip=? and port=?));") // lastTimeJoined
try {
SQLDatabase.createPreparedStatement(query).use { statement ->
statement.setString(1, ip)
statement.setInt(2, port)
statement.setString(3, username)
statement.setString(4, ip)
statement.setInt(5, port)
return statement.execute()
}
} catch (exception: SQLException) {
severe("Error while setting username.", exception)
return false
}
}
/**
* Returns the username to use for a specific server or an empty [Optional] in case no
* username has been set.
*
* @param ip server ip
* @param port server port
* @return An [Optional] containing the to be used username or empty
*/
fun getUsernameForServer(ip: String, port: Int): Optional<String> {
return getStringOfField(ip, port, "username")
}
/**
* Saves the last time a server has been joined.
*
* @param ip ip
* @param port port
* @param lastTimeJoined lastTimeJoined
* @return true if the action was a success, otherwise false
*/
fun setLastTimeJoinedForServer(ip: String, port: Int, lastTimeJoined: Long): Boolean {
val query = ("INSERT OR REPLACE INTO serverconfig (ip, port, username, lastJoin ) values (" + "?," // IP
+ "?," // Port
+ "(select username from serverconfig where ip=? and port=?)," // Username
+ "?);") // lastTimeJoined
try {
SQLDatabase.createPreparedStatement(query).use { statement ->
statement.setString(1, ip)
statement.setInt(2, port)
statement.setString(3, ip)
statement.setInt(4, port)
statement.setLong(5, lastTimeJoined)
return statement.execute()
}
} catch (exception: SQLException) {
severe("Error while setting last join time.", exception)
return false
}
}
/**
* Returns the username to use for a specific server or an empty [Optional] in case no
* username has been set.
*
* @param ip server ip
* @param port server port
* @return An [Optional] containing the to be used username or empty
*/
private fun getLastJoinForServer(ip: String, port: Int): Optional<Long> {
return getStringOfField(ip, port, "lastJoin").map { it.toLong() }
}
/**
* Returns a list of all [SampServer]s which have a lastJoin date, the returned data
* doesn't contain any other data whatsoever (hostname and so on).
*
* @return a [List] of all previously joined [SampServer]s
*/
val lastJoinedServers: List<SampServer>
get() {
val statement = "SELECT ip, port, lastJoin FROM serverconfig WHERE lastJoin IS NOT NULL;"
val resultSet = SQLDatabase.executeGetResult(statement)
val servers = ArrayList<SampServer>()
if (resultSet != null) {
try {
resultSet.use {
while (it.next()) {
val server = SampServer(it.getString("ip"), it.getInt("port"))
server.lastJoin = java.lang.Long.parseLong(it.getString("lastJoin"))
servers.add(server)
}
}
} catch (exception: SQLException) {
severe("Error while retrieving previously joined servers.", exception)
}
}
return servers
}
/**
* Fills a [Collection] of servers with their last join date.
*
* @param servers servers to inject their last join date into
*/
fun initLastJoinData(servers: Collection<SampServer>) {
servers.forEach { server -> getLastJoinForServer(server.address, server.port).ifPresent { server.lastJoin = it } }
}
private fun getStringOfField(ip: String, port: Int, field: String): Optional<String> {
val query = "SELECT $field FROM serverconfig WHERE ip=? and port=? AND $field IS NOT NULL;"
try {
SQLDatabase.createPreparedStatement(query).use { statement ->
statement.setString(1, ip)
statement.setInt(2, port)
val resultSet = SQLDatabase.executeGetResult(statement)
if (resultSet != null) {
try {
resultSet.use {
if (it.next()) {
return Optional.of(it.getString(field))
}
}
} catch (exception: SQLException) {
severe("Error while retrieving field: '$field of server: $ip:$port", exception)
}
}
}
} catch (exception: SQLException) {
severe("Error getting field from server config.", exception)
}
return Optional.empty()
}
} | mpl-2.0 | 2a05653dfd8193f40c918b4f91aca373 | 33.738636 | 122 | 0.558973 | 4.720463 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/AutotuneCore.kt | 1 | 25976 | package info.nightscout.androidaps.plugins.general.autotune
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.LocalInsulin
import info.nightscout.androidaps.plugins.general.autotune.data.ATProfile
import info.nightscout.androidaps.plugins.general.autotune.data.PreppedGlucose
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.Round
import info.nightscout.shared.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class AutotuneCore @Inject constructor(
private val sp: SP,
private val autotuneFS: AutotuneFS
) {
fun tuneAllTheThings(preppedGlucose: PreppedGlucose, previousAutotune: ATProfile, pumpProfile: ATProfile): ATProfile {
//var pumpBasalProfile = pumpProfile.basalprofile;
val pumpBasalProfile = pumpProfile.basal
//console.error(pumpBasalProfile);
var basalProfile = previousAutotune.basal
//console.error(basalProfile);
//console.error(isfProfile);
var isf = previousAutotune.isf
//console.error(isf);
var carbRatio = previousAutotune.ic
//console.error(carbRatio);
val csf = isf / carbRatio
val dia = previousAutotune.dia
val peak = previousAutotune.peak
val csfGlucose = preppedGlucose.csfGlucoseData
val isfGlucose = preppedGlucose.isfGlucoseData
val basalGlucose = preppedGlucose.basalGlucoseData
val crData = preppedGlucose.crData
val diaDeviations = preppedGlucose.diaDeviations
val peakDeviations = preppedGlucose.peakDeviations
val pumpISF = pumpProfile.isf
val pumpCarbRatio = pumpProfile.ic
val pumpCSF = pumpISF / pumpCarbRatio
// Autosens constraints
val autotuneMax = sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)
val autotuneMin = sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)
val min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)
// tune DIA
var newDia = dia
if (diaDeviations.size > 0)
{
val currentDiaMeanDev = diaDeviations[2].meanDeviation
val currentDiaRMSDev = diaDeviations[2].rmsDeviation
//Console.WriteLine(DIA,currentDIAMeanDev,currentDIARMSDev);
var minMeanDeviations = 1000000.0
var minRmsDeviations = 1000000.0
var meanBest = 2
var rmsBest = 2
for (i in 0..diaDeviations.size-1)
{
val meanDeviations = diaDeviations[i].meanDeviation
val rmsDeviations = diaDeviations[i].rmsDeviation
if (meanDeviations < minMeanDeviations)
{
minMeanDeviations = Round.roundTo(meanDeviations, 0.001)
meanBest = i
}
if (rmsDeviations < minRmsDeviations)
{
minRmsDeviations = Round.roundTo(rmsDeviations, 0.001)
rmsBest = i
}
}
log("Best insulinEndTime for meanDeviations: ${diaDeviations[meanBest].dia} hours")
log("Best insulinEndTime for RMSDeviations: ${diaDeviations[rmsBest].dia} hours")
if (meanBest < 2 && rmsBest < 2)
{
if (diaDeviations[1].meanDeviation < currentDiaMeanDev * 0.99 && diaDeviations[1].rmsDeviation < currentDiaRMSDev * 0.99)
newDia = diaDeviations[1].dia
}
else if (meanBest > 2 && rmsBest > 2)
{
if (diaDeviations[3].meanDeviation < currentDiaMeanDev * 0.99 && diaDeviations[3].rmsDeviation < currentDiaRMSDev * 0.99)
newDia = diaDeviations[3].dia
}
if (newDia > 12.0)
{
log("insulinEndTime maximum is 12h: not raising further")
newDia = 12.0
}
if (newDia != dia)
log("Adjusting insulinEndTime from $dia to $newDia hours")
else
log("Leaving insulinEndTime unchanged at $dia hours")
}
// tune insulinPeakTime
var newPeak = peak
if (peakDeviations.size > 2)
{
val currentPeakMeanDev = peakDeviations[2].meanDeviation
val currentPeakRMSDev = peakDeviations[2].rmsDeviation
//Console.WriteLine(currentPeakMeanDev);
var minMeanDeviations = 1000000.0
var minRmsDeviations = 1000000.0
var meanBest = 2
var rmsBest = 2
for (i in 0..peakDeviations.size-1)
{
val meanDeviations = peakDeviations[i].meanDeviation;
val rmsDeviations = peakDeviations[i].rmsDeviation;
if (meanDeviations < minMeanDeviations)
{
minMeanDeviations = Round.roundTo(meanDeviations, 0.001)
meanBest = i
}
if (rmsDeviations < minRmsDeviations)
{
minRmsDeviations = Round.roundTo(rmsDeviations, 0.001)
rmsBest = i
}
}
log("Best insulinPeakTime for meanDeviations: ${peakDeviations[meanBest].peak} minutes")
log("Best insulinPeakTime for RMSDeviations: ${peakDeviations[rmsBest].peak} minutes")
if (meanBest < 2 && rmsBest < 2)
{
if (peakDeviations[1].meanDeviation < currentPeakMeanDev * 0.99 && peakDeviations[1].rmsDeviation < currentPeakRMSDev * 0.99)
newPeak = peakDeviations[1].peak
}
else if (meanBest > 2 && rmsBest > 2)
{
if (peakDeviations[3].meanDeviation < currentPeakMeanDev * 0.99 && peakDeviations[3].rmsDeviation < currentPeakRMSDev * 0.99)
newPeak = peakDeviations[3].peak
}
if (newPeak != peak)
log("Adjusting insulinPeakTime from " + peak + " to " + newPeak + " minutes")
else
log("Leaving insulinPeakTime unchanged at " + peak)
}
// Calculate carb ratio (CR) independently of csf and isf
// Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2
// For now, if another meal IOB/COB stacks on top of it, consider them together
// Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize
// Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR.
//autotune-core (lib/autotune/index.js) #149-#165
var crTotalCarbs = 0.0
var crTotalInsulin = 0.0
for (i in crData.indices) {
val crDatum = crData[i]
val crBGChange = crDatum.crEndBG - crDatum.crInitialBG
val crInsulinReq = crBGChange / isf
//val crIOBChange = crDatum.crEndIOB - crDatum.crInitialIOB
crDatum.crInsulinTotal = crDatum.crInitialIOB + crDatum.crInsulin + crInsulinReq
//log(crDatum.crInitialIOB + " " + crDatum.crInsulin + " " + crInsulinReq + " " + crDatum.crInsulinTotal);
//val cr = Round.roundTo(crDatum.crCarbs / crDatum.crInsulinTotal, 0.001)
//log(crBGChange + " " + crInsulinReq + " " + crIOBChange + " " + crDatum.crInsulinTotal);
//log("CRCarbs: " + crDatum.crCarbs + " CRInsulin: " + crDatum.crInsulinTotal + " CR:" + cr);
if (crDatum.crInsulinTotal > 0) {
crTotalCarbs += crDatum.crCarbs
crTotalInsulin += crDatum.crInsulinTotal
}
}
//autotune-core (lib/autotune/index.js) #166-#169
crTotalInsulin = Round.roundTo(crTotalInsulin, 0.001)
var totalCR = 0.0
if (crTotalInsulin != 0.0)
totalCR = Round.roundTo(crTotalCarbs / crTotalInsulin, 0.001)
log("crTotalCarbs: $crTotalCarbs crTotalInsulin: $crTotalInsulin totalCR: $totalCR")
//autotune-core (lib/autotune/index.js) #170-#209 (already hourly in aaps)
// convert the basal profile to hourly if it isn't already
val hourlyBasalProfile = basalProfile
//log(hourlyPumpProfile.toString());
//log(hourlyBasalProfile.toString());
val newHourlyBasalProfile = DoubleArray(24)
for (i in 0..23) {
newHourlyBasalProfile[i] = hourlyBasalProfile[i]
}
val basalUntuned = previousAutotune.basalUntuned
//autotune-core (lib/autotune/index.js) #210-#266
// look at net deviations for each hour
for (hour in 0..23) {
var deviations = 0.0
for (i in basalGlucose.indices) {
val BGTime = Calendar.getInstance()
//var BGTime: Date? = null
if (basalGlucose[i].date != 0L) {
BGTime.setTimeInMillis(basalGlucose[i].date)
//BGTime = Date(basalGlucose[i].date)
} else {
log("Could not determine last BG time")
}
val myHour = BGTime.get(Calendar.HOUR_OF_DAY)
//val myHour = BGTime!!.hours
if (hour == myHour) {
//log.debug(basalGlucose[i].deviation);
deviations += basalGlucose[i].deviation
}
}
deviations = Round.roundTo(deviations, 0.001)
log("Hour $hour total deviations: $deviations mg/dL")
// calculate how much less or additional basal insulin would have been required to eliminate the deviations
// only apply 20% of the needed adjustment to keep things relatively stable
var basalNeeded = 0.2 * deviations / isf
basalNeeded = Round.roundTo(basalNeeded, 0.01)
// if basalNeeded is positive, adjust each of the 1-3 hour prior basals by 10% of the needed adjustment
log("Hour $hour basal adjustment needed: $basalNeeded U/hr")
if (basalNeeded > 0) {
for (offset in -3..-1) {
var offsetHour = hour + offset
if (offsetHour < 0) {
offsetHour += 24
}
//log.debug(offsetHour);
newHourlyBasalProfile[offsetHour] = newHourlyBasalProfile[offsetHour] + basalNeeded / 3
newHourlyBasalProfile[offsetHour] = Round.roundTo(newHourlyBasalProfile[offsetHour], 0.001)
}
// otherwise, figure out the percentage reduction required to the 1-3 hour prior basals
// and adjust all of them downward proportionally
} else if (basalNeeded < 0) {
var threeHourBasal = 0.0
for (offset in -3..-1) {
var offsetHour = hour + offset
if (offsetHour < 0) {
offsetHour += 24
}
threeHourBasal += newHourlyBasalProfile[offsetHour]
}
val adjustmentRatio = 1.0 + basalNeeded / threeHourBasal
//log.debug(adjustmentRatio);
for (offset in -3..-1) {
var offsetHour = hour + offset
if (offsetHour < 0) {
offsetHour += 24
}
newHourlyBasalProfile[offsetHour] = newHourlyBasalProfile[offsetHour] * adjustmentRatio
newHourlyBasalProfile[offsetHour] = Round.roundTo(newHourlyBasalProfile[offsetHour], 0.001)
}
}
}
//autotune-core (lib/autotune/index.js) #267-#294
for (hour in 0..23) {
//log.debug(newHourlyBasalProfile[hour],hourlyPumpProfile[hour].rate*1.2);
// cap adjustments at autosens_max and autosens_min
val maxRate = pumpBasalProfile[hour] * autotuneMax
val minRate = pumpBasalProfile[hour] * autotuneMin
if (newHourlyBasalProfile[hour] > maxRate) {
log("Limiting hour " + hour + " basal to " + Round.roundTo(maxRate, 0.01) + " (which is " + Round.roundTo(autotuneMax, 0.01) + " * pump basal of " + pumpBasalProfile[hour] + ")")
//log.debug("Limiting hour",hour,"basal to",maxRate.toFixed(2),"(which is 20% above pump basal of",hourlyPumpProfile[hour].rate,")");
newHourlyBasalProfile[hour] = maxRate
} else if (newHourlyBasalProfile[hour] < minRate) {
log("Limiting hour " + hour + " basal to " + Round.roundTo(minRate, 0.01) + " (which is " + autotuneMin + " * pump basal of " + newHourlyBasalProfile[hour] + ")")
//log.debug("Limiting hour",hour,"basal to",minRate.toFixed(2),"(which is 20% below pump basal of",hourlyPumpProfile[hour].rate,")");
newHourlyBasalProfile[hour] = minRate
}
newHourlyBasalProfile[hour] = Round.roundTo(newHourlyBasalProfile[hour], 0.001)
}
// some hours of the day rarely have data to tune basals due to meals.
// when no adjustments are needed to a particular hour, we should adjust it toward the average of the
// periods before and after it that do have data to be tuned
var lastAdjustedHour = 0
// scan through newHourlyBasalProfile and find hours where the rate is unchanged
//autotune-core (lib/autotune/index.js) #302-#323
for (hour in 0..23) {
if (hourlyBasalProfile[hour] == newHourlyBasalProfile[hour]) {
var nextAdjustedHour = 23
for (nextHour in hour..23) {
if (hourlyBasalProfile[nextHour] != newHourlyBasalProfile[nextHour]) {
nextAdjustedHour = nextHour
break
//} else {
// log("At hour: "+nextHour +" " + hourlyBasalProfile[nextHour] + " " +newHourlyBasalProfile[nextHour]);
}
}
//log.debug(hour, newHourlyBasalProfile);
newHourlyBasalProfile[hour] = Round.roundTo(0.8 * hourlyBasalProfile[hour] + 0.1 * newHourlyBasalProfile[lastAdjustedHour] + 0.1 * newHourlyBasalProfile[nextAdjustedHour], 0.001)
basalUntuned[hour]++
log("Adjusting hour " + hour + " basal from " + hourlyBasalProfile[hour] + " to " + newHourlyBasalProfile[hour] + " based on hour " + lastAdjustedHour + " = " + newHourlyBasalProfile[lastAdjustedHour] + " and hour " + nextAdjustedHour + " = " + newHourlyBasalProfile[nextAdjustedHour])
} else {
lastAdjustedHour = hour
}
}
//log(newHourlyBasalProfile.toString());
basalProfile = newHourlyBasalProfile
// Calculate carb ratio (CR) independently of csf and isf
// Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2
// For now, if another meal IOB/COB stacks on top of it, consider them together
// Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize
// Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR.
// calculate net deviations while carbs are absorbing
// measured from carb entry until COB and deviations both drop to zero
var deviations = 0.0
var mealCarbs = 0
var totalMealCarbs = 0
var totalDeviations = 0.0
val fullNewCSF: Double
//log.debug(CSFGlucose[0].mealAbsorption);
//log.debug(CSFGlucose[0]);
//autotune-core (lib/autotune/index.js) #346-#365
for (i in csfGlucose.indices) {
//log.debug(CSFGlucose[i].mealAbsorption, i);
if (csfGlucose[i].mealAbsorption === "start") {
deviations = 0.0
mealCarbs = csfGlucose[i].mealCarbs
} else if (csfGlucose[i].mealAbsorption === "end") {
deviations += csfGlucose[i].deviation
// compare the sum of deviations from start to end vs. current csf * mealCarbs
//log.debug(csf,mealCarbs);
//val csfRise = csf * mealCarbs
//log.debug(deviations,isf);
//log.debug("csfRise:",csfRise,"deviations:",deviations);
totalMealCarbs += mealCarbs
totalDeviations += deviations
} else {
//todo Philoul check 0 * min5minCarbImpact ???
deviations += Math.max(0 * min5minCarbImpact, csfGlucose[i].deviation)
mealCarbs = Math.max(mealCarbs, csfGlucose[i].mealCarbs)
}
}
// at midnight, write down the mealcarbs as total meal carbs (to prevent special case of when only one meal and it not finishing absorbing by midnight)
// TODO: figure out what to do with dinner carbs that don't finish absorbing by midnight
if (totalMealCarbs == 0) {
totalMealCarbs += mealCarbs
}
if (totalDeviations == 0.0) {
totalDeviations += deviations
}
//log.debug(totalDeviations, totalMealCarbs);
fullNewCSF = if (totalMealCarbs == 0) {
// if no meals today, csf is unchanged
csf
} else {
// how much change would be required to account for all of the deviations
Round.roundTo(totalDeviations / totalMealCarbs, 0.01)
}
// only adjust by 20%
var newCSF = 0.8 * csf + 0.2 * fullNewCSF
// safety cap csf
if (pumpCSF != 0.0) {
val maxCSF = pumpCSF * autotuneMax
val minCSF = pumpCSF * autotuneMin
if (newCSF > maxCSF) {
log("Limiting csf to " + Round.roundTo(maxCSF, 0.01) + " (which is " + autotuneMax + "* pump csf of " + pumpCSF + ")")
newCSF = maxCSF
} else if (newCSF < minCSF) {
log("Limiting csf to " + Round.roundTo(minCSF, 0.01) + " (which is" + autotuneMin + "* pump csf of " + pumpCSF + ")")
newCSF = minCSF
} //else { log.debug("newCSF",newCSF,"is close enough to",pumpCSF); }
}
val oldCSF = Round.roundTo(csf, 0.001)
newCSF = Round.roundTo(newCSF, 0.001)
totalDeviations = Round.roundTo(totalDeviations, 0.001)
log("totalMealCarbs: $totalMealCarbs totalDeviations: $totalDeviations oldCSF $oldCSF fullNewCSF: $fullNewCSF newCSF: $newCSF")
// this is where csf is set based on the outputs
//if (newCSF != 0.0) {
// csf = newCSF
//}
var fullNewCR: Double
fullNewCR = if (totalCR == 0.0) {
// if no meals today, CR is unchanged
carbRatio
} else {
// how much change would be required to account for all of the deviations
totalCR
}
// don't tune CR out of bounds
var maxCR = pumpCarbRatio * autotuneMax
if (maxCR > 150) {
maxCR = 150.0
}
var minCR = pumpCarbRatio * autotuneMin
if (minCR < 3) {
minCR = 3.0
}
// safety cap fullNewCR
if (pumpCarbRatio != 0.0) {
if (fullNewCR > maxCR) {
log("Limiting fullNewCR from " + fullNewCR + " to " + Round.roundTo(maxCR, 0.01) + " (which is " + autotuneMax + " * pump CR of " + pumpCarbRatio + ")")
fullNewCR = maxCR
} else if (fullNewCR < minCR) {
log("Limiting fullNewCR from " + fullNewCR + " to " + Round.roundTo(minCR, 0.01) + " (which is " + autotuneMin + " * pump CR of " + pumpCarbRatio + ")")
fullNewCR = minCR
} //else { log.debug("newCR",newCR,"is close enough to",pumpCarbRatio); }
}
// only adjust by 20%
var newCR = 0.8 * carbRatio + 0.2 * fullNewCR
// safety cap newCR
if (pumpCarbRatio != 0.0) {
if (newCR > maxCR) {
log("Limiting CR to " + Round.roundTo(maxCR, 0.01) + " (which is " + autotuneMax + " * pump CR of " + pumpCarbRatio + ")")
newCR = maxCR
} else if (newCR < minCR) {
log("Limiting CR to " + Round.roundTo(minCR, 0.01) + " (which is " + autotuneMin + " * pump CR of " + pumpCarbRatio + ")")
newCR = minCR
} //else { log.debug("newCR",newCR,"is close enough to",pumpCarbRatio); }
}
newCR = Round.roundTo(newCR, 0.001)
log("oldCR: $carbRatio fullNewCR: $fullNewCR newCR: $newCR")
// this is where CR is set based on the outputs
//var ISFFromCRAndCSF = isf;
if (newCR != 0.0) {
carbRatio = newCR
//ISFFromCRAndCSF = Math.round( carbRatio * csf * 1000)/1000;
}
// calculate median deviation and bgi in data attributable to isf
val isfDeviations: MutableList<Double> = ArrayList()
val bGIs: MutableList<Double> = ArrayList()
val avgDeltas: MutableList<Double> = ArrayList()
val ratios: MutableList<Double> = ArrayList()
var count = 0
for (i in isfGlucose.indices) {
val deviation = isfGlucose[i].deviation
isfDeviations.add(deviation)
val BGI = isfGlucose[i].bgi
bGIs.add(BGI)
val avgDelta = isfGlucose[i].avgDelta
avgDeltas.add(avgDelta)
val ratio = 1 + deviation / BGI
//log.debug("Deviation:",deviation,"BGI:",BGI,"avgDelta:",avgDelta,"ratio:",ratio);
ratios.add(ratio)
count++
}
Collections.sort(avgDeltas)
Collections.sort(bGIs)
Collections.sort(isfDeviations)
Collections.sort(ratios)
var p50deviation = IobCobCalculatorPlugin.percentile(isfDeviations.toTypedArray(), 0.50)
var p50BGI = IobCobCalculatorPlugin.percentile(bGIs.toTypedArray(), 0.50)
val p50ratios = Round.roundTo(IobCobCalculatorPlugin.percentile(ratios.toTypedArray(), 0.50), 0.001)
var fullNewISF = isf
if (count < 10) {
// leave isf unchanged if fewer than 5 isf data points
log("Only found " + isfGlucose.size + " ISF data points, leaving ISF unchanged at " + isf)
} else {
// calculate what adjustments to isf would have been necessary to bring median deviation to zero
fullNewISF = isf * p50ratios
}
fullNewISF = Round.roundTo(fullNewISF, 0.001)
// adjust the target isf to be a weighted average of fullNewISF and pumpISF
val adjustmentFraction: Double
/*
// TODO: philoul may be allow adjustmentFraction in settings with safety limits ?)
if (typeof(pumpProfile.autotune_isf_adjustmentFraction) !== 'undefined') {
adjustmentFraction = pumpProfile.autotune_isf_adjustmentFraction;
} else {*/
adjustmentFraction = 1.0
// }
// low autosens ratio = high isf
val maxISF = pumpISF / autotuneMin
// high autosens ratio = low isf
val minISF = pumpISF / autotuneMax
var adjustedISF = 0.0
var newISF = 0.0
if (pumpISF != 0.0) {
adjustedISF = if (fullNewISF < 0) {
isf
} else {
adjustmentFraction * fullNewISF + (1 - adjustmentFraction) * pumpISF
}
// cap adjustedISF before applying 10%
//log.debug(adjustedISF, maxISF, minISF);
if (adjustedISF > maxISF) {
log("Limiting adjusted isf of " + Round.roundTo(adjustedISF, 0.01) + " to " + Round.roundTo(maxISF, 0.01) + "(which is pump isf of " + pumpISF + "/" + autotuneMin + ")")
adjustedISF = maxISF
} else if (adjustedISF < minISF) {
log("Limiting adjusted isf of" + Round.roundTo(adjustedISF, 0.01) + " to " + Round.roundTo(minISF, 0.01) + "(which is pump isf of " + pumpISF + "/" + autotuneMax + ")")
adjustedISF = minISF
}
// and apply 20% of that adjustment
newISF = 0.8 * isf + 0.2 * adjustedISF
if (newISF > maxISF) {
log("Limiting isf of" + Round.roundTo(newISF, 0.01) + "to" + Round.roundTo(maxISF, 0.01) + "(which is pump isf of" + pumpISF + "/" + autotuneMin + ")")
newISF = maxISF
} else if (newISF < minISF) {
log("Limiting isf of" + Round.roundTo(newISF, 0.01) + "to" + Round.roundTo(minISF, 0.01) + "(which is pump isf of" + pumpISF + "/" + autotuneMax + ")")
newISF = minISF
}
}
newISF = Round.roundTo(newISF, 0.001)
//log.debug(avgRatio);
//log.debug(newISF);
p50deviation = Round.roundTo(p50deviation, 0.001)
p50BGI = Round.roundTo(p50BGI, 0.001)
adjustedISF = Round.roundTo(adjustedISF, 0.001)
log("p50deviation: $p50deviation p50BGI $p50BGI p50ratios: $p50ratios Old isf: $isf fullNewISF: $fullNewISF adjustedISF: $adjustedISF newISF: $newISF")
if (newISF != 0.0) {
isf = newISF
}
previousAutotune.from = preppedGlucose.from
previousAutotune.basal = basalProfile
previousAutotune.isf = isf
previousAutotune.ic = Round.roundTo(carbRatio, 0.001)
previousAutotune.basalUntuned = basalUntuned
previousAutotune.dia = newDia
previousAutotune.peak = newPeak
val localInsulin = LocalInsulin("Ins_$newPeak-$newDia", newPeak, newDia)
previousAutotune.localInsulin = localInsulin
previousAutotune.updateProfile()
return previousAutotune
}
private fun log(message: String) {
autotuneFS.atLog("[Core] $message")
}
} | agpl-3.0 | 793626f6acd32e60669a462f0163fb3a | 49.343023 | 301 | 0.580536 | 4.125139 | false | false | false | false |
digital-dreamer/lighthouse | client/src/main/java/lighthouse/controls/ReadMorePane.kt | 1 | 4920 | package lighthouse.controls
import javafx.scene.control.Label
import javafx.scene.layout.HBox
import javafx.geometry.Pos
import javafx.scene.shape.Rectangle
import javafx.animation.Timeline
import javafx.animation.KeyFrame
import javafx.util.Duration
import javafx.animation.KeyValue
import javafx.beans.value.WritableValue
import lighthouse.utils.easing.ElasticInterpolator
import javafx.animation.Interpolator
import javafx.scene.layout.Region
import javafx.application.Platform
import javafx.beans.InvalidationListener
import javafx.beans.Observable
import javafx.scene.layout.StackPane
/**
* Control that wraps another control and hides most of it until the Read more ... link is clicked, when it animates
* itself into the right size.
*/
[suppress("UNCHECKED_CAST")] // Hack around Kotlin compiler bug
public class ReadMorePane() : StackPane() {
{
setMinHeight(65.0)
getChildren().addListener(object : InvalidationListener {
override fun invalidated(observable: Observable?) {
getChildren().removeListener(this)
// Wait for a layout pass to have happened so we can query the wrapped height.
// This is ugly! We should really figure out how to do this without waiting.
Platform.runLater {
val wrappedNode = getChildren()[0] as Region
if (wrappedNode.getHeight() < getPrefHeight()) {
setPrefHeight(wrappedNode.getHeight())
} else {
wrappedNode.setMinHeight(0.0)
val label = Label("Read more ...")
label.setStyle("-fx-text-fill: blue; -fx-cursor: hand")
val box = HBox(label)
box.setAlignment(Pos.BOTTOM_RIGHT)
box.setStyle("-fx-padding: 5px; -fx-background-color: linear-gradient(from 0% 0% to 0% 50%, #ffffff00, white)")
box.setMaxHeight(100.0)
StackPane.setAlignment(box, Pos.BOTTOM_RIGHT)
getChildren().add(box)
val clipRect = Rectangle()
clipRect.widthProperty() bind widthProperty()
clipRect.heightProperty() bind heightProperty()
wrappedNode.setClip(clipRect)
label.setOnMouseClicked {
it.consume()
// We must remove the clip to find this out. We cannot query it above because at that point we're not
// a part of the scene and have not done layout. Plus images may be loading async, etc.
wrappedNode.setClip(null)
val realHeight = wrappedNode.getBoundsInLocal().getHeight()
wrappedNode.setClip(clipRect)
val readMoreClip = Rectangle()
readMoreClip.widthProperty() bind widthProperty()
readMoreClip.setHeight(box.getHeight())
clipRect.heightProperty().unbind()
Timeline(
KeyFrame(
Duration.seconds(0.15),
KeyValue(box.translateXProperty() as WritableValue<Any?>, 5.0, Interpolator.EASE_OUT),
KeyValue(box.opacityProperty() as WritableValue<Any?>, 0.0)
)
).play()
val interp = ElasticInterpolator()
val timeline = Timeline(
KeyFrame(
Duration.seconds(1.5),
KeyValue(minHeightProperty() as WritableValue<Any?>, realHeight, interp),
KeyValue(maxHeightProperty() as WritableValue<Any?>, realHeight, interp),
KeyValue(clipRect.heightProperty() as WritableValue<Any?>, realHeight, interp),
KeyValue(box.minHeightProperty() as WritableValue<Any?>, 0),
KeyValue(box.maxHeightProperty() as WritableValue<Any?>, 0)
)
)
timeline.setDelay(Duration.seconds(0.1))
timeline.setOnFinished {
getChildren().remove(box)
wrappedNode.setClip(null)
}
timeline.play()
}
}
}
}
})
}
} | apache-2.0 | 98944c772463dc7560c5283d621ce757 | 48.707071 | 135 | 0.506301 | 5.84323 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt | 1 | 33802 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil
import com.intellij.codeInspection.*
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection
import com.intellij.codeInspection.ex.EntryPointsManager
import com.intellij.codeInspection.ex.EntryPointsManagerBase
import com.intellij.codeInspection.ex.EntryPointsManagerImpl
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.*
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.safeDelete.SafeDeleteHandler
import com.intellij.util.Processor
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle
import org.jetbrains.kotlin.idea.core.isInheritable
import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.findUsages.handlers.KotlinFindClassUsagesHandler
import org.jetbrains.kotlin.idea.intentions.isFinalizeMethod
import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction
import org.jetbrains.kotlin.idea.isMainFunction
import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.search.findScriptsWithUsages
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators
import org.jetbrains.kotlin.idea.search.projectScope
import org.jetbrains.kotlin.idea.search.usagesSearch.getClassNameForCompanionObject
import org.jetbrains.kotlin.idea.search.usagesSearch.isDataClassProperty
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.hasActualsFor
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JComponent
import javax.swing.JPanel
class UnusedSymbolInspection : AbstractKotlinInspection() {
companion object {
private val javaInspection = UnusedDeclarationInspection()
private val KOTLIN_ADDITIONAL_ANNOTATIONS = listOf("kotlin.test.*", "kotlin.js.JsExport")
private fun KtDeclaration.hasKotlinAdditionalAnnotation() =
this is KtNamedDeclaration && checkAnnotatedUsingPatterns(this, KOTLIN_ADDITIONAL_ANNOTATIONS)
fun isEntryPoint(declaration: KtNamedDeclaration): Boolean =
isEntryPoint(declaration, lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) })
private fun isEntryPoint(declaration: KtNamedDeclaration, isCheapEnough: Lazy<SearchCostResult>): Boolean {
if (declaration.hasKotlinAdditionalAnnotation()) return true
if (declaration is KtClass && declaration.declarations.any { it.hasKotlinAdditionalAnnotation() }) return true
// Some of the main-function-cases are covered by 'javaInspection.isEntryPoint(lightElement)' call
// but not all of them: light method for parameterless main still points to parameterless name
// that is not an actual entry point from Java language point of view
if (declaration.isMainFunction()) return true
val lightElement: PsiElement = when (declaration) {
is KtClassOrObject -> declaration.toLightClass()
is KtNamedFunction, is KtSecondaryConstructor -> LightClassUtil.getLightClassMethod(declaration as KtFunction)
is KtProperty, is KtParameter -> {
if (declaration is KtParameter && !declaration.hasValOrVar()) return false
// we may handle only annotation parameters so far
if (declaration is KtParameter && isAnnotationParameter(declaration)) {
val lightAnnotationMethods = LightClassUtil.getLightClassPropertyMethods(declaration).toList()
for (javaParameterPsi in lightAnnotationMethods) {
if (javaInspection.isEntryPoint(javaParameterPsi)) {
return true
}
}
}
// can't rely on light element, check annotation ourselves
val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase
return checkAnnotatedUsingPatterns(
declaration,
entryPointsManager.additionalAnnotations + entryPointsManager.ADDITIONAL_ANNOTATIONS
)
}
else -> return false
} ?: return false
if (isCheapEnough.value == TOO_MANY_OCCURRENCES) return false
return javaInspection.isEntryPoint(lightElement)
}
private fun isAnnotationParameter(parameter: KtParameter): Boolean {
val constructor = parameter.ownerFunction as? KtConstructor<*> ?: return false
return constructor.containingClassOrObject?.isAnnotation() ?: false
}
private fun isCheapEnoughToSearchUsages(declaration: KtNamedDeclaration): SearchCostResult {
val project = declaration.project
val psiSearchHelper = PsiSearchHelper.getInstance(project)
if (!findScriptsWithUsages(declaration) { DefaultScriptingSupport.getInstance(project).isLoadedFromCache(it) }) {
// Not all script configuration are loaded; behave like it is used
return TOO_MANY_OCCURRENCES
}
val useScope = psiSearchHelper.getUseScope(declaration)
if (useScope is GlobalSearchScope) {
var zeroOccurrences = true
val list = listOf(declaration.name) + declarationAccessorNames(declaration) +
listOfNotNull(declaration.getClassNameForCompanionObject())
for (name in list) {
if (name == null) continue
when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) {
ZERO_OCCURRENCES -> {
} // go on, check other names
FEW_OCCURRENCES -> zeroOccurrences = false
TOO_MANY_OCCURRENCES -> return TOO_MANY_OCCURRENCES // searching usages is too expensive; behave like it is used
}
}
if (zeroOccurrences) return ZERO_OCCURRENCES
}
return FEW_OCCURRENCES
}
/**
* returns list of declaration accessor names e.g. pair of getter/setter for property declaration
*
* note: could be more than declaration.getAccessorNames()
* as declaration.getAccessorNames() relies on LightClasses and therefore some of them could be not available
* (as not accessible outside of class)
*
* e.g.: private setter w/o body is not visible outside of class and could not be used
*/
private fun declarationAccessorNames(declaration: KtNamedDeclaration): List<String> =
when (declaration) {
is KtProperty -> listOfPropertyAccessorNames(declaration)
is KtParameter -> listOfParameterAccessorNames(declaration)
else -> emptyList()
}
fun listOfParameterAccessorNames(parameter: KtParameter): List<String> {
val accessors = mutableListOf<String>()
if (parameter.hasValOrVar()) {
parameter.name?.let {
accessors.add(JvmAbi.getterName(it))
if (parameter.isVarArg)
accessors.add(JvmAbi.setterName(it))
}
}
return accessors
}
fun listOfPropertyAccessorNames(property: KtProperty): List<String> {
val accessors = mutableListOf<String>()
val propertyName = property.name ?: return accessors
accessors.add(property.getter?.let { getCustomAccessorName(it) } ?: JvmAbi.getterName(propertyName))
if (property.isVar)
accessors.add(property.setter?.let { getCustomAccessorName(it) } ?: JvmAbi.setterName(propertyName))
return accessors
}
/*
If the property has 'JvmName' annotation at accessor it should be used instead
*/
private fun getCustomAccessorName(method: KtPropertyAccessor?): String? {
val customJvmNameAnnotation =
method?.annotationEntries?.firstOrNull { it.shortName?.asString() == "JvmName" } ?: return null
return customJvmNameAnnotation.findDescendantOfType<KtStringTemplateEntry>()?.text
}
private fun KtProperty.isSerializationImplicitlyUsedField(): Boolean {
val ownerObject = getNonStrictParentOfType<KtClassOrObject>()
if (ownerObject is KtObjectDeclaration && ownerObject.isCompanion()) {
val lightClass = ownerObject.getNonStrictParentOfType<KtClass>()?.toLightClass() ?: return false
return lightClass.fields.any { it.name == name && HighlightUtil.isSerializationImplicitlyUsedField(it) }
}
return false
}
private fun KtNamedFunction.isSerializationImplicitlyUsedMethod(): Boolean =
toLightMethods().any { JavaHighlightUtil.isSerializationRelatedMethod(it, it.containingClass) }
// variation of IDEA's AnnotationUtil.checkAnnotatedUsingPatterns()
fun checkAnnotatedUsingPatterns(
declaration: KtNamedDeclaration,
annotationPatterns: Collection<String>
): Boolean {
if (declaration.annotationEntries.isEmpty()) return false
val context = declaration.analyze()
val annotationsPresent = declaration.annotationEntries.mapNotNull {
context[BindingContext.ANNOTATION, it]?.fqName?.asString()
}
if (annotationsPresent.isEmpty()) return false
for (pattern in annotationPatterns) {
val hasAnnotation = if (pattern.endsWith(".*")) {
annotationsPresent.any { it.startsWith(pattern.dropLast(1)) }
} else {
pattern in annotationsPresent
}
if (hasAnnotation) return true
}
return false
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return namedDeclarationVisitor(fun(declaration) {
ProgressManager.checkCanceled()
val message = declaration.describe()?.let { KotlinIdeaCompletionBundle.message("inspection.message.never.used", it) } ?: return
if (!RootKindFilter.projectSources.matches(declaration)) return
// Simple PSI-based checks
if (declaration is KtObjectDeclaration && declaration.isCompanion()) return // never mark companion object as unused (there are too many reasons it can be needed for)
if (declaration is KtSecondaryConstructor && declaration.containingClass()?.isEnum() == true) return
if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return
if (declaration is KtProperty && declaration.isLocal) return
if (declaration is KtParameter &&
(declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar())
) return
// More expensive, resolve-based checks
val descriptor = declaration.resolveToDescriptorIfAny() ?: return
if (declaration.languageVersionSettings.explicitApiEnabled
&& (descriptor as? DeclarationDescriptorWithVisibility)?.isEffectivelyPublicApi == true) {
return
}
if (descriptor is FunctionDescriptor && descriptor.isOperator) return
val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) {
isCheapEnoughToSearchUsages(declaration)
}
if (isEntryPoint(declaration, isCheapEnough)) return
if (declaration.isFinalizeMethod(descriptor)) return
if (declaration is KtProperty && declaration.isSerializationImplicitlyUsedField()) return
if (declaration is KtNamedFunction && declaration.isSerializationImplicitlyUsedMethod()) return
// properties can be referred by component1/component2, which is too expensive to search, don't mark them as unused
if (declaration is KtParameter && (declaration.isDataClassProperty() || declaration.isInlineClassProperty())) return
// experimental annotations
if (descriptor is ClassDescriptor && descriptor.kind == ClassKind.ANNOTATION_CLASS) {
val fqName = descriptor.fqNameSafe.asString()
val languageVersionSettings = declaration.languageVersionSettings
if (fqName in languageVersionSettings.getFlag(AnalysisFlags.optIn)) return
}
// Main checks: finding reference usages && text usages
if (hasNonTrivialUsages(declaration, isCheapEnough, descriptor)) return
if (declaration is KtClassOrObject && classOrObjectHasTextUsages(declaration)) return
val psiElement = declaration.nameIdentifier ?: (declaration as? KtConstructor<*>)?.getConstructorKeyword() ?: return
val problemDescriptor = holder.manager.createProblemDescriptor(
psiElement,
null,
message,
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
true,
*createQuickFixes(declaration).toTypedArray()
)
holder.registerProblem(problemDescriptor)
})
}
private fun classOrObjectHasTextUsages(classOrObject: KtClassOrObject): Boolean {
var hasTextUsages = false
// Finding text usages
if (classOrObject.useScope is GlobalSearchScope) {
val findClassUsagesHandler = KotlinFindClassUsagesHandler(classOrObject, KotlinFindUsagesHandlerFactory(classOrObject.project))
findClassUsagesHandler.processUsagesInText(
classOrObject,
{ hasTextUsages = true; false },
GlobalSearchScope.projectScope(classOrObject.project)
)
}
return hasTextUsages
}
private fun hasNonTrivialUsages(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor? = null): Boolean {
val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) }
return hasNonTrivialUsages(declaration, isCheapEnough, descriptor)
}
private fun hasNonTrivialUsages(
declaration: KtNamedDeclaration,
enoughToSearchUsages: Lazy<SearchCostResult>,
descriptor: DeclarationDescriptor? = null
): Boolean {
val project = declaration.project
val psiSearchHelper = PsiSearchHelper.getInstance(project)
val useScope = psiSearchHelper.getUseScope(declaration)
val restrictedScope = if (useScope is GlobalSearchScope) {
val zeroOccurrences = when (enoughToSearchUsages.value) {
ZERO_OCCURRENCES -> true
FEW_OCCURRENCES -> false
TOO_MANY_OCCURRENCES -> return true // searching usages is too expensive; behave like it is used
}
if (zeroOccurrences && !declaration.hasActualModifier()) {
if (declaration is KtObjectDeclaration && declaration.isCompanion()) {
// go on: companion object can be used only in containing class
} else {
return false
}
}
if (declaration.hasActualModifier()) {
KotlinSourceFilterScope.projectSources(project.projectScope(), project)
} else {
KotlinSourceFilterScope.projectSources(useScope, project)
}
} else useScope
if (declaration is KtTypeParameter) {
val containingClass = declaration.containingClass()
if (containingClass != null) {
val isOpenClass = containingClass.isInterface()
|| containingClass.hasModifier(KtTokens.ABSTRACT_KEYWORD)
|| containingClass.hasModifier(KtTokens.SEALED_KEYWORD)
|| containingClass.hasModifier(KtTokens.OPEN_KEYWORD)
if (isOpenClass && hasOverrides(containingClass, restrictedScope)) return true
val containingClassSearchScope = GlobalSearchScope.projectScope(project)
val isRequiredToCallFunction =
ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, containingClassSearchScope)).any { ref ->
val userType = ref.element.parent as? KtUserType ?: return@any false
val typeArguments = userType.typeArguments
if (typeArguments.isEmpty()) return@any false
val parameter = userType.getStrictParentOfType<KtParameter>() ?: return@any false
val callableDeclaration = parameter.getStrictParentOfType<KtCallableDeclaration>()?.let {
if (it !is KtNamedFunction) it.containingClass() else it
} ?: return@any false
val typeParameters = callableDeclaration.typeParameters.map { it.name }
if (typeParameters.isEmpty()) return@any false
if (typeArguments.none { it.text in typeParameters }) return@any false
ReferencesSearch.search(KotlinReferencesSearchParameters(callableDeclaration, containingClassSearchScope)).any {
val callElement = it.element.parent as? KtCallElement
callElement != null && callElement.typeArgumentList == null
}
}
if (isRequiredToCallFunction) return true
}
}
return (declaration is KtObjectDeclaration && declaration.isCompanion() &&
declaration.body?.declarations?.isNotEmpty() == true) ||
hasReferences(declaration, descriptor, restrictedScope) ||
hasOverrides(declaration, restrictedScope) ||
hasFakeOverrides(declaration, restrictedScope) ||
hasPlatformImplementations(declaration, descriptor)
}
private fun checkDeclaration(declaration: KtNamedDeclaration, importedDeclaration: KtNamedDeclaration): Boolean =
declaration !in importedDeclaration.parentsWithSelf && !hasNonTrivialUsages(importedDeclaration)
private val KtNamedDeclaration.isObjectOrEnum: Boolean get() = this is KtObjectDeclaration || this is KtClass && isEnum()
private fun checkReference(ref: PsiReference, declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
ProgressManager.checkCanceled()
if (declaration.isAncestor(ref.element)) return true // usages inside element's declaration are not counted
if (ref.element.parent is KtValueArgumentName) return true // usage of parameter in form of named argument is not counted
val import = ref.element.getParentOfType<KtImportDirective>(false)
if (import != null) {
if (import.aliasName != null && import.aliasName != declaration.name) {
return false
}
// check if we import member(s) from object / nested object / enum and search for their usages
val originalDeclaration = (descriptor as? TypeAliasDescriptor)?.classDescriptor?.findPsi() as? KtNamedDeclaration
if (declaration is KtClassOrObject || originalDeclaration is KtClassOrObject) {
if (import.isAllUnder) {
val importedFrom = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve()
as? KtClassOrObject ?: return true
return importedFrom.declarations.none { it is KtNamedDeclaration && hasNonTrivialUsages(it) }
} else {
if (import.importedFqName != declaration.fqName) {
val importedDeclaration =
import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtNamedDeclaration
?: return true
if (declaration.isObjectOrEnum || importedDeclaration.containingClassOrObject is KtObjectDeclaration) return checkDeclaration(
declaration,
importedDeclaration
)
if (originalDeclaration?.isObjectOrEnum == true) return checkDeclaration(
originalDeclaration,
importedDeclaration
)
// check type alias
if (importedDeclaration.fqName == declaration.fqName) return true
}
}
}
return true
}
return false
}
private fun hasReferences(
declaration: KtNamedDeclaration,
descriptor: DeclarationDescriptor?,
useScope: SearchScope
): Boolean {
fun checkReference(ref: PsiReference): Boolean = checkReference(ref, declaration, descriptor)
val searchOptions = KotlinReferencesSearchOptions(acceptCallableOverrides = declaration.hasActualModifier())
val searchParameters = KotlinReferencesSearchParameters(
declaration,
useScope,
kotlinOptions = searchOptions
)
val referenceUsed: Boolean by lazy { !ReferencesSearch.search(searchParameters).forEach(Processor { checkReference(it) }) }
if (descriptor is FunctionDescriptor && DescriptorUtils.findJvmNameAnnotation(descriptor) != null) {
if (referenceUsed) return true
}
if (declaration is KtSecondaryConstructor) {
val containingClass = declaration.containingClass()
if (containingClass != null && ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, useScope)).any {
it.element.getStrictParentOfType<KtTypeAlias>() != null
}) return true
}
if (declaration is KtCallableDeclaration && declaration.canBeHandledByLightMethods(descriptor)) {
val lightMethods = declaration.toLightMethods()
if (lightMethods.isNotEmpty()) {
val lightMethodsUsed = lightMethods.any { method ->
!MethodReferencesSearch.search(method).forEach(Processor { checkReference(it) })
}
if (lightMethodsUsed) return true
if (!declaration.hasActualModifier()) return false
}
}
if (declaration is KtEnumEntry) {
val enumClass = declaration.containingClass()?.takeIf { it.isEnum() }
if (hasBuiltInEnumFunctionReference(enumClass, useScope)) return true
}
return referenceUsed || checkPrivateDeclaration(declaration, descriptor)
}
private fun hasBuiltInEnumFunctionReference(enumClass: KtClass?, useScope: SearchScope): Boolean {
if (enumClass == null) return false
return enumClass.anyDescendantOfType(KtExpression::isReferenceToBuiltInEnumFunction) ||
ReferencesSearch.search(KotlinReferencesSearchParameters(enumClass, useScope)).any(::hasBuiltInEnumFunctionReference)
}
private fun hasBuiltInEnumFunctionReference(reference: PsiReference): Boolean {
val parent = reference.element.getParentOfTypes(
true,
KtTypeReference::class.java,
KtQualifiedExpression::class.java,
KtCallableReferenceExpression::class.java
) ?: return false
return parent.isReferenceToBuiltInEnumFunction()
}
private fun checkPrivateDeclaration(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
if (descriptor == null || !declaration.isPrivateNestedClassOrObject) return false
val set = hashSetOf<KtSimpleNameExpression>()
declaration.containingKtFile.importList?.acceptChildren(simpleNameExpressionRecursiveVisitor {
set += it
})
return set.mapNotNull { it.referenceExpression() }
.filter { descriptor in it.resolveMainReferenceToDescriptors() }
.any { !checkReference(it.mainReference, declaration, descriptor) }
}
private fun KtCallableDeclaration.canBeHandledByLightMethods(descriptor: DeclarationDescriptor?): Boolean {
return when {
descriptor is ConstructorDescriptor -> {
val classDescriptor = descriptor.constructedClass
!classDescriptor.isInlineClass() && classDescriptor.visibility != DescriptorVisibilities.LOCAL
}
hasModifier(KtTokens.INTERNAL_KEYWORD) -> false
descriptor !is FunctionDescriptor -> true
else -> !descriptor.hasInlineClassParameters()
}
}
private fun FunctionDescriptor.hasInlineClassParameters(): Boolean {
return when {
dispatchReceiverParameter?.type?.isInlineClassType() == true -> true
extensionReceiverParameter?.type?.isInlineClassType() == true -> true
else -> valueParameters.any { it.type.isInlineClassType() }
}
}
private fun hasOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean =
DefinitionsScopedSearch.search(declaration, useScope).findFirst() != null
private fun hasFakeOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean {
val ownerClass = declaration.containingClassOrObject as? KtClass ?: return false
if (!ownerClass.isInheritable()) return false
val descriptor = declaration.toDescriptor() as? CallableMemberDescriptor ?: return false
if (descriptor.modality == Modality.ABSTRACT) return false
val lightMethods = declaration.toLightMethods()
return DefinitionsScopedSearch.search(ownerClass, useScope).any { element: PsiElement ->
when (element) {
is KtLightClass -> {
val memberBySignature =
(element.kotlinOrigin?.toDescriptor() as? ClassDescriptor)?.findCallableMemberBySignature(descriptor)
memberBySignature != null &&
!memberBySignature.kind.isReal &&
memberBySignature.overriddenDescriptors.any { it != descriptor }
}
is PsiClass ->
lightMethods.any { lightMethod ->
val sameMethods = element.findMethodsBySignature(lightMethod, true)
sameMethods.all { it.containingClass != element } &&
sameMethods.any { it.containingClass != lightMethod.containingClass }
}
else ->
false
}
}
}
private fun hasPlatformImplementations(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
if (!declaration.hasExpectModifier()) return false
if (descriptor !is MemberDescriptor) return false
val commonModuleDescriptor = declaration.containingKtFile.findModuleDescriptor()
// TODO: Check if 'allImplementingDescriptors' should be used instead!
return commonModuleDescriptor.implementingDescriptors.any { it.hasActualsFor(descriptor) } ||
commonModuleDescriptor.hasActualsFor(descriptor)
}
override fun createOptionsPanel(): JComponent = JPanel(GridBagLayout()).apply {
add(
EntryPointsManagerImpl.createConfigureAnnotationsButton(),
GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0)
)
}
private fun createQuickFixes(declaration: KtNamedDeclaration): List<LocalQuickFix> {
val list = ArrayList<LocalQuickFix>()
list.add(SafeDeleteFix(declaration))
for (annotationEntry in declaration.annotationEntries) {
val resolvedName = annotationEntry.resolveToDescriptorIfAny() ?: continue
val fqName = resolvedName.fqName?.asString() ?: continue
// checks taken from com.intellij.codeInspection.util.SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes
if (fqName.startsWith("kotlin.")
|| fqName.startsWith("java.")
|| fqName.startsWith("javax.")
|| fqName.startsWith("org.jetbrains.annotations.")
)
continue
val intentionAction = createAddToDependencyInjectionAnnotationsFix(declaration.project, fqName)
list.add(IntentionWrapper(intentionAction))
}
return list
}
private fun KtParameter.isInlineClassProperty(): Boolean {
if (!hasValOrVar()) return false
return containingClassOrObject?.hasModifier(KtTokens.INLINE_KEYWORD) == true ||
containingClassOrObject?.hasModifier(KtTokens.VALUE_KEYWORD) == true
}
}
class SafeDeleteFix(declaration: KtDeclaration) : LocalQuickFix {
@Nls
private val name: String =
if (declaration is KtConstructor<*>) KotlinBundle.message("safe.delete.constructor")
else QuickFixBundle.message("safe.delete.text", declaration.name)
override fun getName() = name
override fun getFamilyName() = QuickFixBundle.message("safe.delete.family")
override fun startInWriteAction(): Boolean = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val declaration = descriptor.psiElement.getStrictParentOfType<KtDeclaration>() ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(declaration.containingFile)) return
if (declaration is KtParameter && declaration.parent is KtParameterList && declaration.parent?.parent is KtFunction) {
RemoveUnusedFunctionParameterFix(declaration).invoke(project, declaration.findExistingEditor(), declaration.containingKtFile)
} else {
val declarationPointer = declaration.createSmartPointer()
invokeLater {
declarationPointer.element?.let { safeDelete(project, it) }
}
}
}
}
private fun safeDelete(project: Project, declaration: PsiElement) {
SafeDeleteHandler.invoke(project, arrayOf(declaration), false)
}
| apache-2.0 | 2fa6c20434f30f1a86b1029ce0761011 | 50.449011 | 178 | 0.673392 | 6.07731 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/ndarray/DenseNDArraySpec.kt | 1 | 60756 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package ndarray
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.RandomGenerator
import com.kotlinnlp.simplednn.simplemath.concatVectorsV
import com.kotlinnlp.simplednn.simplemath.equals
import com.kotlinnlp.simplednn.simplemath.exp
import com.kotlinnlp.simplednn.simplemath.ndarray.Indices
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayMask
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.SparseEntry
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArrayFactory
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.*
/**
*
*/
class DenseNDArraySpec : Spek({
describe("a DenseNDArray") {
context("class factory methods") {
context("arrayOf()") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
it("should have the expected length") {
assertEquals(4, array.length)
}
it("should have the expected last index") {
assertEquals(3, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(4, array.rows)
}
it("should have the expected number of columns") {
assertEquals(1, array.columns)
}
it("should contain the expected value at index 0") {
assertEquals(0.1, array[0])
}
it("should contain the expected value at index 1") {
assertEquals(0.2, array[1])
}
it("should contain the expected value at index 2") {
assertEquals(0.3, array[2])
}
it("should contain the expected value at index 3") {
assertEquals(0.0, array[3])
}
}
context("fromRows()") {
val matrix = DenseNDArrayFactory.fromRows(listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, 0.6))
))
it("should have the expected shape") {
assertEquals(Shape(3, 2), matrix.shape)
}
it("should have the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2),
doubleArrayOf(0.3, 0.4),
doubleArrayOf(0.5, 0.6)
)).equals(matrix, tolerance = 0.001)
}
}
it("should raise an exception if the shapes are not compatible") {
assertFailsWith<IllegalArgumentException> {
DenseNDArrayFactory.fromRows(listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, 0.8, 0.9))
))
}
}
}
context("fromColumns()") {
val matrix = DenseNDArrayFactory.fromColumns(listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, 0.6))
))
it("should have the expected shape") {
assertEquals(Shape(2, 3), matrix.shape)
}
it("should have the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.3, 0.5),
doubleArrayOf(0.2, 0.4, 0.6)
)).equals(matrix, tolerance = 0.001)
}
}
it("should raise an exception if the shapes are not compatible") {
assertFailsWith<IllegalArgumentException> {
DenseNDArrayFactory.fromColumns(listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, 0.8, 0.9))
))
}
}
}
context("zeros()") {
val array = DenseNDArrayFactory.zeros(Shape(2, 3))
it("should have the expected length") {
assertEquals(6, array.length)
}
it("should have the expected last index") {
assertEquals(5, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(2, array.rows)
}
it("should have the expected number of columns") {
assertEquals(3, array.columns)
}
it("should be filled with zeros") {
(0 until array.length).forEach { assertEquals(0.0, array[it]) }
}
}
context("ones()") {
val array = DenseNDArrayFactory.ones(Shape(2, 3))
it("should have the expected length") {
assertEquals(6, array.length)
}
it("should have the expected last index") {
assertEquals(5, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(2, array.rows)
}
it("should have the expected number of columns") {
assertEquals(3, array.columns)
}
it("should be filled with ones") {
(0 until array.length).forEach { assertEquals(1.0, array[it]) }
}
}
context("eye()") {
val array = DenseNDArrayFactory.eye(4)
it("should have the expected length") {
assertEquals(16, array.length)
}
it("should have the expected last index") {
assertEquals(15, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(4, array.rows)
}
it("should have the expected number of columns") {
assertEquals(4, array.columns)
}
it("should be filled with the expected values") {
assertTrue {
(0 until array.rows).all { i ->
(0 until array.columns).all { j ->
if (i == j) array[i, j] == 1.0 else array[i, j] == 0.0
}
}
}
}
}
context("fill()") {
val array = DenseNDArrayFactory.fill(shape = Shape(2, 3), value = 0.35)
it("should have the expected length") {
assertEquals(6, array.length)
}
it("should have the expected last index") {
assertEquals(5, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(2, array.rows)
}
it("should have the expected number of columns") {
assertEquals(3, array.columns)
}
it("should be filled with the expected value") {
(0 until array.length).forEach { assertEquals(0.35, array[it]) }
}
}
context("emptyArray()") {
val array = DenseNDArrayFactory.emptyArray(Shape(3, 2))
it("should have the expected length") {
assertEquals(6, array.length)
}
it("should have the expected last index") {
assertEquals(5, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(3, array.rows)
}
it("should have the expected number of columns") {
assertEquals(2, array.columns)
}
}
context("oneHotEncoder()") {
val array = DenseNDArrayFactory.oneHotEncoder(length = 4, oneAt = 2)
it("should have the expected length") {
assertEquals(4, array.length)
}
it("should have the expected last index") {
assertEquals(3, array.lastIndex)
}
it("should have the expected length") {
assertEquals(4, array.length)
}
it("should be a column vector") {
assertEquals(1, array.columns)
}
it("should have the expected values") {
assertTrue { DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 1.0, 0.0)).equals(array) }
}
}
context("random()") {
val array = DenseNDArrayFactory.random(shape = Shape(216, 648), from = 0.5, to = 0.89)
it("should have the expected length") {
assertEquals(139968, array.length)
}
it("should have the expected last index") {
assertEquals(139967, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(216, array.rows)
}
it("should have the expected number of columns") {
assertEquals(648, array.columns)
}
it("should contain values within the expected range") {
(0 until array.length).forEach { i ->
val value = array[i]
assertTrue { value >= 0.5 && value < 0.89 }
}
}
}
context("exp()") {
val power = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2),
doubleArrayOf(0.3, 0.0)
))
val array = exp(power)
it("should have the expected length") {
assertEquals(4, array.length)
}
it("should have the expected last index") {
assertEquals(3, array.lastIndex)
}
it("should have the expected number of rows") {
assertEquals(2, array.rows)
}
it("should have the expected number of columns") {
assertEquals(2, array.columns)
}
it("should contain the expected value at index 0") {
assertTrue { equals(1.105171, array[0, 0], tolerance = 1.0e-06) }
}
it("should contain the expected value at index 1") {
assertTrue { equals(1.221403, array[0, 1], tolerance = 1.0e-06) }
}
it("should contain the expected value at index 2") {
assertTrue { equals(1.349859, array[1, 0], tolerance = 1.0e-06) }
}
it("should contain the expected value at index 3") {
assertTrue { equals(1.0, array[1, 1], tolerance = 1.0e-06) }
}
}
}
context("equality with tolerance") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.123, 0.234, 0.345, 0.012))
context("comparison with different types") {
val arrayToCompare = SparseNDArrayFactory.arrayOf(
activeIndicesValues = arrayOf(
SparseEntry(Indices(0, 0), 0.123),
SparseEntry(Indices(1, 0), 0.234),
SparseEntry(Indices(2, 0), 0.345),
SparseEntry(Indices(3, 0), 0.012)
),
shape = Shape(4))
it("should return false") {
assertFalse { array.equals(arrayToCompare, tolerance = 1.0e0-3) }
}
}
context("comparison within the tolerance") {
val arrayToCompare = DenseNDArrayFactory.arrayOf(
doubleArrayOf(0.123000001, 0.234000001, 0.345000001, 0.012000001))
it("should result equal with a large tolerance") {
assertTrue { array.equals(arrayToCompare, tolerance=1.0e-03) }
}
it("should result equal with a strict tolerance") {
assertTrue { array.equals(arrayToCompare, tolerance=1.0e-08) }
}
}
context("comparison out of tolerance") {
val arrayToCompare = DenseNDArrayFactory.arrayOf(
doubleArrayOf(0.12303, 0.23403, 0.34503, 0.01203))
it("should result not equal") {
assertFalse { array.equals(arrayToCompare, tolerance=1.0e-05) }
}
}
}
context("initialization through a double array of 4 elements") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
context("properties") {
it("should be a vector") {
assertTrue { array.isVector }
}
it("should not be a matrix") {
assertFalse { array.isMatrix }
}
it("should have the expected length") {
assertEquals(4, array.length)
}
it("should have the expected number of rows") {
assertEquals(4, array.rows)
}
it("should have the expected number of columns") {
assertEquals(1, array.columns)
}
it("should have the expected shape") {
assertEquals(Shape(4), array.shape)
}
}
context("generic methods") {
it("should be equal to itself") {
assertTrue { array.equals(array) }
}
it("should be equal to its copy") {
assertTrue { array.equals(array.copy()) }
}
}
context("getRange() method") {
val a = array.getRange(0, 3)
val b = array.getRange(2, 4)
it("should return a range of the expected length") {
assertEquals(3, a.length)
}
it("should return the expected range (0, 3)") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3)).equals(a)
}
}
it("should return the expected range (2, 4)") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.0)).equals(b)
}
}
it("should raise an IndexOutOfBoundsException requesting for a range out of bounds") {
assertFailsWith<IndexOutOfBoundsException> {
array.getRange(2, 6)
}
}
}
context("transpose") {
val transposedArray = array.t
it("should give a transposed array with the expected shape") {
assertEquals(Shape(1, 4), transposedArray.shape)
}
it("should give a transposed array with the expected values") {
assertEquals(transposedArray[2], 0.3)
}
}
}
context("isOneHotEncoder() method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val oneHotEncoder = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 1.0, 0.0))
val oneHotEncoderDouble = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 1.0, 1.0, 0.0))
val oneHotEncoderFake = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.1, 0.0, 0.0))
val array2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.1, 0.2, 0.3, 0.0)
))
it("should return false on a random array") {
assertFalse { array.isOneHotEncoder }
}
it("should return false on a 2-dim array") {
assertFalse { array2.isOneHotEncoder }
}
it("should return false on an array with one element equal to 0.1") {
assertFalse { oneHotEncoderFake.isOneHotEncoder }
}
it("should return false on an array with two elements equal to 1.0") {
assertFalse { oneHotEncoderDouble.isOneHotEncoder }
}
it("should return true on an array with one element equal to 1.0") {
assertTrue { oneHotEncoder.isOneHotEncoder }
}
}
context("math methods returning a new NDArray") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val a = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.3, 0.5, 0.7))
val n = 0.9
context("sum(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.0, 1.1, 1.2, 0.9))
val res = array.sum(n)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("sum(array) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, 0.5, 0.8, 0.7))
val res = array.sum(a)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("sumByRows(array) method") {
val matrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.4, 0.5, 0.7, 0.9)
))
val expectedRes = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.4, 0.6, 0.0),
doubleArrayOf(0.5, 0.7, 1.0, 0.9)
))
val res = matrix.sumByRows(array)
it("should return a new DenseNDArray") {
assertFalse { matrix === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedRes, tolerance = 1.0e-04) }
}
}
context("sumByColumns(array) method") {
val sumArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2))
val matrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.4, 0.5, 0.7, 0.9)
))
val expectedRes = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.3, 0.4, 0.1),
doubleArrayOf(0.6, 0.7, 0.9, 1.1)
))
val res = matrix.sumByColumns(sumArray)
it("should return a new DenseNDArray") {
assertFalse { matrix === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedRes, tolerance = 1.0e-04) }
}
}
context("sub(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.7, -0.6, -0.9))
val res = array.sub(n)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("sub(array) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.3, -0.1, -0.2, -0.7))
val res = array.sub(a)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should assign the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("reverseSub(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.8, 0.7, 0.6, 0.9))
val res = array.reverseSub(n)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("dot(array) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.04, 0.03, 0.05, 0.07),
doubleArrayOf(0.08, 0.06, 0.1, 0.14),
doubleArrayOf(0.12, 0.09, 0.15, 0.21),
doubleArrayOf(0.0, 0.0, 0.0, 0.0)
))
val res = array.dot(a.t)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should throw an error with not compatible shapes") {
assertFails { array.dot(a) }
}
it("should assign the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("dotLeftMasked(array, mask) method") {
val a1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val a2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.9),
doubleArrayOf(0.5, 0.6)
))
val expected = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.45),
doubleArrayOf(0.25, 0.3),
doubleArrayOf(0.0, 0.0)
))
val res = a1.dotLeftMasked(a2, mask = NDArrayMask(dim1 = intArrayOf(0, 1), dim2 = intArrayOf(0, 1)))
it("should throw an error with not compatible shapes") {
val a3 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(a1, a3) }
}
it("should assign the expected values") {
assertTrue { expected.equals(res, tolerance = 1.0e-04) }
}
}
context("dotRightMasked(array, mask) method") {
val a1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val a2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.9),
doubleArrayOf(0.5, 0.6)
))
val expected = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.18),
doubleArrayOf(0.2, 0.3),
doubleArrayOf(0.14, 0.36)
))
val res = a1.dotRightMasked(a2, mask = NDArrayMask(dim1 = intArrayOf(0, 1), dim2 = intArrayOf(0, 1)))
it("should throw an error with not compatible shapes") {
val a3 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(a1, a3) }
}
it("should assign the expected values") {
assertTrue { expected.equals(res, tolerance = 1.0e-04) }
}
}
context("prod(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.09, 0.18, 0.27, 0.0))
val res = array.prod(n)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("prod(array) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.04, 0.06, 0.15, 0.0))
val res = array.prod(a)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("matrix.prod(colVector) method") {
val matrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.4, 0.5, 0.7, 0.9)
))
val colVector = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2, 0.3))
val expectedMatrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.02, 0.04, 0.06, 0.0),
doubleArrayOf(0.12, 0.15, 0.21, 0.27)
))
val res = matrix.prod(colVector)
it("should return a new DenseNDArray") {
assertFalse { matrix === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedMatrix, tolerance = 1.0e-04) }
}
}
context("div(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1111, 0.2222, 0.3333, 0.0))
val res = array.div(n)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("div(array) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.25, 0.6667, 0.6, 0.0))
val res = array.div(a)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("roundInt(threshold) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 1.0, 1.0, 0.0))
val res = array.roundInt(threshold = 0.2)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("avg() method") {
it("should return the expected average") {
assertTrue { equals(0.15, array.avg(), tolerance = 1.0e-08) }
}
}
context("sign() method") {
val signedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.1, 0.0, 0.7, -0.6))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-1.0, 0.0, 1.0, -1.0))
val res = signedArray.sign()
it("should return a new DenseNDArray") {
assertFalse { signedArray === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("nonZeroSign() method") {
val signedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.1, 0.0, 0.7, -0.6))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-1.0, 1.0, 1.0, -1.0))
val res = signedArray.nonZeroSign()
it("should return a new DenseNDArray") {
assertFalse { signedArray === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("sqrt() method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3162, 0.4472, 0.5478, 0.0))
val res = array.sqrt()
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("pow(number) method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2399, 0.3687, 0.4740, 0.0))
val res = array.pow(0.62)
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("exp() method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.105171, 1.221403, 1.349859, 1.0))
val res = array.exp()
it("should return a new DenseNDArray") {
assertFalse { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("log10() method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.397940, -0.522879, -0.301030, -0.154902))
val res = a.log10()
it("should raise an exception if at least a value is 0.0") {
assertFailsWith<IllegalArgumentException> { array.log10() }
}
it("should return a new DenseNDArray with a valid array") {
assertFalse { a === res }
}
it("should return the expected values with a valid array") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-06) }
}
}
context("ln() method") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.916291, -1.203973, -0.693147, -0.356675))
val res = a.ln()
it("should raise an exception if at least a value is 0.0") {
assertFailsWith<IllegalArgumentException> { array.ln() }
}
it("should return a new DenseNDArray with a valid array") {
assertFalse { a === res }
}
it("should return the expected values with a valid array") {
assertTrue { res.equals(expectedArray, tolerance = 1.0e-06) }
}
}
}
context("math methods in-place") {
val a = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.3, 0.5, 0.7))
val b = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, 0.8, 0.1, 0.4))
val n = 0.9
context("assignSum(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.0, 1.1, 1.2, 0.9))
val res = array.assignSum(n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignSum(array, number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.3, 1.2, 1.4, 1.6))
val res = array.assignSum(a, n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignSum(array, array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.1, 1.1, 0.6, 1.1))
val res = array.assignSum(a, b)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignSumByRows(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val matrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.4, 0.5, 0.7, 0.9)
))
val expectedRes = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.4, 0.6, 0.0),
doubleArrayOf(0.5, 0.7, 1.0, 0.9)
))
val res = matrix.assignSumByRows(array)
it("should return the same DenseNDArray") {
assertTrue { matrix === res }
}
it("should assign the expected values") {
assertTrue { matrix.equals(expectedRes, tolerance = 1.0e-04) }
}
}
context("assignSumByColumns(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2))
val matrix = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.0),
doubleArrayOf(0.4, 0.5, 0.7, 0.9)
))
val expectedRes = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.3, 0.4, 0.1),
doubleArrayOf(0.6, 0.7, 0.9, 1.1)
))
val res = matrix.assignSumByColumns(array)
it("should return the same DenseNDArray") {
assertTrue { matrix === res }
}
it("should assign the expected values") {
assertTrue { matrix.equals(expectedRes, tolerance = 1.0e-04) }
}
}
context("assignSum(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, 0.5, 0.8, 0.7))
val res = array.assignSum(a)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignSub(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.7, -0.6, -0.9))
val res = array.assignSub(n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignSub(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.3, -0.1, -0.2, -0.7))
val res = array.assignSub(a)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDot(array, array[1-d]) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val a1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.28))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.112),
doubleArrayOf(0.084),
doubleArrayOf(0.14),
doubleArrayOf(0.196)
))
val res = array.assignDot(a, a1)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
assertFails { array.assignDot(a, b.t) }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDot(array, array[2-d]) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val v = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.8))
val m = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.61),
doubleArrayOf(0.25),
doubleArrayOf(0.49),
doubleArrayOf(0.61)
))
val res = array.assignDot(m, v)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
val m2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(a.t, m2) }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDotLeftMasked(array[1-d], array[2-d], mask) method") {
val array = DenseNDArrayFactory.emptyArray(Shape(1, 2))
val a1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.3, 0.6)
))
val m = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.3, 0.15)
))
val res = array.assignDotLeftMasked(a1, m, aMask = NDArrayMask(dim1 = intArrayOf(0), dim2 = intArrayOf(1)))
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
val m2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(a1, m2) }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDotLeftMasked(array[2-d], array[2-d], mask) method") {
val array = DenseNDArrayFactory.emptyArray(Shape(3, 2))
val m1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val m2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.9),
doubleArrayOf(0.5, 0.6)
))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.45),
doubleArrayOf(0.25, 0.3),
doubleArrayOf(0.0, 0.0)
))
val res = array.assignDotLeftMasked(m1, m2, aMask = NDArrayMask(dim1 = intArrayOf(0, 1), dim2 = intArrayOf(0, 1)))
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
val m3 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(m1, m3) }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDotRightMasked(array[1-d], array[2-d], mask) method") {
val array = DenseNDArrayFactory.emptyArray(Shape(1, 2))
val a1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.3, 0.6)
))
val m = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.35, 0.15)
))
val mask = NDArrayMask(dim1 = intArrayOf(0, 1), dim2 = intArrayOf(0, 1))
val res = array.assignDotRightMasked(a1, m, bMask = mask)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
val m2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(a1, m2) }
}
it("should assign the expected values") {
assertTrue { expectedArray.equals(array, tolerance = 1.0e-04) }
}
}
context("assignDotRightMasked(array[2-d], array[2-d], mask) method") {
val array = DenseNDArrayFactory.emptyArray(Shape(3, 2))
val m1 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.5, 0.3),
doubleArrayOf(1.0, 0.5),
doubleArrayOf(0.7, 0.6)
))
val m2 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.9),
doubleArrayOf(0.5, 0.6)
))
val expectedArray = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.18),
doubleArrayOf(0.2, 0.3),
doubleArrayOf(0.14, 0.36)
))
val mask = NDArrayMask(dim1 = intArrayOf(0, 1), dim2 = intArrayOf(0, 1))
val res = array.assignDotRightMasked(m1, m2, bMask = mask)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should throw an error with not compatible shapes") {
val m3 = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.7, 0.5),
doubleArrayOf(0.3, 0.2),
doubleArrayOf(0.3, 0.5),
doubleArrayOf(0.7, 0.5)
))
assertFails { array.assignDot(m1, m3) }
}
it("should assign the expected values") {
assertTrue { expectedArray.equals(array, tolerance = 1.0e-04) }
}
}
context("assignProd(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.09, 0.18, 0.27, 0.0))
val res = array.assignProd(n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignProd(array, number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.36, 0.27, 0.45, 0.63))
val res = array.assignProd(a, n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignProd(array, array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.28, 0.24, 0.05, 0.28))
val res = array.assignProd(a, b)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignProd(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.04, 0.06, 0.15, 0.0))
val res = array.assignProd(a)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDiv(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1111, 0.2222, 0.3333, 0.0))
val res = array.assignDiv(n)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignDiv(array) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.25, 0.6667, 0.6, 0.0))
val res = array.assignDiv(a)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignPow(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2399, 0.3687, 0.4740, 0.0))
val res = array.assignPow(0.62)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignExp(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(1.105171, 1.221403, 1.349859, 1.0))
val res = array.assignExp()
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-6) }
}
}
context("assignSqrt(number) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3162, 0.4472, 0.5478, 0.0))
val res = array.assignSqrt()
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("assignLog10() method") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val array2 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.3, 0.5, 0.7))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.397940, -0.522879, -0.301030, -0.154902))
val res = array2.assignLog10()
it("should raise an exception if at least a value is 0.0") {
assertFailsWith<IllegalArgumentException> { array1.assignLog10() }
}
it("should return the same DenseNDArray with a valid array") {
assertTrue { array2 === res }
}
it("should assign the expected values with a valid array") {
assertTrue { array2.equals(expectedArray, tolerance = 1.0e-06) }
}
}
context("assignLn() method") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val array2 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.3, 0.5, 0.7))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.916291, -1.203973, -0.693147, -0.356675))
val res = array2.assignLn()
it("should raise an exception if at least a value is 0.0") {
assertFailsWith<IllegalArgumentException> { array1.assignLn() }
}
it("should return the same DenseNDArray with a valid array") {
assertTrue { array2 === res }
}
it("should assign the expected values with a valid array") {
assertTrue { array2.equals(expectedArray, tolerance = 1.0e-06) }
}
}
context("assignRoundInt(threshold) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 1.0, 1.0, 0.0))
val res = array.assignRoundInt(threshold = 0.2)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should assign the expected values") {
assertTrue { array.equals(expectedArray, tolerance = 1.0e-04) }
}
}
context("randomize(randomGenerator) method") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
val randomGeneratorMock = mock<RandomGenerator>()
var i = 0
@Suppress("UNUSED_CHANGED_VALUE")
whenever(randomGeneratorMock.next()).then { a[i++] } // assign the same values of [a]
val res = array.randomize(randomGeneratorMock)
it("should return the same DenseNDArray") {
assertTrue { array === res }
}
it("should return the expected values") {
assertTrue { res.equals(a) }
}
}
}
context("other math methods") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
context("sum() method") {
it("should give the expected sum of its elements") {
assertTrue { equals(0.6, array.sum(), tolerance = 1.0e-10) }
}
}
context("norm() method") {
it("should return the expected norm") {
assertTrue { equals(0.6, array.norm(), tolerance = 1.0e-05) }
}
}
context("norm2() method") {
it("should return the expected euclidean norm") {
assertTrue { equals(0.37417, array.norm2(), tolerance = 1.0e-05) }
}
}
context("argMaxIndex() method") {
it("should have the expected argmax index") {
assertEquals(2, array.argMaxIndex())
}
it("should have the expected argmax index excluding a given index") {
assertEquals(1, array.argMaxIndex(exceptIndex = 2))
}
it("should have the expected argmax index excluding more indices") {
assertEquals(0, array.argMaxIndex(exceptIndices = setOf(1, 2)))
}
}
context("max() method") {
it("should have the expected max value") {
assertEquals(0.3, array.max())
}
}
}
context("initialization through an array of 2 double arrays of 4 elements") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.4),
doubleArrayOf(0.5, 0.6, 0.7, 0.8)
))
context("properties") {
it("should not be a vector") {
assertFalse { array.isVector }
}
it("should be a matrix") {
assertTrue { array.isMatrix }
}
it("should have the expected length") {
assertEquals(8, array.length)
}
it("should have the expected number of rows") {
assertEquals(2, array.rows)
}
it("should have the expected number of columns") {
assertEquals(4, array.columns)
}
it("should have the expected shape") {
assertEquals(Shape(2, 4), array.shape)
}
}
context("generic methods") {
it("should be equal to itself") {
assertTrue { array.equals(array) }
}
it("should be equal to its copy") {
assertTrue { array.equals(array.copy()) }
}
}
context("getRange() method") {
it("should fail the vertical vector require") {
assertFailsWith<Throwable> {
array.getRange(2, 4)
}
}
}
context("getRow() method") {
val row = array.getRow(1)
it("should return a row vector") {
assertEquals(1, row.rows)
}
it("should return the expected row values") {
assertTrue { row.equals(DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.5, 0.6, 0.7, 0.8)))) }
}
}
context("getRows() method") {
val rows = array.getRows()
it("should return the expected number of rows") {
assertEquals(2, rows.size)
}
it("should return the expected first row") {
assertTrue {
rows[0].equals(DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.1, 0.2, 0.3, 0.4))), tolerance = 0.001)
}
}
it("should return the expected second row") {
assertTrue {
rows[1].equals(DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.5, 0.6, 0.7, 0.8))), tolerance = 0.001)
}
}
}
context("getColumn() method") {
val column = array.getColumn(1)
it("should return a column vector") {
assertEquals(1, column.columns)
}
it("should return the expected column values") {
assertTrue { column.equals(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2, 0.6))) }
}
}
context("getColumns() method") {
val columns = array.getColumns()
it("should return the expected number of columns") {
assertEquals(4, columns.size)
}
it("should return the expected first column") {
assertTrue {
columns[0].equals(
DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.1), doubleArrayOf(0.5))),
tolerance = 0.001)
}
}
it("should return the expected second column") {
assertTrue {
columns[1].equals(
DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.2), doubleArrayOf(0.6))),
tolerance = 0.001)
}
}
it("should return the expected third column") {
assertTrue {
columns[2].equals(
DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.3), doubleArrayOf(0.7))),
tolerance = 0.001)
}
}
it("should return the expected fourth column") {
assertTrue {
columns[3].equals(
DenseNDArrayFactory.arrayOf(listOf(doubleArrayOf(0.4), doubleArrayOf(0.8))),
tolerance = 0.001)
}
}
}
context("transpose") {
val transposedArray = array.t
it("should give a transposed array with the expected shape") {
assertEquals(Shape(4, 2), transposedArray.shape)
}
it("should give a transposed array with the expected values") {
assertEquals(transposedArray[2, 1], 0.7)
}
}
}
context("initialization through zerosLike()") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0)).zerosLike()
val arrayOfZeros = array.zerosLike()
it("should have the expected length") {
assertEquals(array.length, arrayOfZeros.length)
}
it("should have the expected values") {
assertTrue { DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0)).equals(arrayOfZeros) }
}
}
context("initialization through onesLike()") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0)).onesLike()
val arrayOfOnes = array.onesLike()
it("should have the expected length") {
assertEquals(array.length, arrayOfOnes.length)
}
it("should have the expected values") {
assertTrue { DenseNDArrayFactory.arrayOf(doubleArrayOf(1.0, 1.0, 1.0, 1.0)).equals(arrayOfOnes) }
}
}
context("converting a DenseNDArray to zeros") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.4),
doubleArrayOf(0.5, 0.6, 0.7, 0.8)
))
context("zeros() method call") {
array.zeros()
it("should return an DenseNDArray filled with zeros") {
(0 until array.length).forEach { i -> assertEquals(0.0, array[i]) }
}
}
}
context("converting a DenseNDArray to ones") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3, 0.4),
doubleArrayOf(0.5, 0.6, 0.7, 0.8)
))
context("ones() method call") {
array.ones()
it("should return an DenseNDArray filled with ones") {
(0 until array.length).forEach { i -> assertEquals(1.0, array[i]) }
}
}
}
context("values assignment") {
context("assignment through another DenseNDArray") {
val array = DenseNDArrayFactory.emptyArray(Shape(3, 2))
val arrayToAssign = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2),
doubleArrayOf(0.3, 0.4),
doubleArrayOf(0.5, 0.6)
))
array.assignValues(arrayToAssign)
it("should contain the expected assigned values") {
assertTrue { array.equals(arrayToAssign) }
}
}
context("assignment through a number") {
val array = DenseNDArrayFactory.emptyArray(Shape(3, 2))
array.assignValues(0.6)
it("should contain the expected assigned values") {
(0 until array.length).forEach { i -> assertEquals(0.6, array[i]) }
}
}
}
context("getters") {
context("a vertical vector") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
it("should get the correct item") {
assertEquals(array[2], 0.3)
}
}
context("a horizontal vector") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1),
doubleArrayOf(0.2),
doubleArrayOf(0.3),
doubleArrayOf(0.0)
))
it("should get the correct item") {
assertEquals(array[2], 0.3)
}
}
context("a matrix") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3),
doubleArrayOf(0.4, 0.5, 0.6)
))
it("should get the correct item") {
assertEquals(array[1, 2], 0.6)
}
}
}
context("setters") {
context("a vertical vector") {
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.0))
array[2] = 0.7
it("should set the correct item") {
assertEquals(array[2], 0.7)
}
}
context("a horizontal vector") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1),
doubleArrayOf(0.2),
doubleArrayOf(0.3),
doubleArrayOf(0.0)
))
array[2] = 0.7
it("should get the correct item") {
assertEquals(array[2], 0.7)
}
}
context("a matrix") {
val array = DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.2, 0.3),
doubleArrayOf(0.4, 0.5, 0.6)
))
array[1, 2] = 0.7
it("should get the correct item") {
assertEquals(array[1, 2], 0.7)
}
}
}
context("single horizontal concatenation") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3))
val array2 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.5, 0.6))
val concatenatedArray = array1.concatH(array2)
it("should have the expected shape") {
assertEquals(Shape(3, 2), concatenatedArray.shape)
}
it("should have the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.4),
doubleArrayOf(0.2, 0.5),
doubleArrayOf(0.3, 0.6))
).equals(concatenatedArray)
}
}
}
context("single vertical concatenation") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3))
val array2 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.5, 0.6))
val concatenatedArray = array1.concatV(array2)
it("should have the expected length") {
assertEquals(6, concatenatedArray.length)
}
it("should have the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.4, 0.5, 0.6))
.equals(concatenatedArray)
}
}
}
context("multiple vertical concatenation") {
val concatenatedArray = concatVectorsV(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, 0.5, 0.6)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, 0.8, 0.9))
)
it("should have the expected length") {
assertEquals(9, concatenatedArray.length)
}
it("should have the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9))
.equals(concatenatedArray)
}
}
}
context("single vertical split") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.4))
val splitArray: List<DenseNDArray> = array1.splitV(2)
it("should have the expected length") {
assertEquals(2, splitArray.size)
}
it("should have the expected values") {
assertEquals(
listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4))
),
splitArray
)
}
}
context("single vertical split multiple range size") {
val array1 = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2, 0.3, 0.4))
val splitArray: List<DenseNDArray> = array1.splitV(2, 1, 1)
it("should have the expected length") {
assertEquals(3, splitArray.size)
}
it("should have the expected values") {
assertEquals(
listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.2)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4))
),
splitArray
)
}
}
}
})
| mpl-2.0 | 23eaa1ddb59b9b1c17002accb8bc7ffc | 29.809331 | 122 | 0.573902 | 4.058246 | false | false | false | false |
edwardharks/Aircraft-Recognition | recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/feedback/RepositorySubmitFeedbackUseCaseTest.kt | 1 | 1678 | package com.edwardharker.aircraftrecognition.feedback
import com.edwardharker.aircraftrecognition.model.FeedbackResult
import com.edwardharker.aircraftrecognition.model.FeedbackResult.*
import com.edwardharker.aircraftrecognition.repository.FakeFeedbackRepository
import com.edwardharker.aircraftrecognition.repository.FeedbackRepository
import com.nhaarman.mockito_kotlin.verify
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert
import org.junit.Assert.assertThat
import org.junit.Test
import org.mockito.Mockito
class RepositorySubmitFeedbackUseCaseTest {
@Test
fun `submits feedback`() {
val mockRepository = Mockito.mock(FeedbackRepository::class.java)
val useCase = RepositorySubmitFeedbackUseCase(mockRepository)
useCase.submitFeedback(MESSAGE)
verify(mockRepository).submitFeedback(MESSAGE)
}
@Test
fun `returns feedback success result`() {
val useCase = RepositorySubmitFeedbackUseCase(
feedbackRepository = FakeFeedbackRepository(
withResult = Success
)
)
val actual = useCase.submitFeedback(MESSAGE)
assertThat(actual, equalTo<FeedbackResult>(Success))
}
@Test
fun `returns feedback error result`() {
val useCase = RepositorySubmitFeedbackUseCase(
feedbackRepository = FakeFeedbackRepository(
withResult = Error
)
)
val actual = useCase.submitFeedback(MESSAGE)
assertThat(actual, equalTo<FeedbackResult>(Error))
}
companion object {
private const val MESSAGE = "A lovely message"
}
} | gpl-3.0 | 67ce1ccae6a07df1026788445659cf64 | 30.679245 | 77 | 0.722884 | 5.131498 | false | true | false | false |
martinhellwig/DatapassWidget | app/src/main/java/de/schooltec/datapass/AppWidgetIdUtil.kt | 1 | 5172 | package de.schooltec.datapass
import android.appwidget.AppWidgetManager
import android.content.Context
import java.util.*
/**
* Copyright Kyss.
* Created by Martin Hellwig on 2019-06-20.
*/
object AppWidgetIdUtil {
const val LAST_UPDATE_TIMESTAMP = "last_update_timestamp"
private const val MIN_TIME_BETWEEN_TWO_REQUESTS = 15_000L
/**
* Says, if the time of last update of the given widget is more than the current time plus the
* specified timeout apart. This method does not set the new time to the given widget.
* @param context
* the context, needed for sharedPrefs
* @param appWidgetId
* the appWidgetId to proof
* @return
* true, if the last update was long ago or this appWidgetId is completely new
*/
fun lastUpdateTimeoutOver(context: Context, appWidgetId: Int): Boolean {
val sharedPref = context.getSharedPreferences(PreferenceKeys.PREFERENCE_FILE_MISC, Context.MODE_PRIVATE)
val lastUpdate = sharedPref.getLong(LAST_UPDATE_TIMESTAMP + appWidgetId, 0)
return lastUpdate + MIN_TIME_BETWEEN_TWO_REQUESTS < Date().time
}
/**
* Deletes all entries in the current widget list, where the toDeleteWidgetId matches. Also returns the carrier of
* the deleted entry.
*
* @param context
* the context
* @param toDeleteWidgetId
* the widgetId to delete
*
* @return the carrier of the probably deleted widget, otherwise null
*/
fun deleteEntryIfContained(context: Context, toDeleteWidgetId: Int): String? {
val newToStoreWidgetIds = HashSet<String>()
var oldCarrier: String? = null
val sharedPreferences = context.getSharedPreferences(PreferenceKeys.PREFERENCE_FILE_MISC, Context.MODE_PRIVATE)
val storedWidgetIds = sharedPreferences.getStringSet(PreferenceKeys.SAVED_APP_IDS, HashSet())
storedWidgetIds?.forEach {
val widgetId = Integer.valueOf(it.substring(0, it.indexOf(",")))
if (widgetId == toDeleteWidgetId) {
oldCarrier = it.substring(it.indexOf(",") + 1)
} else {
newToStoreWidgetIds.add(it)
}
}
val editor = sharedPreferences.edit()
editor.putStringSet(PreferenceKeys.SAVED_APP_IDS, newToStoreWidgetIds)
editor.apply()
return oldCarrier
}
fun getCarrierForGivenAppWidgetId(context: Context, appWidgetId: Int): String? {
val sharedPreferences = context.getSharedPreferences(PreferenceKeys.PREFERENCE_FILE_MISC, Context.MODE_PRIVATE)
val storedWidgetIds = sharedPreferences.getStringSet(PreferenceKeys.SAVED_APP_IDS, HashSet())
storedWidgetIds?.forEach {
val widgetId = Integer.valueOf(it.substring(0, it.indexOf(",")))
if (widgetId == appWidgetId) {
return it.substring(it.indexOf(",") + 1)
}
}
return null
}
fun getAllStoredAppWidgetIds(context: Context): MutableSet<String> {
val appWidgetManager = AppWidgetManager.getInstance(context)
val appWidgetProvider = appWidgetManager.installedProviders.find {
it.provider.shortClassName.contains(WidgetAutoUpdateProvider::class.java.simpleName.toString())
}
val realAppWidgetIds = appWidgetProvider?.let {
appWidgetManager.getAppWidgetIds(it.provider)
} ?: IntArray(0)
val sharedPref = context.getSharedPreferences(PreferenceKeys.PREFERENCE_FILE_MISC, Context.MODE_PRIVATE)
val currentlyStoredAppIds = sharedPref.getStringSet(
PreferenceKeys.SAVED_APP_IDS,
HashSet()
) ?: HashSet()
currentlyStoredAppIds.forEach { storedAppWidgetIdPlusCarrier ->
var isRealAppWidgetId = false
realAppWidgetIds.forEach {
if (storedAppWidgetIdPlusCarrier.contains(it.toString())) isRealAppWidgetId = true
}
if (!isRealAppWidgetId) {
val widgetId = Integer.valueOf(
storedAppWidgetIdPlusCarrier.substring(
0,
storedAppWidgetIdPlusCarrier.indexOf(",")
)
)
deleteEntryIfContained(context, widgetId)
}
}
return sharedPref.getStringSet(
PreferenceKeys.SAVED_APP_IDS,
HashSet()
) ?: HashSet()
}
/**
* Saves the new widget data in shared preferences.
*
* @param context
* the context
* @param appWidgetId
* the id of this widget
* @param carrier
* the carrier of this widget
*/
fun addEntry(context: Context, appWidgetId: Int, carrier: String) {
val sharedPreferences = context.getSharedPreferences(PreferenceKeys.PREFERENCE_FILE_MISC, Context.MODE_PRIVATE)
val storedWidgetIds = sharedPreferences.getStringSet(PreferenceKeys.SAVED_APP_IDS, HashSet())
storedWidgetIds?.add("$appWidgetId,$carrier")
val editor = sharedPreferences.edit()
editor.putStringSet(PreferenceKeys.SAVED_APP_IDS, storedWidgetIds)
editor.apply()
}
}
| apache-2.0 | 0daa2c43efe6cbd795354846bf2a2912 | 37.311111 | 119 | 0.651779 | 4.888469 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginVfsListener.kt | 1 | 4898 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.ide.FrameStateListener
import com.intellij.ide.IdeBundle
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.PreloadingActivity
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import java.nio.file.Path
private const val AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY = "idea.auto.reload.plugins"
private var initialRefreshDone = false
internal class DynamicPluginVfsListenerInitializer : PreloadingActivity() {
override suspend fun execute() {
if (java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) {
val pluginsPath = PathManager.getPluginsPath()
LocalFileSystem.getInstance().addRootToWatch(pluginsPath, true)
val pluginsRoot = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(pluginsPath))
if (pluginsRoot != null) {
// ensure all plugins are in VFS
VfsUtilCore.processFilesRecursively(pluginsRoot) { true }
RefreshQueue.getInstance().refresh(true, true, Runnable { initialRefreshDone = true }, pluginsRoot)
}
else {
DynamicPluginVfsListener.LOG.info("Dynamic plugin VFS listener not active, couldn't find plugins root in VFS")
}
}
}
}
internal class DynamicPluginVfsListener : AsyncFileListener {
override fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier? {
if (!java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) return null
if (!initialRefreshDone) return null
val pluginsToReload = hashSetOf<IdeaPluginDescriptorImpl>()
for (event in events) {
if (!event.isFromRefresh) continue
if (event is VFileContentChangeEvent) {
findPluginByPath(event.file)?.let {
LOG.info("Detected plugin .jar file change ${event.path}, reloading plugin")
pluginsToReload.add(it)
}
}
}
val descriptorsToReload = pluginsToReload.filter { it.isEnabled && DynamicPlugins.allowLoadUnloadWithoutRestart(it) }
if (descriptorsToReload.isEmpty()) {
return null
}
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
ApplicationManager.getApplication().invokeLater {
val reloaded = mutableListOf<String>()
val unloadFailed = mutableListOf<String>()
for (pluginDescriptor in descriptorsToReload) {
if (!DynamicPlugins.unloadPlugin(pluginDescriptor, DynamicPlugins.UnloadPluginOptions(isUpdate = true, waitForClassloaderUnload = true))) {
unloadFailed.add(pluginDescriptor.name)
continue
}
reloaded.add(pluginDescriptor.name)
DynamicPlugins.loadPlugin(pluginDescriptor)
}
if (unloadFailed.isNotEmpty()) {
DynamicPlugins.notify(IdeBundle.message("failed.to.unload.modified.plugins", unloadFailed.joinToString()), NotificationType.INFORMATION,
object : AnAction(IdeBundle.message("ide.restart.action")) {
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().restart()
}
})
}
else if (reloaded.isNotEmpty()) {
DynamicPlugins.notify(IdeBundle.message("plugins.reloaded.successfully", reloaded.joinToString()), NotificationType.INFORMATION)
}
}
}
}
}
private fun findPluginByPath(file: VirtualFile): IdeaPluginDescriptorImpl? {
if (!VfsUtilCore.isAncestorOrSelf(PathManager.getPluginsPath(), file)) {
return null
}
return PluginManager.getPlugins().firstOrNull {
VfsUtilCore.isAncestorOrSelf(it.pluginPath.toAbsolutePath().toString(), file)
} as IdeaPluginDescriptorImpl?
}
companion object {
val LOG = Logger.getInstance(DynamicPluginVfsListener::class.java)
}
}
class DynamicPluginsFrameStateListener : FrameStateListener {
override fun onFrameActivated() {
if (!java.lang.Boolean.getBoolean(AUTO_RELOAD_PLUGINS_SYSTEM_PROPERTY)) return
val pluginsRoot = LocalFileSystem.getInstance().findFileByPath(PathManager.getPluginsPath())
pluginsRoot?.refresh(true, true)
}
}
| apache-2.0 | 2fdaee0853a38aa0479ae8906b8271e4 | 41.591304 | 151 | 0.729686 | 4.898 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConflictingExtensionPropertyInspection.kt | 1 | 13015 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.ModalityUiUtil
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.resolve.scopes.collectSyntheticExtensionProperties
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() {
@OptIn(FrontendInternals::class)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
val file = session.file as? KtFile ?: return PsiElementVisitor.EMPTY_VISITOR
val resolutionFacade = file.getResolutionFacade()
return propertyVisitor(fun(property: KtProperty) {
if (property.receiverTypeReference != null) {
val nameElement = property.nameIdentifier ?: return
val propertyDescriptor = property.resolveToDescriptorIfAny(resolutionFacade) as? PropertyDescriptor ?: return
val syntheticScopes = resolutionFacade.frontendService<SyntheticScopes>()
val conflictingExtension = conflictingSyntheticExtension(propertyDescriptor, syntheticScopes) ?: return
// don't report on hidden declarations
if (resolutionFacade.frontendService<DeprecationResolver>().isHiddenInResolution(propertyDescriptor)) return
val fixes = createFixes(property, conflictingExtension, isOnTheFly)
val problemDescriptor = holder.manager.createProblemDescriptor(
nameElement,
KotlinBundle.message("this.property.conflicts.with.synthetic.extension.and.should.be.removed.or.renamed.to.avoid.breaking.code.by.future.changes.in.the.compiler"),
true,
fixes,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
holder.registerProblem(problemDescriptor)
}
})
}
private fun conflictingSyntheticExtension(descriptor: PropertyDescriptor, scopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? {
val extensionReceiverType = descriptor.extensionReceiverParameter?.type ?: return null
return scopes.collectSyntheticExtensionProperties(listOf(extensionReceiverType), descriptor.name, NoLookupLocation.FROM_IDE)
.firstIsInstanceOrNull<SyntheticJavaPropertyDescriptor>()
}
private fun isSameAsSynthetic(declaration: KtProperty, syntheticProperty: SyntheticJavaPropertyDescriptor): Boolean {
val getter = declaration.getter ?: return false
val setter = declaration.setter
if (!checkGetterBodyIsGetMethodCall(getter, syntheticProperty.getMethod)) return false
if (setter != null) {
val setMethod = syntheticProperty.setMethod ?: return false // synthetic property is val but our property is var
if (!checkSetterBodyIsSetMethodCall(setter, setMethod)) return false
}
return true
}
private fun checkGetterBodyIsGetMethodCall(getter: KtPropertyAccessor, getMethod: FunctionDescriptor): Boolean {
return if (getter.hasBlockBody()) {
val statement = getter.bodyBlockExpression?.statements?.singleOrNull() ?: return false
(statement as? KtReturnExpression)?.returnedExpression.isGetMethodCall(getMethod)
} else {
getter.bodyExpression.isGetMethodCall(getMethod)
}
}
private fun checkSetterBodyIsSetMethodCall(setter: KtPropertyAccessor, setMethod: FunctionDescriptor): Boolean {
val valueParameterName = setter.valueParameters.singleOrNull()?.nameAsName ?: return false
if (setter.hasBlockBody()) {
val statement = setter.bodyBlockExpression?.statements?.singleOrNull() ?: return false
return statement.isSetMethodCall(setMethod, valueParameterName)
} else {
return setter.bodyExpression.isSetMethodCall(setMethod, valueParameterName)
}
}
private fun KtExpression?.isGetMethodCall(getMethod: FunctionDescriptor): Boolean = when (this) {
is KtCallExpression -> {
val resolvedCall = resolveToCall()
resolvedCall != null && resolvedCall.isReallySuccess() && resolvedCall.resultingDescriptor.original == getMethod.original
}
is KtQualifiedExpression -> {
val receiver = receiverExpression
receiver is KtThisExpression && receiver.labelQualifier == null && selectorExpression.isGetMethodCall(getMethod)
}
else -> false
}
private fun KtExpression?.isSetMethodCall(setMethod: FunctionDescriptor, valueParameterName: Name): Boolean {
when (this) {
is KtCallExpression -> {
if ((valueArguments.singleOrNull()
?.getArgumentExpression() as? KtSimpleNameExpression)?.getReferencedNameAsName() != valueParameterName
) return false
val resolvedCall = resolveToCall()
return resolvedCall != null &&
resolvedCall.isReallySuccess() &&
resolvedCall.resultingDescriptor.original == setMethod.original
}
is KtQualifiedExpression -> {
val receiver = receiverExpression
return receiver is KtThisExpression && receiver.labelQualifier == null && selectorExpression.isSetMethodCall(
setMethod,
valueParameterName
)
}
else -> return false
}
}
private fun createFixes(
property: KtProperty,
conflictingExtension: SyntheticJavaPropertyDescriptor,
isOnTheFly: Boolean
): Array<IntentionWrapper> {
return if (isSameAsSynthetic(property, conflictingExtension)) {
val fix1 = IntentionWrapper(DeleteRedundantExtensionAction(property))
// don't add the second fix when on the fly to allow code cleanup
val fix2 = if (isOnTheFly)
object : IntentionWrapper(MarkHiddenAndDeprecatedAction(property)), LowPriorityAction {}
else
null
listOfNotNull(fix1, fix2).toTypedArray()
} else {
emptyArray()
}
}
private class DeleteRedundantExtensionAction(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) {
companion object {
private val LOG = logger<DeleteRedundantExtensionAction>()
}
override fun getFamilyName() = KotlinBundle.message("delete.redundant.extension.property")
override fun getText() = familyName
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val declaration = element ?: return
val fqName = declaration.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL).importableFqName
if (fqName != null) {
ProgressManager.getInstance().run(
object : Task.Modal(project, KotlinBundle.message("searching.for.imports.to.delete.title"), true) {
override fun run(indicator: ProgressIndicator) {
val importsToDelete = runReadAction {
val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project)
ReferencesSearch.search(declaration, searchScope)
.filterIsInstance<KtSimpleNameReference>()
.mapNotNull { ref -> ref.expression.getStrictParentOfType<KtImportDirective>() }
.filter { import -> !import.isAllUnder && import.targetDescriptors().size == 1 }
}
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL)
{
project.executeWriteCommand(text) {
importsToDelete.forEach { import ->
if (!FileModificationService.getInstance()
.preparePsiElementForWrite(
import
)
) return@forEach
try {
import.delete()
} catch (e: Exception) {
LOG.error(e)
}
}
declaration.delete()
}
}
}
})
} else {
project.executeWriteCommand(text) { declaration.delete() }
}
}
}
private class MarkHiddenAndDeprecatedAction(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) {
override fun getFamilyName() = KotlinBundle.message("mark.as.deprecated.level.deprecationlevel.hidden")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val factory = KtPsiFactory(project)
val name = element.nameAsName!!.render()
element.addAnnotationWithLineBreak(factory.createAnnotationEntry("@Deprecated(\"Is replaced with automatic synthetic extension\", ReplaceWith(\"$name\"), level = DeprecationLevel.HIDDEN)"))
}
//TODO: move into PSI?
private fun KtNamedDeclaration.addAnnotationWithLineBreak(annotationEntry: KtAnnotationEntry): KtAnnotationEntry {
val newLine = KtPsiFactory(this).createNewLine()
return if (modifierList != null) {
val result = addAnnotationEntry(annotationEntry)
modifierList!!.addAfter(newLine, result)
result
} else {
val result = addAnnotationEntry(annotationEntry)
addAfter(newLine, modifierList)
result
}
}
}
}
| apache-2.0 | 3cd7a4ea51a135d0c61371207242f8ba | 50.240157 | 201 | 0.665463 | 6.101735 | false | false | false | false |
InsideZhou/Instep | core/src/main/kotlin/instep/util/StringExtensions.kt | 1 | 1486 | package instep.util
import java.util.*
@JvmOverloads
fun String.capitalize(locale: Locale? = null): String {
return this.replaceFirstChar {
if (it.isLowerCase()) {
it.titlecase(locale ?: Locale.getDefault())
}
else {
it.toString()
}
}
}
@JvmOverloads
fun String.snakeToCamelCase(locale: Locale? = null): String {
return "_([a-zA-Z\\d])".toRegex().replace(this) {
it.groupValues[1].uppercase(locale ?: Locale.getDefault())
}
}
@JvmOverloads
fun String.camelCaseToSnake(locale: Locale? = null): String {
val len = this.length
val sb = StringBuilder(len)
this.forEachIndexed { index, item ->
if (!item.isLetter()) {
sb.append(item)
return@forEachIndexed
}
if (0 == index) {
sb.append(item.lowercase(locale ?: Locale.getDefault()))
return@forEachIndexed
}
val previous = this[index - 1]
val next = if (index + 1 < len) {
"${this[index + 1]}"
}
else {
""
}
val nextChar = next.firstOrNull()
if (item.isUpperCase()) {
if ('_' != previous && (!previous.isUpperCase() || (next.isNotBlank() && !nextChar!!.isUpperCase() && !nextChar.isDigit() && '_' != nextChar))) {
sb.append("_")
}
}
sb.append(item.lowercase(locale ?: Locale.getDefault()))
}
return sb.toString()
}
| bsd-2-clause | f960eeac32e9b02ad25e191533620d59 | 23.766667 | 157 | 0.533647 | 4.19774 | false | false | false | false |
plombardi89/KOcean | src/main/kotlin/com/github/plombardi89/kocean/model/Image.kt | 1 | 1178 | package com.github.plombardi89.kocean.model
import com.eclipsesource.json.JsonObject
import java.time.Instant
public data class Image(val id: String, val slug: String?, val name: String, val distribution: String,
val role: ImageRole, val public: Boolean, val minimumDiskSize: Long,
val regions: Collection<String>, val creationTime: Instant) {
companion object: ModelFactory<Image> {
override fun fromJson(json: JsonObject): Image {
return Image(id = json.get("id").asString(),
slug = json.getString("slug", null),
name = json.get("name").asString(),
distribution = json.get("distribution").asString(),
role = ImageRole.fromAlias(json.getString("type", null)),
public = json.get("public").asBoolean(),
minimumDiskSize = json.get("min_disk_size").asLong(),
regions = json.get("regions").asArray().values().map { it.asString() },
creationTime = Instant.parse(json.get("created_at").asString()))
}
}
} | mit | cc822e412d3f329c4eab783ccb47a24c | 48.125 | 102 | 0.566214 | 4.693227 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/util/SchedulerProviders.kt | 1 | 751 | package csumissu.weatherforecast.util
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* @author yxsun
* @since 15/08/2017
*/
interface BaseSchedulerProvider {
fun computation(): Scheduler
fun io(): Scheduler
fun ui(): Scheduler
}
class ImmediateSchedulerProvider : BaseSchedulerProvider {
override fun computation() = Schedulers.single()
override fun io() = Schedulers.single()
override fun ui() = Schedulers.single()
}
class SchedulerProvider : BaseSchedulerProvider {
override fun computation() = Schedulers.computation()
override fun io() = Schedulers.io()
override fun ui(): Scheduler = AndroidSchedulers.mainThread()
} | mit | ec5ddeeb81131f019e03c326e207fb39 | 26.851852 | 65 | 0.747004 | 4.845161 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/permissions/PermissionsSettingsFragment.kt | 1 | 3725 | package org.thoughtcrime.securesms.components.settings.conversation.permissions
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.fragment.app.viewModels
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.groups.ParcelableGroupId
import org.thoughtcrime.securesms.groups.ui.GroupErrors
class PermissionsSettingsFragment : DSLSettingsFragment(
titleId = R.string.ConversationSettingsFragment__permissions
) {
private val permissionsOptions: Array<String> by lazy {
resources.getStringArray(R.array.PermissionsSettingsFragment__editor_labels)
}
private val viewModel: PermissionsSettingsViewModel by viewModels(
factoryProducer = {
val args = PermissionsSettingsFragmentArgs.fromBundle(requireArguments())
val groupId = requireNotNull(ParcelableGroupId.get(args.groupId as ParcelableGroupId))
val repository = PermissionsSettingsRepository(requireContext())
PermissionsSettingsViewModel.Factory(groupId, repository)
}
)
override fun bindAdapter(adapter: DSLSettingsAdapter) {
viewModel.state.observe(viewLifecycleOwner) { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
viewModel.events.observe(viewLifecycleOwner) { event ->
when (event) {
is PermissionsSettingsEvents.GroupChangeError -> handleGroupChangeError(event)
}
}
}
private fun handleGroupChangeError(groupChangeError: PermissionsSettingsEvents.GroupChangeError) {
Toast.makeText(context, GroupErrors.getUserDisplayMessage(groupChangeError.reason), Toast.LENGTH_LONG).show()
}
private fun getConfiguration(state: PermissionsSettingsState): DSLConfiguration {
return configure {
radioListPref(
title = DSLSettingsText.from(R.string.PermissionsSettingsFragment__add_members),
isEnabled = state.selfCanEditSettings,
listItems = permissionsOptions,
dialogTitle = DSLSettingsText.from(R.string.PermissionsSettingsFragment__who_can_add_new_members),
selected = getSelected(state.nonAdminCanAddMembers),
confirmAction = true,
onSelected = {
viewModel.setNonAdminCanAddMembers(it == 1)
}
)
radioListPref(
title = DSLSettingsText.from(R.string.PermissionsSettingsFragment__edit_group_info),
isEnabled = state.selfCanEditSettings,
listItems = permissionsOptions,
dialogTitle = DSLSettingsText.from(R.string.PermissionsSettingsFragment__who_can_edit_this_groups_info),
selected = getSelected(state.nonAdminCanEditGroupInfo),
confirmAction = true,
onSelected = {
viewModel.setNonAdminCanEditGroupInfo(it == 1)
}
)
radioListPref(
title = DSLSettingsText.from(R.string.PermissionsSettingsFragment__send_messages),
isEnabled = state.selfCanEditSettings,
listItems = permissionsOptions,
dialogTitle = DSLSettingsText.from(R.string.PermissionsSettingsFragment__who_can_send_messages),
selected = getSelected(!state.announcementGroup),
confirmAction = true,
onSelected = {
viewModel.setAnnouncementGroup(it == 0)
}
)
}
}
@StringRes
private fun getSelected(isNonAdminAllowed: Boolean): Int {
return if (isNonAdminAllowed) {
1
} else {
0
}
}
}
| gpl-3.0 | cff9fb525e4ba7e768c1628188a681d6 | 37.010204 | 113 | 0.746577 | 4.973298 | false | true | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/expire/ExpireTimerSettingsState.kt | 4 | 450 | package org.thoughtcrime.securesms.components.settings.app.privacy.expire
import org.thoughtcrime.securesms.util.livedata.ProcessState
data class ExpireTimerSettingsState(
val initialTimer: Int = 0,
val userSetTimer: Int? = null,
val saveState: ProcessState<Int> = ProcessState.Idle(),
val isGroupCreate: Boolean = false,
val isForRecipient: Boolean = isGroupCreate,
) {
val currentTimer: Int
get() = userSetTimer ?: initialTimer
}
| gpl-3.0 | bbe2c6d4a5155306b78e39afc6b2f1ca | 31.142857 | 73 | 0.768889 | 4.054054 | false | false | false | false |
marius-m/wt4 | models/src/test/java/lt/markmerkk/entities/JiraWorkValidWorklogTest.kt | 1 | 1003 | package lt.markmerkk.entities
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import lt.markmerkk.entities.JiraWork
import net.rcarz.jiraclient.Issue
import net.rcarz.jiraclient.WorkLog
import org.junit.Assert.*
import org.junit.Test
import java.util.*
/**
* @author mariusmerkevicius
* *
* @since 2016-07-10
*/
class JiraWorkValidWorklogTest {
@Test
fun valid_returnTrue() {
// Arrange
val fakeWorklog: WorkLog = mock()
doReturn(Date(1000)).whenever(fakeWorklog).started
val work = JiraWork()
// Act
val result = work.validWorklog(fakeWorklog)
// Assert
assertTrue(result)
}
@Test
fun invalidNoStart_returnFalse() {
// Arrange
val fakeWorklog: WorkLog = mock()
val work = JiraWork()
// Act
val result = work.validWorklog(fakeWorklog)
// Assert
assertFalse(result)
}
} | apache-2.0 | da4f3beec7e9e3dd848e6cdb7cffb785 | 21.311111 | 58 | 0.66002 | 4.012 | false | true | false | false |
DarrenAtherton49/droid-community-app | app/src/main/kotlin/com/darrenatherton/droidcommunity/data/reddit/RedditDataEntity.kt | 1 | 2388 | package com.darrenatherton.droidcommunity.data.reddit
import com.darrenatherton.droidcommunity.common.util.emptyString
import com.google.gson.JsonElement
data class RedditResponse<out T>(val data: T)
data class RedditObjectWrapper(val kind: RedditType, val data: JsonElement)
enum class RedditType(val derivedClass: Class<*>) {
t1(RedditComment::class.java),
t3(RedditLink::class.java),
Listing(RedditListing::class.java)
}
open class RedditObject
class RedditListing(
val children: List<RedditObject>,
val after: String?,
val before: String?,
val modhash: String
)
open class RedditSubmission(
val author: String = emptyString,
val title: String = emptyString,
val num_comments: Int = 0,
val created: Long = 0,
val thumbnail: String = emptyString,
val url: String = emptyString
) : RedditObject()
class RedditLink(
val domain: String,
val subreddit: String,
val selftext_html: String,
val selftext: String,
val link_flair_text: String,
val clicked: Boolean,
val hidden: Boolean,
val permalink: String,
val stickied: Boolean,
val visited: Boolean
) : RedditSubmission()
class RedditComment(
val replies: RedditObject? = null,
val subreddit_id: String = emptyString,
val parent_id: String = emptyString,
val controversiality: Int = 0,
val body: String = emptyString,
val body_html: String = emptyString,
val link_id: String = emptyString,
val depth: Int = 0
) : RedditSubmission()
enum class Subreddit(val label: String, val urlSuffix: String) {
ANDROIDDEV("/r/AndroidDev", "androiddev"),
ANDROID("/r/Android", "android"),
ANDROIDAPPS("/r/AndroidApps", "androidapps"),
KOTLIN("/r/Kotlin", "kotlin"),
JAVA("/r/Java", "java"),
MATERIAL_DESIGN("/r/MaterialDesign", "materialdesign");
companion object {
fun getReadableLabelFromSuffix(suffix: String): String {
values().forEach {
if (it.urlSuffix.contentEquals(suffix)) {
return it.label
}
}
return "/r/$suffix"
}
}
}
enum class RedditFilterType(private val text: String) {
HOT("hot"),
NEW("new"),
TOP("top");
override fun toString() = text
} | mit | 9a5fd7e6d751c27bc87aec14f71bc84c | 27.440476 | 75 | 0.629816 | 4.256684 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/meow/src/templates/kotlin/meow/meowTypes.kt | 4 | 913 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package meow
import org.lwjgl.generator.*
val meow_u8 = typedef(unsigned_char, "meow_u8")
val meow_u32 = typedef(unsigned_int, "meow_u32")
val meow_u64 = typedef(unsigned_long_long, "meow_u64")
val meow_u128 = struct(
Module.MEOW,
"MeowU128",
nativeName = "meow_u128",
mutable = false,
nativeLayout = true
) {
nativeImport("meow_intrinsics.h")
alignas(16)
}
val meow_hash = union(Module.MEOW, "MeowHash", nativeName = "meow_hash", mutable = false) {
meow_u128("u128", "")
meow_u64("u64", "")[2]
meow_u32("u32", "")[4]
}
val meow_hash_state = struct(
Module.MEOW,
"MeowHashState",
nativeName = "meow_hash_state",
mutable = false,
nativeLayout = true
) {
nativeImport(
"meow_intrinsics.h",
"meow_hash.h",
"meow_more.h"
)
} | bsd-3-clause | 17732e874ced13e3e9a2c9d0e926cc60 | 20.761905 | 91 | 0.618839 | 2.862069 | false | false | false | false |
mdanielwork/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToStatic/ConvertToStaticIntention.kt | 1 | 2300 | // 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 org.jetbrains.plugins.groovy.refactoring.convertToStatic
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.intentions.base.Intention
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle
class ConvertToStaticIntention: Intention() {
override fun getText(): String {
return GroovyRefactoringBundle.message("intention.converting.to.static")
}
override fun getFamilyName(): String {
return GroovyRefactoringBundle.message("intention.converting.to.static.family")
}
override fun processIntention(element: PsiElement, project: Project, editor: Editor?) {
val containingMember = PsiTreeUtil.getParentOfType(element, GrMember::class.java, false, GrAnnotation::class.java) ?: return
applyDeclarationFixes(containingMember)
applyErrorFixes(containingMember)
}
override fun getElementPredicate(): PsiElementPredicate = PsiElementPredicate {
if (!PsiUtil.isCompileStatic(it)) return@PsiElementPredicate false
val checker = TypeChecker()
it.accept(GroovyPsiElementVisitor(checker))
if (checker.fixes.isNotEmpty()) return@PsiElementPredicate true
return@PsiElementPredicate checkUnresolvedReferences(it)
}
private fun checkUnresolvedReferences(element: PsiElement): Boolean {
val expression = element as? GrReferenceExpression ?: return false
if (expression.advancedResolve().isValidResult) return false
val qualifier = expression.qualifierExpression ?: return false
return collectReferencedEmptyDeclarations(qualifier, false).isNotEmpty()
}
} | apache-2.0 | 7ab87e36f4c83a00851f492ef284180a | 46.9375 | 140 | 0.811304 | 4.637097 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/s3/src/main/kotlin/com/kotlin/s3/DeleteBucket.kt | 1 | 1574 | // snippet-sourcedescription:[DeleteBucket.kt demonstrates how to delete an Amazon Simple Storage Service (Amazon S3) bucket.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon S3]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.s3
// snippet-start:[s3.kotlin.del_bucket.import]
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.model.DeleteBucketRequest
import kotlin.system.exitProcess
// snippet-end:[s3.kotlin.del_bucket.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<bucketName>
Where:
bucketName - The name of the Amazon S3 bucket to delete.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val bucketName = args[0]
deleteExistingBucket(bucketName)
}
// snippet-start:[s3.kotlin.del_bucket.main]
suspend fun deleteExistingBucket(bucketName: String?) {
val request = DeleteBucketRequest {
bucket = bucketName
}
S3Client { region = "us-east-1" }.use { s3 ->
s3.deleteBucket(request)
println("The $bucketName was successfully deleted!")
}
}
// snippet-end:[s3.kotlin.del_bucket.main]
| apache-2.0 | 6f20b284e19c9fbe6a97c6ee499191c2 | 26.618182 | 126 | 0.679161 | 3.686183 | false | false | false | false |
seratch/jslack | bolt-docker-examples/echo-command-app/src/main/kotlin/App.kt | 1 | 995 | package example
import com.slack.api.bolt.App
import com.slack.api.bolt.jetty.SlackAppServer
fun main() {
// export SLACK_BOT_TOKEN=xoxb-***
// export SLACK_SIGNING_SECRET=123abc***
val app = App()
app.command("/echo") { req, ctx ->
val text = "You said ${req.payload.text} at <#${req.payload.channelId}|${req.payload.channelName}>"
val res = ctx.respond { it.text(text) }
ctx.logger.info("respond result - {}", res)
ctx.ack()
}
// Amazon Elastic Container Service - the default health check endpoint
// [ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]
// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_HealthCheck.html
app.endpoint("/") { _, ctx ->
ctx.ack()
}
// export SLACK_PORT=8080
val envPort: String? = System.getenv()["SLACK_PORT"]
val port: Int = if (envPort == null) 8080 else Integer.valueOf(envPort)
val server = SlackAppServer(app, port)
server.start()
} | mit | ded7f615f23ae7628bbcbf4ef09268fc | 31.129032 | 107 | 0.625126 | 3.491228 | false | false | false | false |
laviua/komock | komock-core/src/main/kotlin/ua/com/lavi/komock/registrar/consul/ConsulRegistrar.kt | 1 | 1931 | package ua.com.lavi.komock.registrar.consul
import com.ecwid.consul.v1.ConsulClient
import com.ecwid.consul.v1.agent.model.NewService
import org.slf4j.LoggerFactory
import ua.com.lavi.komock.model.config.consul.ConsulAgentProperties
import ua.com.lavi.komock.registrar.Registrar
/**
* Created by Oleksandr Loushkin
*/
class ConsulRegistrar: Registrar<ConsulAgentProperties> {
private val log = LoggerFactory.getLogger(this.javaClass)
override fun register(properties: ConsulAgentProperties) {
val clientRegistrar = ConsulClient(properties.consulHost, properties.consulPort)
log.debug("Found: ${properties.services.size} consul services")
for (consulService in properties.services) {
if (consulService.enabled) {
val newService = NewService()
newService.id = consulService.serviceId
newService.name = consulService.serviceName
newService.port = consulService.servicePort
newService.address = consulService.serviceAddress
val check = NewService.Check()
check.interval = consulService.checkInterval
check.timeout = consulService.checkTimeout
check.tcp = consulService.tcp
check.http = consulService.http
check.script = consulService.script
newService.check = check
clientRegistrar.agentServiceRegister(newService)
log.info("Registered consul service: ${consulService.serviceId} - ${consulService.serviceAddress}:${consulService.servicePort}")
}
}
if (properties.daemon) {
try {
log.info("Consul registration is running in daemon mode")
Thread.currentThread().join()
} catch (e: InterruptedException) {
log.warn("Error: {}", e)
}
}
}
}
| apache-2.0 | 08dcfa85267c5783c5704f09c652e5c2 | 40.085106 | 144 | 0.64319 | 4.408676 | false | false | false | false |
algra/pact-jvm | pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/BaseRequest.kt | 1 | 1752 | package au.com.dius.pact.model
import java.io.ByteArrayOutputStream
import javax.mail.internet.InternetHeaders
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMultipart
abstract class BaseRequest : HttpPart() {
/**
* Sets up the request as a multipart file upload
* @param partName The attribute name in the multipart upload that the file is included in
* @param contentType The content type of the file data
* @param contents File contents
*/
fun withMultipartFileUpload(partName: String, filename: String, contentType: ContentType, contents: String) =
withMultipartFileUpload(partName, filename, contentType.contentType, contents)
/**
* Sets up the request as a multipart file upload
* @param partName The attribute name in the multipart upload that the file is included in
* @param contentType The content type of the file data
* @param contents File contents
*/
fun withMultipartFileUpload(partName: String, filename: String, contentType: String, contents: String): BaseRequest {
val multipart = MimeMultipart("form-data")
val internetHeaders = InternetHeaders()
internetHeaders.setHeader("Content-Disposition", "form-data; name=\"$partName\"; filename=\"$filename\"")
internetHeaders.setHeader("Content-Type", contentType)
multipart.addBodyPart(MimeBodyPart(internetHeaders, contents.toByteArray()))
val stream = ByteArrayOutputStream()
multipart.writeTo(stream)
body = OptionalBody.body(stream.toString())
headers!!["Content-Type"] = multipart.contentType
return this
}
/**
* If this request represents a multipart file upload
*/
fun isMultipartFileUpload() = mimeType().equals("multipart/form-data", ignoreCase = true)
}
| apache-2.0 | f283ce835ced9d9419e23600a4c577ee | 38.818182 | 119 | 0.748858 | 4.684492 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/RecursiveApplicableConversionWithState.kt | 6 | 1027 | // 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
abstract class RecursiveApplicableConversionWithState<S>(
context: NewJ2kConverterContext,
private val initialState: S
) : MatchBasedConversion(context) {
override fun onElementChanged(new: JKTreeElement, old: JKTreeElement) {
somethingChanged = true
}
private var somethingChanged = false
override fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean {
val root = applyToElement(treeRoot, initialState)
assert(root === treeRoot)
return somethingChanged
}
abstract fun applyToElement(element: JKTreeElement, state: S): JKTreeElement
fun <T : JKTreeElement> recurse(element: T, state: S): T = applyRecursive(element, state, ::applyToElement)
}
| apache-2.0 | f3a6be7a31d7d88213aa91d80c6e0401 | 35.678571 | 120 | 0.753651 | 4.504386 | false | false | false | false |
1stargames/speed_clicking | app/src/main/kotlin/games/onestar/speedclicking/helper/SavedScoreHelper.kt | 1 | 1551 | package games.onestar.speedclicking.helper
import android.content.Context
object SavedScoreHelper {
private val SAVED_SCORE = "SHARED_SCORE"
private val TEN_SECONDS_HIGH_SCORE = "TEN_SECONDS_HIGH_SCORE"
private val THIRTY_SECONDS_HIGH_SCORE = "THIRTY_SECONDS_HIGH_SCORE"
private val SIXTY_SECONDS_HIGH_SCORE = "SIXTY_SECONDS_HIGH_SCORE"
fun getTenSecondsHighScore(context: Context): Int {
return getHighScore(context, TEN_SECONDS_HIGH_SCORE)
}
fun setTenSecondsHighScore(context: Context, score: Int) {
setHighScore(context, TEN_SECONDS_HIGH_SCORE, score)
}
fun getThirtySecondsHighScore(context: Context): Int {
return getHighScore(context, THIRTY_SECONDS_HIGH_SCORE)
}
fun setThirtySecondsHighScore(context: Context, score: Int) {
setHighScore(context, THIRTY_SECONDS_HIGH_SCORE, score)
}
fun getSixtySecondsHighScore(context: Context): Int {
return getHighScore(context, SIXTY_SECONDS_HIGH_SCORE)
}
fun setSixtySecondsHighScore(context: Context, score: Int) {
setHighScore(context, SIXTY_SECONDS_HIGH_SCORE, score)
}
private fun getHighScore(context: Context, key: String): Int {
val prefs = context.getSharedPreferences(SAVED_SCORE, Context.MODE_PRIVATE)
return prefs.getInt(key, 0)
}
private fun setHighScore(context: Context, key: String, score: Int) {
val prefs = context.getSharedPreferences(SAVED_SCORE, Context.MODE_PRIVATE)
prefs.edit().putInt(key, score).apply()
}
}
| mit | 5f39fd31fae5cb010c9cc87bb5e38d73 | 32.717391 | 83 | 0.706641 | 3.666667 | false | false | false | false |
JetBrains/intellij-community | plugins/git4idea/src/git4idea/rebase/GitAutomaticRebaseEditor.kt | 1 | 2067 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.rebase
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import git4idea.config.GitConfigUtil
import java.io.File
internal class GitAutomaticRebaseEditor(private val project: Project,
private val root: VirtualFile,
private val entriesEditor: (List<GitRebaseEntry>) -> List<GitRebaseEntry>,
private val plainTextEditor: (String) -> String
) : GitInteractiveRebaseEditorHandler(project, root) {
companion object {
private val LOG = logger<GitAutomaticRebaseEditor>()
}
override fun editCommits(file: File): Int {
try {
if (!myRebaseEditorShown) {
myRebaseEditorShown = true
val rebaseFile = GitInteractiveRebaseFile(project, root, file)
val entries = rebaseFile.load()
rebaseFile.save(entriesEditor(entries))
}
else {
val encoding = GitConfigUtil.getCommitEncoding(project, root)
val originalMessage = FileUtil.loadFile(file, encoding)
val modifiedMessage = plainTextEditor(originalMessage)
FileUtil.writeToFile(file, modifiedMessage.toByteArray(charset(encoding)))
}
return 0
}
catch (ex: Exception) {
LOG.error("Editor failed: ", ex)
return ERROR_EXIT_CODE
}
}
} | apache-2.0 | 04e9c881a0059f5f4050034239d176af | 35.928571 | 114 | 0.68747 | 4.522976 | false | true | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt | 1 | 32169 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.updateSettings.impl
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.externalComponents.ExternalComponentManager
import com.intellij.ide.externalComponents.ExternalComponentSource
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.eventLog.fus.MachineIdManager
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.reference.SoftReference
import com.intellij.util.Urls
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import org.jdom.JDOMException
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JComponent
import kotlin.Result
import kotlin.concurrent.withLock
/**
* See XML file by [ApplicationInfoEx.getUpdateUrls] for reference.
*/
object UpdateChecker {
private val LOG = logger<UpdateChecker>()
private const val DISABLED_UPDATE = "disabled_update.txt"
private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt"
private const val PRODUCT_DATA_TTL_MIN = 5L
private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled"
private const val MACHINE_ID_PARAMETER = "mid"
private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL }
private val updateUrl: String
get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl
private val productDataLock = ReentrantLock()
private var productDataCache: SoftReference<Result<Product?>>? = null
private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap()
private val ourShownNotifications = MultiMap<NotificationKind, Notification>()
private var machineIdInitialized = false
/**
* Adding a plugin ID to this collection allows excluding a plugin from a regular update check.
* Has no effect on non-bundled plugins.
*/
val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf()
init {
UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString())
UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get())
UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION)
if (ExternalUpdateManager.ACTUAL != null) {
val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName
UpdateRequestParameters.addParameter("manager", name)
}
if (ApplicationInfoEx.getInstanceEx().isEAP) {
UpdateRequestParameters.addParameter("eap", "")
}
}
@JvmStatic
fun getNotificationGroup(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates")
@JvmStatic
fun getNotificationGroupForPluginUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results")
@JvmStatic
fun getNotificationGroupForIdeUpdateResults(): NotificationGroup =
NotificationGroupManager.getInstance().getNotificationGroup("IDE Update Results")
/**
* For scheduled update checks.
*/
@JvmStatic
fun updateAndShowResult(): ActionCallback {
return ActionCallback().also {
ProcessIOExecutorService.INSTANCE.execute {
doUpdateAndShowResult(
userInitiated = false,
preferDialog = false,
showSettingsLink = true,
callback = it,
)
}
}
}
/**
* For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
* (the latter action passes customized update settings and forces results presentation in a dialog).
*/
@JvmStatic
@JvmOverloads
fun updateAndShowResult(
project: Project?,
customSettings: UpdateSettings? = null,
) {
ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(
getProject(),
customSettings,
userInitiated = true,
preferDialog = isConditionalModal,
showSettingsLink = shouldStartInBackground(),
indicator = indicator,
)
override fun isConditionalModal(): Boolean = customSettings != null
override fun shouldStartInBackground(): Boolean = !isConditionalModal
})
}
@JvmStatic
private fun doUpdateAndShowResult(
project: Project? = null,
customSettings: UpdateSettings? = null,
userInitiated: Boolean,
preferDialog: Boolean,
showSettingsLink: Boolean,
indicator: ProgressIndicator? = null,
callback: ActionCallback? = null,
) {
if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) {
machineIdInitialized = true
val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "")
if (machineId != null) {
UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId)
}
}
val updateSettings = customSettings ?: UpdateSettings.getInstance()
val platformUpdates = getPlatformUpdates(updateSettings, indicator)
if (platformUpdates is PlatformUpdates.ConnectionError) {
if (userInitiated) {
showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog)
}
callback?.setRejected()
return
}
val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates(
(platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion,
indicator,
)
indicator?.text = IdeBundle.message("updates.external.progress")
val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator)
UpdateSettings.getInstance().saveLastCheckedInfo()
if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) {
val builder = HtmlBuilder()
internalErrors.forEach { (host, ex) ->
if (!builder.isEmpty) builder.br()
val message = host?.let {
IdeBundle.message("updates.plugins.error.message2", it, ex.message)
} ?: IdeBundle.message("updates.plugins.error.message1", ex.message)
builder.append(message)
}
externalErrors.forEach { (key, value) ->
if (!builder.isEmpty) builder.br()
builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message))
}
showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog)
}
ApplicationManager.getApplication().invokeLater {
fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) }
val enabledPlugins = nonIgnored(pluginUpdates.allEnabled)
val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled)
val forceDialog = preferDialog || userInitiated && !notificationsEnabled()
if (platformUpdates is PlatformUpdates.Loaded) {
showResults(
project,
platformUpdates,
updatedPlugins,
pluginUpdates.incompatible,
showNotification = userInitiated || WelcomeFrame.getInstance() != null,
forceDialog,
showSettingsLink,
)
}
else {
showResults(
project,
updatedPlugins,
customRepoPlugins,
externalUpdates,
enabledPlugins.isNotEmpty(),
userInitiated,
forceDialog,
showSettingsLink,
)
}
callback?.setDone()
}
}
@JvmOverloads
@JvmStatic
@JvmName("getPlatformUpdates")
internal fun getPlatformUpdates(
settings: UpdateSettings = UpdateSettings.getInstance(),
indicator: ProgressIndicator? = null,
): PlatformUpdates =
try {
indicator?.text = IdeBundle.message("updates.checking.platform")
val productData = loadProductData(indicator)
if (productData == null || !settings.isCheckNeeded || ExternalUpdateManager.ACTUAL != null) {
PlatformUpdates.Empty
}
else {
UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates()
}
}
catch (e: Exception) {
LOG.infoWithDebug(e)
when (e) {
is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling users
else -> PlatformUpdates.ConnectionError(e)
}
}
@JvmStatic
@Throws(IOException::class, JDOMException::class)
fun loadProductData(indicator: ProgressIndicator?): Product? =
productDataLock.withLock {
val cached = SoftReference.dereference(productDataCache)
if (cached != null) return@withLock cached.getOrThrow()
val result = runCatching {
var url = Urls.newFromEncoded(updateUrl)
if (url.scheme != URLUtil.FILE_PROTOCOL) {
url = UpdateRequestParameters.amendUpdateRequest(url)
}
LOG.debug { "loading ${url}" }
HttpRequests.request(url)
.connect { JDOMUtil.load(it.getReader(indicator)) }
.let { parseUpdateData(it) }
?.also {
if (it.disableMachineId) {
PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true)
UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER)
}
}
}
productDataCache = SoftReference(result)
AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES)
return@withLock result.getOrThrow()
}
private fun clearProductDataCache() {
if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // a longer time means loading now, no much sense in clearing
productDataCache = null
productDataLock.unlock()
}
}
@ApiStatus.Internal
@JvmStatic
fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) {
if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
ApplicationManager.getApplication().executeOnPooledThread {
val updateable = collectUpdateablePlugins()
if (updateable.isNotEmpty()) {
findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null)
}
}
}
}
/**
* When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version,
* otherwise, returns versions compatible with the specified build.
*/
@RequiresBackgroundThread
@RequiresReadLockAbsence
@JvmOverloads
@JvmStatic
fun getInternalPluginUpdates(
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): InternalPluginResults {
indicator?.text = IdeBundle.message("updates.checking.plugins")
if (!PluginEnabler.HEADLESS.isIgnoredDisabledPlugins) {
val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build)
if (brokenPlugins.isNotEmpty()) {
PluginManagerCore.updateBrokenPlugins(brokenPlugins)
}
}
val updateable = collectUpdateablePlugins()
if (updateable.isEmpty()) {
return InternalPluginResults(PluginUpdates())
}
val toUpdate = HashMap<PluginId, PluginDownloader>()
val toUpdateDisabled = HashMap<PluginId, PluginDownloader>()
val customRepoPlugins = HashMap<PluginId, PluginNode>()
val errors = LinkedHashMap<String?, Exception>()
val state = InstalledPluginsState.getInstance()
for (host in RepositoryHelper.getPluginHosts()) {
try {
if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) {
findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator)
}
else {
RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor ->
val id = descriptor.pluginId
if (updateable.remove(id) != null) {
prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host)
}
// collect latest plugins from custom repos
val storedDescriptor = customRepoPlugins[id]
if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) {
customRepoPlugins[id] = descriptor
}
}
}
}
catch (e: Exception) {
LOG.info(
"failed to load plugins from ${host ?: "default repository"}: ${e.message}",
if (LOG.isDebugEnabled) e else null,
)
errors[host] = e
}
}
val incompatible = if (buildNumber == null) emptyList() else {
// collecting plugins that aren't going to be updated and are incompatible with the new build
// (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE)
updateable.values.asSequence()
.filterNotNull()
.filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) }
.toSet()
}
return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors)
}
private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> {
val updateable = HashMap<PluginId, IdeaPluginDescriptor?>()
// installed plugins that could be updated (either downloaded or updateable bundled)
PluginManagerCore.getPlugins()
.filter { !it.isBundled || it.allowBundledUpdate() }
.associateByTo(updateable) { it.pluginId }
// plugins installed in an instance from which the settings were imported
val onceInstalled = PluginManager.getOnceInstalledIfExists()
if (onceInstalled != null) {
try {
Files.readAllLines(onceInstalled).forEach { line ->
val id = PluginId.getId(line.trim { it <= ' ' })
updateable.putIfAbsent(id, null)
}
}
catch (e: IOException) {
LOG.error(onceInstalled.toString(), e)
}
@Suppress("SSBasedInspection")
onceInstalled.toFile().deleteOnExit()
}
// excluding plugins that take care of their own updates
if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) {
excludedFromUpdateCheckPlugins.forEach {
val id = PluginId.getId(it)
val plugin = updateable[id]
if (plugin != null && plugin.isBundled) {
updateable.remove(id)
}
}
}
return updateable
}
@RequiresBackgroundThread
@RequiresReadLockAbsence
private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber?,
state: InstalledPluginsState,
indicator: ProgressIndicator?) {
val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator)
val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet()
val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber)
updateable.forEach { (id, descriptor) ->
val lastUpdate = updates.find { it.pluginId == id.idString }
if (lastUpdate != null &&
(descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor,
buildNumber) > 0)) {
runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) }
.onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it }
.onSuccess { it.externalPluginIdForScreenShots = lastUpdate.externalPluginId }
.onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) }
}
}
(toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) }
}
@RequiresBackgroundThread
private fun prepareDownloader(state: InstalledPluginsState,
descriptor: PluginNode,
buildNumber: BuildNumber?,
toUpdate: MutableMap<PluginId, PluginDownloader>,
toUpdateDisabled: MutableMap<PluginId, PluginDownloader>,
indicator: ProgressIndicator?,
host: String?) {
val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber)
state.onDescriptorDownload(descriptor)
checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator)
}
@JvmOverloads
@JvmStatic
fun getExternalPluginUpdates(
updateSettings: UpdateSettings,
indicator: ProgressIndicator? = null,
): ExternalPluginResults {
val result = ArrayList<ExternalUpdate>()
val errors = LinkedHashMap<ExternalComponentSource, Exception>()
val manager = ExternalComponentManager.getInstance()
for (source in ExternalComponentManager.getComponentSources()) {
indicator?.checkCanceled()
try {
val siteResult = source.getAvailableVersions(indicator, updateSettings)
.filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) }
if (siteResult.isNotEmpty()) {
result += ExternalUpdate(source, siteResult)
}
}
catch (e: Exception) {
LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null)
errors[source] = e
}
}
return ExternalPluginResults(result, errors)
}
@Throws(IOException::class)
@JvmOverloads
@JvmStatic
@RequiresBackgroundThread
fun checkAndPrepareToInstall(
originalDownloader: PluginDownloader,
state: InstalledPluginsState,
toUpdate: MutableMap<PluginId, PluginDownloader>,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
) {
val pluginId = originalDownloader.id
val pluginVersion = originalDownloader.pluginVersion
val installedPlugin = PluginManagerCore.getPlugin(pluginId)
if (installedPlugin == null
|| pluginVersion == null
|| PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) {
val oldDownloader = ourUpdatedPlugins[pluginId]
val downloader = if (PluginManagerCore.isDisabled(pluginId)) {
originalDownloader
}
else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) {
val descriptor = originalDownloader.descriptor
if (descriptor is PluginNode && descriptor.isIncomplete) {
originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator())
ourUpdatedPlugins[pluginId] = originalDownloader
}
originalDownloader
}
else {
oldDownloader
}
val descriptor = downloader.descriptor
if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) {
toUpdate[pluginId] = downloader
}
}
}
private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) {
if (preferDialog) {
UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) }
}
else {
getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project)
}
}
@RequiresEdt
private fun showResults(
project: Project?,
updatedPlugins: List<PluginDownloader>,
customRepoPlugins: Collection<PluginNode>,
externalUpdates: Collection<ExternalUpdate>,
pluginsEnabled: Boolean,
userInitiated: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (pluginsEnabled) {
if (userInitiated) {
ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() }
}
val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() }
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins)
if (userInitiated) {
val updatedPluginNames = updatedPlugins.map { it.pluginName }
val (title, message) = when (updatedPluginNames.size) {
1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0])
else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" }
}
showNotification(
project,
NotificationKind.PLUGINS,
"plugins.update.available",
title,
message,
NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ ->
PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null)
},
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable),
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) {
ignorePlugins(updatedPlugins.map { it.descriptor })
})
}
}
}
if (externalUpdates.isNotEmpty()) {
ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() }
for (update in externalUpdates) {
val runnable = { update.source.installUpdates(update.components) }
if (forceDialog) {
runnable()
}
else {
val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", "))
showNotification(
project, NotificationKind.EXTERNAL, "external.components.available", "", message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable))
}
}
}
else if (!pluginsEnabled) {
if (forceDialog) {
NoUpdatesDialog(showSettingsLink).show()
}
else if (userInitiated) {
showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText())
}
}
}
@RequiresEdt
private fun showResults(
project: Project?,
platformUpdates: PlatformUpdates.Loaded,
updatedPlugins: List<PluginDownloader>,
incompatiblePlugins: Collection<IdeaPluginDescriptor>,
showNotification: Boolean,
forceDialog: Boolean,
showSettingsLink: Boolean,
) {
if (showNotification) {
ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() }
}
val runnable = {
UpdateInfoDialog(
project,
platformUpdates,
showSettingsLink,
updatedPlugins,
incompatiblePlugins,
).show()
}
if (forceDialog) {
runnable()
}
else {
UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins)
if (showNotification) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project)
val message = IdeBundle.message(
"updates.new.build.notification.title",
ApplicationNamesInfo.getInstance().fullProductName,
platformUpdates.newBuild.version,
)
showNotification(
project,
NotificationKind.PLATFORM,
"ide.update.available",
"",
message,
NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) {
IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project)
runnable()
})
}
}
}
private fun notificationsEnabled(): Boolean =
NotificationsConfiguration.getNotificationsConfiguration().let {
it.areNotificationsEnabled() && it.getDisplayType(getNotificationGroup().displayId) != NotificationDisplayType.NONE
}
private fun showNotification(project: Project?,
kind: NotificationKind,
displayId: String,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent message: String,
vararg actions: NotificationAction) {
val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION
val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type)
.setDisplayId(displayId)
.setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST)
notification.whenExpired { ourShownNotifications.remove(kind, notification) }
actions.forEach { notification.addAction(it) }
notification.notify(project)
ourShownNotifications.putValue(kind, notification)
}
@JvmStatic
val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) }
@JvmStatic
fun saveDisabledToUpdatePlugins() {
runCatching {
PluginManagerCore.writePluginIdsToFile(
/* path = */ PathManager.getConfigDir().resolve(DISABLED_UPDATE),
/* pluginIds = */ disabledToUpdate,
)
}.onFailure {
LOG.error(it)
}
}
@JvmStatic
@JvmName("isIgnored")
internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean =
descriptor.ignoredKey in ignoredPlugins
@JvmStatic
@JvmName("ignorePlugins")
internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) {
ignoredPlugins += descriptors.map { it.ignoredKey }
runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) }
.onFailure { LOG.error(it) }
UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors)
}
private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) }
private val IdeaPluginDescriptor.ignoredKey: String
get() = "${pluginId.idString}+${version}"
private fun readConfigLines(fileName: String): List<String> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
runCatching {
val file = Path.of(PathManager.getConfigPath(), fileName)
if (Files.isRegularFile(file)) {
return Files.readAllLines(file)
}
}.onFailure { LOG.error(it) }
}
return emptyList()
}
private var ourHasFailedPlugins = false
@JvmStatic
fun checkForUpdate(event: IdeaLoggingEvent) {
if (!ourHasFailedPlugins) {
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) {
val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable))
if (pluginDescriptor != null && !pluginDescriptor.isBundled) {
ourHasFailedPlugins = true
updateAndShowResult()
}
}
}
}
/** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */
@ApiStatus.Internal
fun testPlatformUpdate(
project: Project?,
updateDataText: String,
patchFile: File?,
forceUpdate: Boolean,
) {
if (!ApplicationManager.getApplication().isInternal) {
throw IllegalStateException()
}
val currentBuild = ApplicationInfo.getInstance().build
val productCode = currentBuild.productCode
val checkForUpdateResult = if (forceUpdate) {
val node = JDOMUtil.load(updateDataText)
.getChild("product")
?.getChild("channel")
?: throw IllegalArgumentException("//channel missing")
val channel = UpdateChannel(node, productCode)
val newBuild = channel.builds.firstOrNull()
?: throw IllegalArgumentException("//build missing")
val patches = newBuild.patches.firstOrNull()
?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) }
PlatformUpdates.Loaded(newBuild, channel, patches)
}
else {
UpdateStrategy(
currentBuild,
parseUpdateData(updateDataText, productCode),
).checkForUpdates()
}
val dialog = when (checkForUpdateResult) {
is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile)
else -> NoUpdatesDialog(true)
}
dialog.show()
}
//<editor-fold desc="Deprecated stuff.">
@ApiStatus.ScheduledForRemoval
@Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()")
@Suppress("DEPRECATION", "unused")
@JvmField
val NOTIFICATIONS = NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID)
@get:ApiStatus.ScheduledForRemoval
@get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate"))
@Suppress("unused")
@JvmStatic
val disabledToUpdatePlugins: Set<String>
get() = disabledToUpdate.mapTo(TreeSet()) { it.idString }
@ApiStatus.ScheduledForRemoval
@Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith(""))
@JvmStatic
fun getPluginUpdates(): Collection<PluginDownloader>? =
getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null }
//</editor-fold>
}
| apache-2.0 | 5a5fb20e23b18f592f66e362542c1903 | 38.665845 | 156 | 0.696043 | 5.428451 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/mpp/populateModuleDependenciesByPlatformPropagation.kt | 1 | 7357 | // 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.gradleJava.configuration.mpp
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinMPPGradleProjectResolver
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.getKotlinModuleId
import org.jetbrains.kotlin.idea.gradleTooling.KotlinDependency
import org.jetbrains.kotlin.idea.gradleTooling.findCompilation
import org.jetbrains.kotlin.idea.gradleTooling.getCompilations
import org.jetbrains.kotlin.idea.projectModel.KotlinCompilation
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform.*
import org.jetbrains.kotlin.idea.projectModel.KotlinSourceSet
import org.jetbrains.plugins.gradle.model.ExternalProjectDependency
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
internal fun KotlinMPPGradleProjectResolver.Companion.populateModuleDependenciesByPlatformPropagation(
context: KotlinMppPopulateModuleDependenciesContext
): Unit = with(context) {
if (!mppModel.extraFeatures.isHMPPEnabled) return
context.mppModel.sourceSetsByName.values
.filter { sourceSet -> isDependencyPropagationAllowed(sourceSet) }
.filter { sourceSet -> processedModuleIds.add(getKotlinModuleId(gradleIdeaModule, sourceSet, resolverCtx)) }
.forEach { sourceSet -> populateModuleDependenciesByPlatformPropagation(context, sourceSet) }
}
//region implementation
/**
* Used to mark a set of dependencies as 'associated with one compilation'
*/
private typealias CompilationDependencies = Set<KotlinDependency>
private fun KotlinMPPGradleProjectResolver.Companion.populateModuleDependenciesByPlatformPropagation(
context: KotlinMppPopulateModuleDependenciesContext, sourceSet: KotlinSourceSet
) = with(context) {
val sourceSetDataNode = getSiblingKotlinModuleData(sourceSet, gradleIdeaModule, ideModule, resolverCtx)?.cast<GradleSourceSetData>()
?: return
val propagatedDependencies = findCompilationsToPropagateDependenciesFrom(sourceSet)
.map { compilation -> resolveVisibleDependencies(compilation) }
.dependencyIntersection()
/*
Dependency Propagation is also allowed for root or intermediate 'Android' source sets.
However, this mechanism is relying on the mpp model to propagate dependencies, which
is not capable of transforming aar dependencies.
For now, only non-aar (jar) dependencies can be propagated.
Android aar dependencies are not supported in source sets like 'commonMain',
even when 'commonMain' is considered 'Android'
*/
.filter { it.packaging != "aar" }
/*
For 'common' (more than one listed platform) source sets:
Project dependencies will not be propagated, but will come from the listed 'source sets' dependencies instead.
This is due to the fact that 'findCompilationsToPropagateDependenciesFrom' might not include the full list of
compilations that the source set participates in.
Therefore, the intersection of dependencies might contain to many visible source sets to other projects.
The mechanism below is more correct in this case.
*/
.filter { sourceSet.actualPlatforms.platforms.size == 1 || it !is ExternalProjectDependency }
/*
Dependency Propagation will not work for project <-> project dependencies.
Source sets that shall receive propagated dependencies still report proper project <-> project dependencies.
Note: This includes sourceSet dependencies as transformed by the 'DependencyAdjuster' where the source set
is mentioned as the configuration of the project dependency!
*/
val projectDependencies = sourceSet.additionalVisibleSourceSets.mapNotNull { mppModel.sourceSetsByName[it] }.plus(sourceSet)
.flatMap { sourceSet -> getDependencies(sourceSet) }
.filterIsInstance<ExternalProjectDependency>().toSet()
val preprocessedDependencies = dependenciesPreprocessor(propagatedDependencies + projectDependencies)
buildDependencies(resolverCtx, sourceSetMap, artifactsMap, sourceSetDataNode, preprocessedDependencies, ideProject)
}
private fun KotlinMppPopulateModuleDependenciesContext.isDependencyPropagationAllowed(sourceSet: KotlinSourceSet): Boolean {
/*
Source sets sharing code between JVM and Android are the only intermediate source sets that
can effectively consume a dependency's platform artifact.
When a library only offers a JVM variant, then Android and JVM consume this variant of the library.
This will be replaced later on by [KT-43450](https://youtrack.jetbrains.com/issue/KT-43450)
*/
if (sourceSet.actualPlatforms.platforms.toSet() == setOf(JVM, ANDROID)) {
return true
}
/*
Single jvm target | Single android target, intermediate source set use case.
This source set shall also just propagate platform dependencies
*/
if (mppModel.sourceSetsByName.values.any { otherSourceSet -> sourceSet.name in otherSourceSet.declaredDependsOnSourceSets } &&
(sourceSet.actualPlatforms.platforms.singleOrNull() == JVM ||
sourceSet.actualPlatforms.platforms.singleOrNull() == ANDROID)
) return true
return false
}
private fun KotlinMppPopulateModuleDependenciesContext.findCompilationsToPropagateDependenciesFrom(
sourceSet: KotlinSourceSet
): Set<KotlinCompilation> {
return when (sourceSet.actualPlatforms.platforms.toSet()) {
/*
Sharing code between Android and JVM:
In this case, we discriminate the Android compilation and only propagate jvm dependencies.
This might lead to some libraries being propagated that are not available on Android, but at least gives
some coverage.
The dependency intersection cannot be built upon jvm + android, because the dependencies
in this case will have *different ids*: As example:
my-library-jvm (jvm) vs my-library-android-release (android)
*/
setOf(JVM, ANDROID) -> mppModel.getCompilations(sourceSet).filter { compilation -> compilation.platform == JVM }
else -> mppModel.getCompilations(sourceSet)
}.toSet()
}
private fun KotlinMppPopulateModuleDependenciesContext.resolveVisibleDependencies(compilation: KotlinCompilation): CompilationDependencies {
return compilation.associateCompilations.mapNotNull { coordinates -> mppModel.findCompilation(coordinates) }.plus(compilation)
.flatMap { compilationOrAssociate -> compilationOrAssociate.dependencies.mapNotNull(mppModel.dependencyMap::get) }
.toSet()
}
/**
* Used to find out 'common' dependencies between compilations.
* A dependency is considered 'common' if its dependency id is present in all sets of dependencies
*
* @return The intersection of all dependencies listed by their dependency ID
*/
private fun List<CompilationDependencies>.dependencyIntersection(): Set<KotlinDependency> {
if (this.isEmpty()) return emptySet()
if (this.size == 1) return first()
val idIntersection = map { dependencies -> dependencies.map { it.id }.toSet() }
.reduce { acc, ids -> acc intersect ids }
return first().filter { dependency -> dependency.id in idIntersection }.toSet()
}
//endregion
| apache-2.0 | 040336cde6f108d51a6894e6ce8352f5 | 50.447552 | 140 | 0.762403 | 5.327299 | false | false | false | false |
google/iosched | model/src/main/java/com/google/samples/apps/iosched/model/Session.kt | 4 | 5849 | /*
* 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.iosched.model
import com.google.samples.apps.iosched.model.SessionType.Companion.reservableTypes
import org.threeten.bp.ZonedDateTime
typealias SessionId = String
/**
* Describes a conference session. Sessions have specific start and end times, and they represent a
* variety of conference events: talks, sandbox demos, office hours, etc. A session is usually
* associated with one or more [Tag]s.
*/
data class Session(
/**
* Unique string identifying this session.
*/
val id: SessionId,
/**
* Start time of the session
*/
val startTime: ZonedDateTime,
/**
* End time of the session
*/
val endTime: ZonedDateTime,
/**
* Session title.
*/
val title: String,
/**
* Body of text explaining this session in detail.
*/
val description: String,
/**
* The session room.
*/
val room: Room?,
/**
* Full URL for the session online.
*/
val sessionUrl: String,
/**
* Indicates if the Session has a live stream.
*/
val isLivestream: Boolean,
/**
* Full URL to YouTube.
*/
val youTubeUrl: String,
/**
* URL to the Dory page.
*/
val doryLink: String,
/**
* The [Tag]s associated with the session. Ordered, with the most important tags appearing
* first.
*/
val tags: List<Tag>,
/**
* Subset of [Tag]s that are for visual consumption.
*/
val displayTags: List<Tag>,
/**
* The session speakers.
*/
val speakers: Set<Speaker>,
/**
* The session's photo URL.
*/
val photoUrl: String,
/**
* IDs of the sessions related to this session.
*/
val relatedSessions: Set<SessionId>
) {
/**
* Returns whether the session is currently being live streamed or not.
*/
fun isLive(): Boolean {
val now = ZonedDateTime.now()
// TODO: Determine when a session is live based on the time AND the liveStream being
// available.
return startTime <= now && endTime >= now
}
val hasPhoto inline get() = photoUrl.isNotEmpty()
/**
* Returns whether the session has a video or not. A session could be live streaming or have a
* recorded session. Both live stream and recorded videos are stored in [Session.youTubeUrl].
*/
val hasVideo inline get() = youTubeUrl.isNotEmpty()
val hasPhotoOrVideo inline get() = hasPhoto || hasVideo
/**
* The year the session was held.
*/
val year = startTime.year
/**
* The duration of the session.
*/
// TODO: Get duration from the YouTube video. Not every talk fills the full session time.
val duration = endTime.toInstant().toEpochMilli() - startTime.toInstant().toEpochMilli()
/**
* The type of the event e.g. Session, Codelab etc.
*/
val type: SessionType by lazy(LazyThreadSafetyMode.PUBLICATION) {
SessionType.fromTags(tags)
}
fun levelTag(): Tag? {
return tags.firstOrNull { it.category == Tag.CATEGORY_LEVEL }
}
/**
* Whether this event is reservable, based upon [type].
*/
val isReservable: Boolean by lazy(LazyThreadSafetyMode.PUBLICATION) {
type in reservableTypes
}
fun isOverlapping(session: Session): Boolean {
return this.startTime < session.endTime && this.endTime > session.startTime
}
/**
* Detailed description of this event. Includes description, speakers, and live-streaming URL.
*/
fun getCalendarDescription(
paragraphDelimiter: String,
speakerDelimiter: String
): String = buildString {
append(description)
append(paragraphDelimiter)
append(speakers.joinToString(speakerDelimiter) { speaker -> speaker.name })
if (!isLivestream && !youTubeUrl.isEmpty()) {
append(paragraphDelimiter)
append(youTubeUrl)
}
}
}
/**
* Represents the type of the event e.g. Session, Codelab etc.
*/
enum class SessionType(val displayName: String) {
KEYNOTE("Keynote"),
SESSION("Session"),
APP_REVIEW("App Reviews"),
GAME_REVIEW("Game Reviews"),
OFFICE_HOURS("Office Hours"),
CODELAB("Codelab"),
MEETUP("Meetup"),
AFTER_DARK("After Dark"),
UNKNOWN("Unknown");
companion object {
/**
* Examine the given [tags] to determine the [SessionType]. Defaults to [SESSION] if no
* category tag is found.
*/
fun fromTags(tags: List<Tag>): SessionType {
val typeTag = tags.firstOrNull { it.category == Tag.CATEGORY_TYPE }
return when (typeTag?.tagName) {
Tag.TYPE_KEYNOTE -> KEYNOTE
Tag.TYPE_SESSIONS -> SESSION
Tag.TYPE_APP_REVIEWS -> APP_REVIEW
Tag.TYPE_GAME_REVIEWS -> GAME_REVIEW
Tag.TYPE_OFFICEHOURS -> OFFICE_HOURS
Tag.TYPE_CODELABS -> CODELAB
Tag.TYPE_MEETUPS -> MEETUP
Tag.TYPE_AFTERDARK -> AFTER_DARK
else -> UNKNOWN
}
}
internal val reservableTypes = listOf(SESSION, OFFICE_HOURS, APP_REVIEW, GAME_REVIEW)
}
}
| apache-2.0 | 708921cdf0f160c0263033b1800e5d29 | 26.078704 | 99 | 0.619251 | 4.345468 | false | false | false | false |
apollographql/apollo-android | tests/coroutines-mt/src/macosX64Test/kotlin/macos/app/MainTest.kt | 1 | 2044 | package macos.app
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.mockserver.enqueue
import com.apollographql.apollo3.mpp.currentThreadId
import com.apollographql.apollo3.cache.normalized.normalizedCache
import com.apollographql.apollo3.testing.runTest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.native.concurrent.freeze
import kotlin.test.Test
import kotlin.test.assertFailsWith
class MainTest {
val json = """
{
"data": {
"random": 42
}
}
""".trimIndent()
@Test
fun coroutinesMtCanWork() = runTest {
withContext(Dispatchers.Default) {
println("Dispatchers.Default: ${currentThreadId()}")
withContext(Dispatchers.Main) {
println("Dispatchers.Main: ${currentThreadId()}")
val server = MockServer()
server.enqueue(json)
val response = ApolloClient.Builder()
.serverUrl(server.url())
.build()
.query(GetRandomQuery())
.execute()
check(response.dataAssertNoErrors.random == 42)
}
}
}
@Test
fun startingAQueryFromNonMainThreadAsserts() = runTest {
val server = MockServer()
server.enqueue(json)
val client = ApolloClient.Builder().serverUrl(server.url()).build().freeze()
withContext(Dispatchers.Default) {
assertFailsWith(IllegalStateException::class) {
client.query(GetRandomQuery()).execute()
}
}
}
@Test
fun freezingTheStoreIsPossible() = runTest {
val server = MockServer()
server.enqueue(json)
val client = ApolloClient.Builder().serverUrl(server.url()).normalizedCache(MemoryCacheFactory()).build()
withContext(Dispatchers.Default) {
withContext(Dispatchers.Main) {
val response = client.query(GetRandomQuery()).execute()
check(response.dataAssertNoErrors.random == 42)
}
}
}
}
| mit | faa5b9195ad7adc8979a6f396e78181b | 29.507463 | 109 | 0.696184 | 4.462882 | false | true | false | false |
JetBrains/intellij-community | plugins/gradle/java/src/service/project/data/AnnotationProcessingDataService.kt | 1 | 12778 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.data
import com.intellij.compiler.CompilerConfiguration
import com.intellij.compiler.CompilerConfigurationImpl
import com.intellij.ide.projectView.actions.MarkRootActionBase
import com.intellij.openapi.diagnostic.Logger
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.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.service.project.manage.SourceFolderManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile
import org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl
import org.jetbrains.plugins.gradle.model.data.AnnotationProcessingData
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.util.*
@Order(ExternalSystemConstants.UNORDERED)
class AnnotationProcessingDataService : AbstractProjectDataService<AnnotationProcessingData, ProcessorConfigProfile>() {
override fun getTargetDataKey(): Key<AnnotationProcessingData> {
return AnnotationProcessingData.KEY
}
override fun importData(toImport: Collection<DataNode<AnnotationProcessingData>>,
projectData: ProjectData?,
project: Project,
modifiableModelsProvider: IdeModifiableModelsProvider) {
val importedData = mutableSetOf<AnnotationProcessingData>()
val config = CompilerConfiguration.getInstance(project) as CompilerConfigurationImpl
val sourceFolderManager = SourceFolderManager.getInstance(project)
for (node in toImport) {
val moduleData = node.parent?.data as? ModuleData
if (moduleData == null) {
LOG.debug("Failed to find parent module data in annotation processor data. Parent: ${node.parent} ")
continue
}
val ideModule = modifiableModelsProvider.findIdeModule(moduleData)
if (ideModule == null) {
LOG.debug("Failed to find ide module for module data: ${moduleData}")
continue
}
config.configureAnnotationProcessing(ideModule, node.data, importedData)
if (projectData != null) {
val isDelegatedBuild = GradleSettings.getInstance(project).getLinkedProjectSettings(
projectData.linkedExternalProjectPath)?.delegatedBuild ?: true
clearGeneratedSourceFolders(ideModule, node, modifiableModelsProvider)
val externalSource = ExternalSystemApiUtil.toExternalSource(moduleData.owner)
addGeneratedSourceFolders(ideModule, node, isDelegatedBuild, modifiableModelsProvider, sourceFolderManager, externalSource)
}
}
}
private fun clearGeneratedSourceFolders(ideModule: Module,
node: DataNode<AnnotationProcessingData>,
modelsProvider: IdeModifiableModelsProvider) {
val gradleOutputs = ExternalSystemApiUtil.findAll(node, AnnotationProcessingData.OUTPUT_KEY)
val pathsToRemove =
(gradleOutputs
.map { it.data.outputPath } +
listOf(
getAnnotationProcessorGenerationPath(ideModule, false, modelsProvider),
getAnnotationProcessorGenerationPath(ideModule, true, modelsProvider)
))
.filterNotNull()
pathsToRemove.forEach { path ->
val url = VfsUtilCore.pathToUrl(path)
val modifiableRootModel = modelsProvider.getModifiableRootModel(ideModule)
val (entry, folder) = findContentEntryOrFolder(modifiableRootModel, url)
if (entry != null) {
if (folder != null) {
entry.removeSourceFolder(folder)
}
if (entry.sourceFolders.isEmpty()) {
modifiableRootModel.removeContentEntry(entry)
}
}
}
}
private fun addGeneratedSourceFolders(ideModule: Module,
node: DataNode<AnnotationProcessingData>,
delegatedBuild: Boolean,
modelsProvider: IdeModifiableModelsProvider,
sourceFolderManager: SourceFolderManager,
externalSource: ProjectModelExternalSource) {
if (delegatedBuild) {
val outputs = ExternalSystemApiUtil.findAll(node, AnnotationProcessingData.OUTPUT_KEY)
outputs.forEach {
val outputPath = it.data.outputPath
val isTestSource = it.data.isTestSources
addGeneratedSourceFolder(ideModule, outputPath, isTestSource, modelsProvider, sourceFolderManager, externalSource)
}
}
else {
val outputPath = getAnnotationProcessorGenerationPath(ideModule, false, modelsProvider)
if (outputPath != null) {
addGeneratedSourceFolder(ideModule, outputPath, false, modelsProvider, sourceFolderManager, externalSource)
}
val testOutputPath = getAnnotationProcessorGenerationPath(ideModule, true, modelsProvider)
if (testOutputPath != null) {
addGeneratedSourceFolder(ideModule, testOutputPath, true, modelsProvider, sourceFolderManager, externalSource)
}
}
}
private fun addGeneratedSourceFolder(ideModule: Module,
path: String,
isTest: Boolean,
modelsProvider: IdeModifiableModelsProvider,
sourceFolderManager: SourceFolderManager,
externalSource: ProjectModelExternalSource) {
val type = if (isTest) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE
val url = VfsUtilCore.pathToUrl(path)
val vf = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)
if (vf == null || !vf.exists()) {
sourceFolderManager.addSourceFolder(ideModule, url, type)
sourceFolderManager.setSourceFolderGenerated(url, true)
} else {
val modifiableRootModel = modelsProvider.getModifiableRootModel(ideModule)
val contentEntry = MarkRootActionBase.findContentEntry(modifiableRootModel, vf)
?: modifiableRootModel.addContentEntry(url)
val properties = JpsJavaExtensionService.getInstance().createSourceRootProperties("", true)
contentEntry.addSourceFolder(url, type, properties, externalSource)
}
}
private fun findContentEntryOrFolder(modifiableRootModel: ModifiableRootModel,
url: String): Pair<ContentEntry?, SourceFolder?> {
var entryVar: ContentEntry? = null
var folderVar: SourceFolder? = null
modifiableRootModel.contentEntries.forEach search@{ ce ->
ce.sourceFolders.forEach { sf ->
if (sf.url == url) {
entryVar = ce
folderVar = sf
return@search
}
}
if (ce.url == url) {
entryVar = ce
}
}
return entryVar to folderVar
}
private fun getAnnotationProcessorGenerationPath(ideModule: Module, forTests: Boolean,
modelsProvider: IdeModifiableModelsProvider): String? {
val config = CompilerConfiguration.getInstance(ideModule.project).getAnnotationProcessingConfiguration(ideModule)
val sourceDirName = config.getGeneratedSourcesDirectoryName(forTests)
val roots = modelsProvider.getModifiableRootModel(ideModule).contentRootUrls
if (roots.isEmpty()) {
return null
}
if (roots.size > 1) {
Arrays.sort(roots)
}
return if (StringUtil.isEmpty(sourceDirName)) VirtualFileManager.extractPath(roots[0])
else VirtualFileManager.extractPath(roots[0]) + "/" + sourceDirName
}
override fun computeOrphanData(toImport: Collection<DataNode<AnnotationProcessingData>>,
projectData: ProjectData,
project: Project,
modelsProvider: IdeModifiableModelsProvider): Computable<Collection<ProcessorConfigProfile>> =
Computable {
val profiles = ArrayList((CompilerConfiguration.getInstance(project) as CompilerConfigurationImpl).moduleProcessorProfiles)
val importedProcessingProfiles = ArrayList(toImport).asSequence()
.map { it.data }
.distinct()
.map { createProcessorConfigProfile(it) }
.toList()
val orphans = profiles
.filter {
it.moduleNames.all { configuredModule -> isGradleModule(configuredModule, modelsProvider) }
&& importedProcessingProfiles.none { imported -> imported.matches(it) }
}
.toMutableList()
orphans
}
private fun isGradleModule(moduleName: String, modelsProvider: IdeModifiableModelsProvider): Boolean {
return ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID,
modelsProvider.findIdeModule(moduleName))
}
override fun removeData(toRemoveComputable: Computable<out Collection<ProcessorConfigProfile>>,
toIgnore: Collection<DataNode<AnnotationProcessingData>>,
projectData: ProjectData,
project: Project,
modelsProvider: IdeModifiableModelsProvider) {
val toRemove = toRemoveComputable.compute()
val config = CompilerConfiguration.getInstance(project) as CompilerConfigurationImpl
val newProfiles = config
.moduleProcessorProfiles
.toMutableList()
.apply { removeAll(toRemove) }
config.setModuleProcessorProfiles(newProfiles)
}
private fun CompilerConfigurationImpl.configureAnnotationProcessing(ideModule: Module,
data: AnnotationProcessingData,
importedData: MutableSet<AnnotationProcessingData>) {
val profile = findOrCreateProcessorConfigProfile(data)
if (importedData.add(data)) {
profile.clearModuleNames()
}
with(profile) {
isEnabled = true
isObtainProcessorsFromClasspath = false
isOutputRelativeToContentRoot = true
addModuleName(ideModule.name)
}
}
private fun CompilerConfigurationImpl.findOrCreateProcessorConfigProfile(data: AnnotationProcessingData): ProcessorConfigProfile {
val newProfile = createProcessorConfigProfile(data)
return ArrayList(this.moduleProcessorProfiles)
.find { existing -> existing.matches(newProfile) }
?: newProfile.also { addModuleProcessorProfile(it) }
}
private fun createProcessorConfigProfile(annotationProcessingData: AnnotationProcessingData): ProcessorConfigProfileImpl {
val newProfile = ProcessorConfigProfileImpl(IMPORTED_PROFILE_NAME)
newProfile.setProcessorPath(annotationProcessingData.path.joinToString(separator = File.pathSeparator))
annotationProcessingData.arguments
.map { it.removePrefix("-A").split('=', limit = 2) }
.forEach { newProfile.setOption(it[0], if (it.size > 1) it[1] else "") }
return newProfile
}
private fun ProcessorConfigProfile.matches(other: ProcessorConfigProfile): Boolean {
return this.name == other.name
&& this.processorPath == other.processorPath
&& this.processorOptions == other.processorOptions
}
companion object {
private val LOG = Logger.getInstance(AnnotationProcessingDataService::class.java)
const val IMPORTED_PROFILE_NAME = "Gradle Imported"
}
}
| apache-2.0 | 83d9e50cf5dba71b08af45b262d66ad5 | 44.799283 | 140 | 0.704257 | 5.577477 | false | true | false | false |
youdonghai/intellij-community | plugins/settings-repository/testSrc/LoadTest.kt | 1 | 5647 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.configurationStore.SchemeManagerImpl
import com.intellij.configurationStore.TestScheme
import com.intellij.configurationStore.TestSchemesProcessor
import com.intellij.configurationStore.save
import com.intellij.testFramework.ProjectRule
import com.intellij.util.toByteArray
import com.intellij.util.xmlb.serialize
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.ReadonlySource
import org.jetbrains.settingsRepository.SyncType
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.cloneBare
import org.jetbrains.settingsRepository.git.commit
import org.junit.ClassRule
import org.junit.Test
private const val dirName = "keymaps"
class LoadTest : IcsTestCase() {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@Suppress("UNCHECKED_CAST")
private fun createSchemeManager(dirPath: String) = icsManager.schemeManagerFactory.value.create(dirPath, TestSchemesProcessor(), streamProvider = provider) as SchemeManagerImpl<TestScheme, TestScheme>
@Test fun `load scheme`() {
val localScheme = TestScheme("local")
provider.write("$dirName/local.xml", localScheme.serialize().toByteArray())
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
schemeManager.save()
val dirPath = (icsManager.repositoryManager as GitRepositoryManager).repository.workTree.toPath().resolve(dirName)
assertThat(dirPath).isDirectory()
schemeManager.removeScheme(localScheme)
schemeManager.save()
assertThat(dirPath).doesNotExist()
provider.write("$dirName/local1.xml", TestScheme("local1").serialize().toByteArray())
provider.write("$dirName/local2.xml", TestScheme("local2").serialize().toByteArray())
assertThat(dirPath.resolve("local1.xml")).isRegularFile()
assertThat(dirPath.resolve("local2.xml")).isRegularFile()
schemeManager.loadSchemes()
schemeManager.removeScheme("local1")
schemeManager.save()
assertThat(dirPath.resolve("local1.xml")).doesNotExist()
assertThat(dirPath.resolve("local2.xml")).isRegularFile()
}
@Test fun `load scheme with the same names`() {
val localScheme = TestScheme("local")
val data = localScheme.serialize().toByteArray()
provider.write("$dirName/local.xml", data)
provider.write("$dirName/local2.xml", data)
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
}
@Test fun `load scheme from repo and read-only repo`() {
val localScheme = TestScheme("local")
provider.write("$dirName/local.xml", localScheme.serialize().toByteArray())
val remoteScheme = TestScheme("remote")
val remoteRepository = tempDirManager.createRepository()
remoteRepository
.add("$dirName/Mac OS X from RubyMine.xml", remoteScheme.serialize().toByteArray())
.commit("")
remoteRepository.useAsReadOnlySource {
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(remoteScheme, localScheme)
assertThat(schemeManager.isMetadataEditable(localScheme)).isTrue()
assertThat(schemeManager.isMetadataEditable(remoteScheme)).isFalse()
remoteRepository
.delete("$dirName/Mac OS X from RubyMine.xml")
.commit("")
icsManager.sync(SyncType.MERGE)
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
}
}
@Test fun `scheme overrides read-only`() {
val schemeName = "Emacs"
val localScheme = TestScheme(schemeName, "local")
provider.write("$dirName/$schemeName.xml", localScheme.serialize().toByteArray())
val remoteScheme = TestScheme(schemeName, "remote")
val remoteRepository = tempDirManager.createRepository("remote")
remoteRepository
.add("$dirName/$schemeName.xml", remoteScheme.serialize().toByteArray())
.commit("")
remoteRepository.useAsReadOnlySource {
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
assertThat(schemeManager.isMetadataEditable(localScheme)).isFalse()
}
}
inline fun Repository.useAsReadOnlySource(runnable: () -> Unit) {
createAndRegisterReadOnlySource()
try {
runnable()
}
finally {
icsManager.readOnlySourcesManager.setSources(emptyList())
}
}
fun Repository.createAndRegisterReadOnlySource(): ReadonlySource {
val source = ReadonlySource(workTree.absolutePath)
assertThat(cloneBare(source.url!!, icsManager.readOnlySourcesManager.rootDir.resolve(source.path!!)).objectDatabase.exists()).isTrue()
icsManager.readOnlySourcesManager.setSources(listOf(source))
return source
}
} | apache-2.0 | 5b160a0ba0c943942bb8199510892133 | 35.915033 | 202 | 0.754029 | 5.019556 | false | true | false | false |
ttomsu/orca | orca-peering/src/main/kotlin/com/netflix/spinnaker/orca/peering/PeeringMetrics.kt | 1 | 2912 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.peering
import com.netflix.spectator.api.Id
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import java.time.Duration
open class PeeringMetrics(
peeredId: String,
private val registry: Registry
) {
private val peeringLagTimerId = registry.createId("pollers.peering.lag").withTag("peerId", peeredId)
private val peeringNumPeeredId = registry.createId("pollers.peering.numPeered").withTag("peerId", peeredId)
private val peeringNumDeletedId = registry.createId("pollers.peering.numDeleted").withTag("peerId", peeredId)
private val peeringNumStagesDeletedId = registry.createId("pollers.peering.numStagesDeleted").withTag("peerId", peeredId)
private val peeringNumErrorsId = registry.createId("pollers.peering.numErrors").withTag("peerId", peeredId)
open fun recordOverallLag(block: () -> Unit) {
registry
.timer(peeringLagTimerId.withTag("executionType", "OVER_ALL"))
.record {
block()
}
}
open fun recordLag(executionType: ExecutionType, duration: Duration) {
registry
.timer(peeringLagTimerId.tag(executionType))
.record(duration)
}
open fun incrementNumPeered(executionType: ExecutionType, state: ExecutionState, count: Int) {
registry
.counter(peeringNumPeeredId.tag(executionType, state))
.increment(count.toLong())
}
open fun incrementNumDeleted(executionType: ExecutionType, count: Int) {
registry
.counter(peeringNumDeletedId.tag(executionType))
.increment(count.toLong())
}
open fun incrementNumErrors(executionType: ExecutionType) {
registry
.counter(peeringNumErrorsId.tag(executionType))
.increment()
}
open fun incrementNumStagesDeleted(executionType: ExecutionType, count: Int) {
registry
.counter(peeringNumStagesDeletedId.tag(executionType))
.increment(count.toLong())
}
}
internal fun Id.tag(executionType: ExecutionType): Id {
return this
.withTag("executionType", executionType.toString())
}
internal fun Id.tag(executionType: ExecutionType, state: ExecutionState): Id {
return this
.withTag("executionType", executionType.toString())
.withTag("state", state.toString())
}
enum class ExecutionState {
ACTIVE,
COMPLETED,
}
| apache-2.0 | a0ab47c7b650a64decdc51a7f2fcab92 | 32.090909 | 123 | 0.741071 | 4.027663 | false | false | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/ForwardingTimeout.kt | 1 | 1720 | /*
* Copyright (C) 2015 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 okio
import java.io.IOException
import java.util.concurrent.TimeUnit
/** A [Timeout] which forwards calls to another. Useful for subclassing. */
open class ForwardingTimeout(
@get:JvmName("delegate")
@set:JvmSynthetic // So .java callers get the setter that returns this.
var delegate: Timeout
) : Timeout() {
// For backwards compatibility with Okio 1.x, this exists so it can return `ForwardingTimeout`.
fun setDelegate(delegate: Timeout): ForwardingTimeout {
this.delegate = delegate
return this
}
override fun timeout(timeout: Long, unit: TimeUnit) = delegate.timeout(timeout, unit)
override fun timeoutNanos() = delegate.timeoutNanos()
override fun hasDeadline() = delegate.hasDeadline()
override fun deadlineNanoTime() = delegate.deadlineNanoTime()
override fun deadlineNanoTime(deadlineNanoTime: Long) = delegate.deadlineNanoTime(
deadlineNanoTime
)
override fun clearTimeout() = delegate.clearTimeout()
override fun clearDeadline() = delegate.clearDeadline()
@Throws(IOException::class)
override fun throwIfReached() = delegate.throwIfReached()
}
| apache-2.0 | 53c7e77c8e85b9930b1ce5ece88d8594 | 32.076923 | 97 | 0.744767 | 4.37659 | false | false | false | false |
allotria/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/logger/FileNavigationLogger.kt | 2 | 3647 | // 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.intellij.filePrediction.logger
import com.intellij.filePrediction.candidates.FilePredictionCandidateSource
import com.intellij.filePrediction.predictor.FilePredictionCompressedCandidate
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.project.Project
internal class FileNavigationLogger : CounterUsagesCollector() {
companion object {
private val GROUP = EventLogGroup("file.prediction", 12)
private var session: IntEventField = EventFields.Int("session")
private var performance: LongListEventField = EventFields.LongList("performance")
private var anonymized_path: CandidateAnonymizedPath = CandidateAnonymizedPath()
private var opened: EncodedBooleanEventField = EncodedBooleanEventField("opened")
private var source: EncodedEnumEventField<FilePredictionCandidateSource> = EncodedEnumEventField("source")
private var probability: EncodedDoubleEventField = EncodedDoubleEventField("prob")
private var features: StringEventField = EventFields.StringValidatedByCustomRule("features", "file_features")
private var candidates: ObjectListEventField = ObjectListEventField(
"candidates",
anonymized_path,
opened.field,
source.field,
probability.field,
features
)
private val cacheCandidates = GROUP.registerEvent("calculated", session, performance, candidates)
fun logEvent(project: Project,
sessionId: Int,
opened: FilePredictionCompressedCandidate?,
candidates: List<FilePredictionCompressedCandidate>,
totalDuration: Long,
refsComputation: Long) {
val allCandidates: MutableList<ObjectEventData> = arrayListOf()
if (opened != null) {
allCandidates.add(toObject(opened, true))
}
for (candidate in candidates) {
allCandidates.add(toObject(candidate, false))
}
val performanceMs = toPerformanceMetrics(totalDuration, refsComputation, opened, candidates)
cacheCandidates.log(project, sessionId, performanceMs, allCandidates)
}
private fun toObject(candidate: FilePredictionCompressedCandidate, wasOpened: Boolean): ObjectEventData {
val data = arrayListOf<EventPair<*>>(
anonymized_path.with(candidate.path),
opened.with(wasOpened),
source.with(candidate.source)
)
if (candidate.probability != null) {
data.add(probability.with(candidate.probability))
}
data.add(features.with(candidate.features))
return ObjectEventData(data)
}
private fun toPerformanceMetrics(totalDuration: Long, refsComputation: Long,
openCandidate: FilePredictionCompressedCandidate?,
candidates: List<FilePredictionCompressedCandidate>): List<Long> {
var featuresMs: Long = 0
var predictionMs: Long = 0
openCandidate?.let {
featuresMs += it.featuresComputation
predictionMs += it.duration ?: 0
}
for (candidate in candidates) {
featuresMs += candidate.featuresComputation
predictionMs += candidate.duration ?: 0
}
return arrayListOf(totalDuration, refsComputation, featuresMs, predictionMs)
}
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | apache-2.0 | 1c6917d5589f7f86f495b2183063df19 | 39.087912 | 140 | 0.71456 | 5.202568 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/find/actions/SearchTarget2UsageTarget.kt | 2 | 3953 | // 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.
@file:Suppress("DEPRECATION")
package com.intellij.find.actions
import com.intellij.find.usages.api.SearchTarget
import com.intellij.find.usages.api.UsageHandler
import com.intellij.find.usages.impl.AllSearchOptions
import com.intellij.model.Pointer
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.usageView.UsageViewBundle
import com.intellij.usages.ConfigurableUsageTarget
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageView
import com.intellij.usages.impl.UsageViewImpl
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.Icon
@ApiStatus.Internal
class SearchTarget2UsageTarget<O>(
private val project: Project,
target: SearchTarget,
private val allOptions: AllSearchOptions<O>
) : UsageTarget, DataProvider, ConfigurableUsageTarget {
private val myPointer: Pointer<out SearchTarget> = target.createPointer()
override fun isValid(): Boolean = myPointer.dereference() != null
// ----- presentation -----
private var myItemPresentation: ItemPresentation = getItemPresentation(target)
override fun update() {
val target = myPointer.dereference() ?: return
myItemPresentation = getItemPresentation(target)
}
private fun getItemPresentation(target: SearchTarget): ItemPresentation {
val presentation = target.presentation
return object : ItemPresentation {
override fun getIcon(unused: Boolean): Icon? = presentation.icon
override fun getPresentableText(): String = presentation.presentableText
override fun getLocationString(): String = error("must not be called")
}
}
override fun getPresentation(): ItemPresentation = myItemPresentation
override fun isReadOnly(): Boolean = false // TODO used in Usage View displayed by refactorings
// ----- Navigatable & NavigationItem -----
// TODO Symbol navigation
override fun canNavigate(): Boolean = false
override fun canNavigateToSource(): Boolean = false
override fun getName(): String? = null
override fun navigate(requestFocus: Boolean) = Unit
// ----- actions -----
override fun getShortcut(): KeyboardShortcut? = UsageViewImpl.getShowUsagesWithSettingsShortcut()
override fun getLongDescriptiveName(): @Nls String {
val target = myPointer.dereference() ?: return UsageViewBundle.message("node.invalid")
@Suppress("UNCHECKED_CAST") val usageHandler = target.usageHandler as UsageHandler<O>
return UsageViewBundle.message(
"search.title.0.in.1",
usageHandler.getSearchString(allOptions),
allOptions.options.searchScope.displayName
)
}
override fun showSettings() {
val target = myPointer.dereference() ?: return
@Suppress("UNCHECKED_CAST") val usageHandler = target.usageHandler as UsageHandler<O>
val dialog = UsageOptionsDialog(project, target.displayString, usageHandler, allOptions, target.showScopeChooser(), true)
if (!dialog.showAndGet()) {
return
}
val newOptions = dialog.result()
findUsages(project, target, usageHandler, newOptions)
}
override fun findUsages(): Unit = error("must not be called")
override fun findUsagesInEditor(editor: FileEditor): Unit = error("must not be called")
override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean): Unit = error("must not be called")
// ----- data context -----
override fun getData(dataId: String): Any? {
if (UsageView.USAGE_SCOPE.`is`(dataId)) {
return allOptions.options.searchScope
}
return null
}
}
| apache-2.0 | 5a286580aa47b65c8071d6e4de5c91b1 | 37.378641 | 140 | 0.759423 | 4.656066 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/ext/IntExt.kt | 1 | 503 | package slatekit.common.ext
//import java.time.*
import org.threeten.bp.*
import org.threeten.bp.temporal.*
val Int.years: Period get() = Period.ofYears(this)
val Int.months: Period get() = Period.ofMonths(this)
val Int.days: Period get() = Period.ofDays(this)
val Int.hours: Duration get() = Duration.of(this.toLong(), ChronoUnit.HOURS)
val Int.minutes: Duration get() = Duration.of(this.toLong(), ChronoUnit.MINUTES)
val Int.seconds: Duration get() = Duration.of(this.toLong(), ChronoUnit.SECONDS)
| apache-2.0 | 325de7997059d14f547ace385b23846a | 37.692308 | 80 | 0.743539 | 3.353333 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkDownloadDialog.kt | 1 | 5077 | // 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.openapi.projectRoots.impl.jdkDownloader
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.textFieldWithBrowseButton
import com.intellij.ui.layout.*
import java.awt.Component
import java.awt.event.ItemEvent
import javax.swing.Action
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.event.DocumentEvent
class JdkDownloadDialog(
val project: Project?,
val parentComponent: Component?,
val sdkType: SdkTypeId,
val items: List<JdkItem>
) : DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) {
companion object {
const val DIALOG_TITLE = "Download JDK"
}
private val panel: JComponent
private var installDirTextField: TextFieldWithBrowseButton
private lateinit var selectedItem: JdkItem
private lateinit var selectedPath: String
init {
title = DIALOG_TITLE
setResizable(false)
val defaultItem = items.filter { it.isDefaultItem }.minBy { it } /*pick the newest default JDK */
?: items.minBy { it } /* pick just the newest JDK is no default was set (aka the JSON is broken) */
?: error("There must be at least one JDK to install") /* totally broken JSON */
val vendorComboBox = ComboBox(items.map { it.product }.distinct().sorted().toTypedArray())
vendorComboBox.selectedItem = defaultItem.product
vendorComboBox.renderer = object: ColoredListCellRenderer<JdkProduct>() {
override fun customizeCellRenderer(list: JList<out JdkProduct>, value: JdkProduct?, index: Int, selected: Boolean, hasFocus: Boolean) {
value ?: return
append(value.packagePresentationText)
}
}
vendorComboBox.isSwingPopup = false
val versionModel = DefaultComboBoxModel<JdkItem>()
val versionComboBox = ComboBox(versionModel)
versionComboBox.renderer = object: ColoredListCellRenderer<JdkItem>() {
override fun customizeCellRenderer(list: JList<out JdkItem>, value: JdkItem?, index: Int, selected: Boolean, hasFocus: Boolean) {
value ?: return
append(value.versionPresentationText, SimpleTextAttributes.REGULAR_ATTRIBUTES)
append(" ")
append(value.downloadSizePresentationText, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
}
versionComboBox.isSwingPopup = false
fun selectVersions(newProduct: JdkProduct) {
val newVersions = items.filter { it.product == newProduct }.sorted()
versionModel.removeAllElements()
for (version in newVersions) {
versionModel.addElement(version)
}
}
installDirTextField = textFieldWithBrowseButton(
project = project,
browseDialogTitle = "Select Path to Install JDK",
fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
)
fun selectInstallPath(newVersion: JdkItem) {
installDirTextField.text = JdkInstaller.defaultInstallDir(newVersion)
selectedItem = newVersion
}
vendorComboBox.onSelectionChange(::selectVersions)
versionComboBox.onSelectionChange(::selectInstallPath)
installDirTextField.onTextChange {
selectedPath = it
}
panel = panel {
row("Vendor:") { vendorComboBox.invoke().sizeGroup("combo").focused() }
row("Version:") { versionComboBox.invoke().sizeGroup("combo") }
row("Location:") { installDirTextField.invoke() }
}
myOKAction.putValue(Action.NAME, "Download")
init()
selectVersions(defaultItem.product)
}
override fun doValidate(): ValidationInfo? {
super.doValidate()?.let { return it }
val path = selectedPath
val (_, error) = JdkInstaller.validateInstallDir(path)
return error?.let { ValidationInfo(error, installDirTextField) }
}
override fun createCenterPanel() = panel
// returns unpacked JDK location (if any) or null if cancelled
fun selectJdkAndPath() = when {
showAndGet() -> selectedItem to selectedPath //TODO: validate the path!
else -> null
}
private inline fun TextFieldWithBrowseButton.onTextChange(crossinline action: (String) -> Unit) {
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
action(text)
}
})
}
private inline fun <reified T> ComboBox<T>.onSelectionChange(crossinline action: (T) -> Unit) {
this.addItemListener { e ->
if (e.stateChange == ItemEvent.SELECTED) action(e.item as T)
}
}
}
| apache-2.0 | e12b08f113c285582ed81a373486c21b | 36.330882 | 141 | 0.731337 | 4.662075 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.