repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/AsyncEditorLoader.kt | 2 | 8330 | // 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.fileEditor.impl.text
import com.intellij.diagnostic.ThreadDumper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorStateLevel
import com.intellij.openapi.fileEditor.impl.EditorsSplitters.Companion.isOpenedInBulk
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.EditorNotifications
import com.intellij.util.concurrency.Semaphore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
class AsyncEditorLoader internal constructor(private val textEditor: TextEditorImpl,
private val editorComponent: TextEditorComponent,
private val provider: TextEditorProvider) {
private val editor: Editor = textEditor.editor
private val project: Project = textEditor.myProject
private val delayedActions = ArrayList<Runnable>()
private var delayedState: TextEditorState? = null
private val loadingFinished = AtomicBoolean()
@OptIn(ExperimentalCoroutinesApi::class)
private val executor: Executor = object : Executor {
private val dispatcher = Dispatchers.IO.limitedParallelism(2)
override fun execute(command: Runnable) {
project.coroutineScope.launch(dispatcher) {
command.run()
}
}
}
init {
editor.putUserData(ASYNC_LOADER, this)
editorComponent.contentPanel.isVisible = false
}
companion object {
private val ASYNC_LOADER = Key.create<AsyncEditorLoader>("ASYNC_LOADER")
private const val SYNCHRONOUS_LOADING_WAITING_TIME_MS = 200
private const val DOCUMENT_COMMIT_WAITING_TIME_MS = 5000
private val LOG = Logger.getInstance(AsyncEditorLoader::class.java)
private fun <T> resultInTimeOrNull(future: CompletableFuture<T>): T? {
try {
return future.get(SYNCHRONOUS_LOADING_WAITING_TIME_MS.toLong(), TimeUnit.MILLISECONDS)
}
catch (ignored: InterruptedException) {
}
catch (ignored: TimeoutException) {
}
return null
}
@JvmStatic
fun performWhenLoaded(editor: Editor, runnable: Runnable) {
ApplicationManager.getApplication().assertIsDispatchThread()
val loader = editor.getUserData(ASYNC_LOADER)
loader?.delayedActions?.add(runnable) ?: runnable.run()
}
@JvmStatic
fun isEditorLoaded(editor: Editor): Boolean {
return editor.getUserData(ASYNC_LOADER) == null
}
}
fun start() {
ApplicationManager.getApplication().assertIsDispatchThread()
val asyncLoading = scheduleLoading()
var showProgress = true
if (worthWaiting()) {
/*
* Possible alternatives:
* 1. show "Loading" from the beginning, then it'll be always noticeable at least in fade-out phase
* 2. show a gray screen for some time and then "Loading" if it's still loading; it'll produce quick background blinking for all editors
* 3. show non-highlighted and unfolded editor as "Loading" background and allow it to relayout at the end of loading phase
* 4. freeze EDT a bit and hope that for small editors it'll suffice and for big ones show "Loading" after that.
* This strategy seems to produce minimal blinking annoyance.
*/
val continuation = resultInTimeOrNull(asyncLoading)
if (continuation != null) {
showProgress = false
loadingFinished(continuation)
}
}
if (showProgress) {
editorComponent.startLoading()
}
}
private fun scheduleLoading(): CompletableFuture<Runnable> {
val commitDeadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(DOCUMENT_COMMIT_WAITING_TIME_MS.toLong())
// we can't return the result of "nonBlocking" call below because it's only finished on EDT later,
// but we need to get the result of bg calculation in the same EDT event, if it's quick
val future = CompletableFuture<Runnable>()
ReadAction.nonBlocking<Runnable> {
waitForCommit(commitDeadline)
val runnable = ProgressManager.getInstance().computePrioritized<Runnable, RuntimeException> {
try {
return@computePrioritized textEditor.loadEditorInBackground()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: IndexOutOfBoundsException) {
// EA-232290 investigation
val filePathAttachment = Attachment("filePath.txt", textEditor.file.toString())
val threadDumpAttachment = Attachment("threadDump.txt", ThreadDumper.dumpThreadsToString())
threadDumpAttachment.isIncluded = true
LOG.error("Error during async editor loading", e,
filePathAttachment, threadDumpAttachment)
return@computePrioritized null
}
catch (e: Exception) {
LOG.error("Error during async editor loading", e)
return@computePrioritized null
}
}
future.complete(runnable)
runnable
}
.expireWith(editorComponent)
.expireWith(project)
.finishOnUiThread(ModalityState.any(), ::loadingFinished)
.submit(executor)
return future
}
private fun waitForCommit(commitDeadlineNs: Long) {
val document = editor.document
val pdm = PsiDocumentManager.getInstance(project)
if (!pdm.isCommitted(document) && System.nanoTime() < commitDeadlineNs) {
val semaphore = Semaphore(1)
pdm.performForCommittedDocument(document) { semaphore.up() }
while (System.nanoTime() < commitDeadlineNs && !semaphore.waitFor(10)) {
ProgressManager.checkCanceled()
}
}
}
private val isDone: Boolean
get() = loadingFinished.get()
private fun worthWaiting(): Boolean {
// cannot perform commitAndRunReadAction in parallel to EDT waiting
return !isOpenedInBulk(textEditor.myFile) &&
!PsiDocumentManager.getInstance(project).hasUncommitedDocuments() &&
!ApplicationManager.getApplication().isWriteAccessAllowed
}
private fun loadingFinished(continuation: Runnable?) {
if (!loadingFinished.compareAndSet(false, true)) {
return
}
editor.putUserData(ASYNC_LOADER, null)
if (editorComponent.isDisposed) {
return
}
if (continuation != null) {
try {
continuation.run()
}
catch (e: Throwable) {
LOG.error(e)
}
}
editorComponent.loadingFinished()
if (delayedState != null && PsiDocumentManager.getInstance(project).isCommitted(editor.document)) {
val state = TextEditorState()
state.RELATIVE_CARET_POSITION = Int.MAX_VALUE // don't do any scrolling
state.foldingState = delayedState!!.foldingState
provider.setStateImpl(project, editor, state, true)
delayedState = null
}
for (runnable in delayedActions) {
editor.scrollingModel.disableAnimation()
runnable.run()
}
delayedActions.clear()
editor.scrollingModel.enableAnimation()
EditorNotifications.getInstance(project).updateNotifications(textEditor.myFile)
}
fun getEditorState(level: FileEditorStateLevel): TextEditorState {
ApplicationManager.getApplication().assertIsDispatchThread()
val state = provider.getStateImpl(project, editor, level)
val delayedState = delayedState
if (!isDone && delayedState != null) {
state.setDelayedFoldState { delayedState.foldingState }
}
return state
}
fun setEditorState(state: TextEditorState, exactState: Boolean) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (!isDone) {
delayedState = state
}
provider.setStateImpl(project, editor, state, exactState)
}
} | apache-2.0 | 82463ed124f942aa530afa6f2173be2d | 37.569444 | 142 | 0.710924 | 4.826188 | false | false | false | false |
vhromada/Catalog | web/src/test/kotlin/com/github/vhromada/catalog/web/mapper/GameMapperTest.kt | 1 | 1322 | package com.github.vhromada.catalog.web.mapper
import com.github.vhromada.catalog.web.CatalogWebMapperTestConfiguration
import com.github.vhromada.catalog.web.utils.GameUtils
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* A class represents test for mapper for games.
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [CatalogWebMapperTestConfiguration::class])
class GameMapperTest {
/**
* Instance of [GameMapper]
*/
@Autowired
private lateinit var mapper: GameMapper
/**
* Test method for [GameMapper.map].
*/
@Test
fun map() {
val game = GameUtils.getGame()
val result = mapper.map(source = game)
GameUtils.assertGameDeepEquals(expected = game, actual = result)
}
/**
* Test method for [GameMapper.mapRequest].
*/
@Test
fun mapRequest() {
val gameFO = GameUtils.getGameFO()
val result = mapper.mapRequest(source = gameFO)
GameUtils.assertRequestDeepEquals(expected = gameFO, actual = result)
}
}
| mit | e8dbbdd6370cb829414575f5fb185c9c | 25.44 | 77 | 0.713313 | 4.183544 | false | true | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/injection/course_revenue/CourseRevenuePresentationModule.kt | 1 | 3713 | package org.stepik.android.view.injection.course_revenue
import androidx.lifecycle.ViewModel
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import org.stepik.android.presentation.base.injection.ViewModelKey
import org.stepik.android.presentation.course_revenue.CourseBenefitSummaryFeature
import org.stepik.android.presentation.course_revenue.CourseRevenueFeature
import org.stepik.android.presentation.course_revenue.CourseBenefitsFeature
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature
import org.stepik.android.presentation.course_revenue.CourseRevenueViewModel
import org.stepik.android.presentation.course_revenue.dispatcher.CourseBenefitSummaryActionDispatcher
import org.stepik.android.presentation.course_revenue.dispatcher.CourseBenefitsActionDispatcher
import org.stepik.android.presentation.course_revenue.dispatcher.CourseBenefitsMonthlyActionDispatcher
import org.stepik.android.presentation.course_revenue.dispatcher.CourseRevenueActionDispatcher
import org.stepik.android.presentation.course_revenue.reducer.CourseRevenueReducer
import ru.nobird.app.core.model.safeCast
import ru.nobird.app.presentation.redux.container.wrapWithViewContainer
import ru.nobird.app.presentation.redux.dispatcher.transform
import ru.nobird.app.presentation.redux.dispatcher.wrapWithActionDispatcher
import ru.nobird.app.presentation.redux.feature.ReduxFeature
@Module
object CourseRevenuePresentationModule {
/**
* Presentation
*/
@Provides
@IntoMap
@ViewModelKey(CourseRevenueViewModel::class)
internal fun provideCourseBenefitsPresenter(
courseRevenueReducer: CourseRevenueReducer,
courseRevenueActionDispatcher: CourseRevenueActionDispatcher,
courseBenefitSummaryActionDispatcher: CourseBenefitSummaryActionDispatcher,
courseBenefitsActionDispatcher: CourseBenefitsActionDispatcher,
courseBenefitsMonthlyActionDispatcher: CourseBenefitsMonthlyActionDispatcher
): ViewModel =
CourseRevenueViewModel(
ReduxFeature(CourseRevenueFeature.State(
courseRevenueState = CourseRevenueFeature.CourseRevenueState.Idle,
courseBenefitSummaryState = CourseBenefitSummaryFeature.State.Loading,
courseBenefitsState = CourseBenefitsFeature.State.Loading,
courseBenefitsMonthlyState = CourseBenefitsMonthlyFeature.State.Loading
), courseRevenueReducer)
.wrapWithActionDispatcher(courseRevenueActionDispatcher)
.wrapWithActionDispatcher(
courseBenefitSummaryActionDispatcher.transform(
transformAction = { it.safeCast<CourseRevenueFeature.Action.CourseBenefitSummaryAction>()?.action },
transformMessage = CourseRevenueFeature.Message::CourseBenefitSummaryMessage
)
)
.wrapWithActionDispatcher(
courseBenefitsActionDispatcher.transform(
transformAction = { it.safeCast<CourseRevenueFeature.Action.CourseBenefitsAction>()?.action },
transformMessage = CourseRevenueFeature.Message::CourseBenefitsMessage
)
)
.wrapWithActionDispatcher(
courseBenefitsMonthlyActionDispatcher.transform(
transformAction = { it.safeCast<CourseRevenueFeature.Action.CourseBenefitsMonthlyAction>()?.action },
transformMessage = CourseRevenueFeature.Message::CourseBenefitsMonthlyMessage
)
)
.wrapWithViewContainer()
)
} | apache-2.0 | 8447fba6c576081fcb615270c70cfd78 | 54.432836 | 125 | 0.748182 | 5.819749 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ide/gdpr/ui/HtmlRtfPaneConverter.kt | 1 | 5434 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.gdpr.ui
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.nodes.TextNode
import java.awt.Cursor
import java.awt.Desktop
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.awt.event.MouseMotionListener
import java.net.URI
import javax.swing.JTextPane
import javax.swing.text.DefaultStyledDocument
/**
* This class creates a JTextPane with HTML content rendered by RTF. Only few HTML tags are supported.
*/
class HtmlRtfPane {
private val linkMap: MutableMap<IntRange, String> = mutableMapOf()
private val resultPane = JTextPane()
private val mouseMotionListenersList = mutableListOf<MouseMotionListener>()
private val mouseListenersList = mutableListOf<MouseListener>()
fun create(htmlText: String): JTextPane {
process(htmlText)
return resultPane
}
fun replaceText(newText: String): JTextPane {
resultPane.document.remove(0, resultPane.document.length)
clearMouseListeners()
process(newText)
return resultPane
}
private fun clearMouseListeners() {
mouseListenersList.forEach { resultPane.removeMouseListener(it) }
mouseListenersList.clear()
mouseMotionListenersList.forEach { resultPane.removeMouseMotionListener(it) }
mouseMotionListenersList.clear()
}
private fun process(htmlContent: String): DefaultStyledDocument {
val document = Jsoup.parse(htmlContent, "UTF-8")
val licenseContentNode = document.getElementsByAttributeValue("class", "licenseContent").firstOrNull()
?: document.body()
val styledDocument = resultPane.document as DefaultStyledDocument
licenseContentNode.children().forEach {
val style = when (it.tagName().toUpperCase()) {
"H1" -> Styles.H1
"H2" -> Styles.H2
"P" -> Styles.PARAGRAPH
else -> Styles.REGULAR
}
val start = styledDocument.length
styledDocument.insertString(styledDocument.length, it.text() + "\n", style)
styledDocument.setParagraphAttributes(start, it.text().length + 1, style, false)
if (it.tagName().toUpperCase() == "P") styleNodes(it, styledDocument, start, linkMap)
}
addHyperlinksListeners()
return styledDocument
}
private fun addHyperlinksListeners() {
val cursorListener = object : MouseAdapter() {
override fun mouseMoved(e: MouseEvent?) {
val location = e?.point?.location ?: return
if (linkMap.keys.any { it.contains(resultPane.viewToModel(location)) })
resultPane.cursor = Cursor(Cursor.HAND_CURSOR)
else
resultPane.cursor = Cursor(Cursor.DEFAULT_CURSOR)
}
}
val linkListener = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
if (e?.button == MouseEvent.BUTTON1) {
val location = e.point.location
val range = linkMap.keys.firstOrNull { it.contains(resultPane.viewToModel(location)) } ?: return
val link = linkMap[range] ?: return
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(URI(link))
}
}
}
}
resultPane.addMouseMotionListener(cursorListener)
mouseMotionListenersList.add(cursorListener)
resultPane.addMouseListener(linkListener)
mouseListenersList.add(linkListener)
}
private fun styleNodes(nodeElement: Element,
styledDocument: DefaultStyledDocument,
offsetInDocument: Int,
linkMap: MutableMap<IntRange, String>) {
var currentOffset = offsetInDocument
val style = when (nodeElement.tagName().toUpperCase()) {
"STRONG" -> Styles.BOLD
"A" -> {
val linkUrl = nodeElement.attr("href")
linkMap[IntRange(currentOffset, currentOffset + nodeElement.text().length + 1)] = linkUrl
Styles.LINK
}
"HINT" -> Styles.HINT
//"SUP" -> Styles.SUP don't use superscript due to IDEA-235457
"SUP" -> null
else -> Styles.REGULAR
}
if (style != null) {
styledDocument.setCharacterAttributes(offsetInDocument, nodeElement.text().length, style, false)
}
if (nodeElement.childNodes().isEmpty()) return
nodeElement.childNodes().forEach {
if (it is TextNode) {
//if first node starts with spaces.
val length: Int = if (it.siblingIndex() == 0) {
(nodeElement.textNodes()[0] as TextNode).text().trimIndent().length
} else {
it.text().length
}
currentOffset += length
}
if (it is Element) {
styleNodes(it, styledDocument, currentOffset, linkMap)
currentOffset += it.text().length
}
}
}
}
| apache-2.0 | 933c2a8473d3f6fc547d688b09c16739 | 39.251852 | 140 | 0.603055 | 4.83452 | false | false | false | false |
allotria/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenSetupProjectTest.kt | 2 | 2828 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.importing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.NonBlockingReadAction
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTest
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTestCase
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.idea.maven.MavenImportingTestCase
import org.jetbrains.idea.maven.importing.xml.MavenBuildFileBuilder
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.actions.AddFileAsMavenProjectAction
import org.jetbrains.idea.maven.project.actions.AddManagedFilesAction
import org.jetbrains.idea.maven.utils.MavenUtil.SYSTEM_ID
class MavenSetupProjectTest : ExternalSystemSetupProjectTest, MavenImportingTestCase() {
override fun getSystemId(): ProjectSystemId = SYSTEM_ID
override fun generateProject(id: String): ExternalSystemSetupProjectTestCase.ProjectInfo {
val name = "${System.currentTimeMillis()}-$id"
createProjectSubFile("$name-external-module/pom.xml", MavenBuildFileBuilder("$name-external-module").generate())
createProjectSubFile("$name-project/$name-module/pom.xml", MavenBuildFileBuilder("$name-module").generate())
val buildScript = MavenBuildFileBuilder("$name-project")
.withPomPackaging()
.withModule("$name-module")
.withModule("../$name-external-module")
.generate()
val projectFile = createProjectSubFile("$name-project/pom.xml", buildScript)
return ExternalSystemSetupProjectTestCase.ProjectInfo(projectFile, "$name-project", "$name-module", "$name-external-module")
}
override fun attachProject(project: Project, projectFile: VirtualFile) {
AddManagedFilesAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
}
override fun attachProjectFromScript(project: Project, projectFile: VirtualFile) {
AddFileAsMavenProjectAction().perform(project, selectedFile = projectFile)
waitForImportCompletion(project)
}
override fun <R> waitForImport(action: () -> R): R = action()
private fun waitForImportCompletion(project: Project) {
NonBlockingReadActionImpl.waitForAsyncTaskCompletion()
val projectManager = MavenProjectsManager.getInstance(project)
ApplicationManager.getApplication().invokeAndWait {
projectManager.waitForResolvingCompletion()
projectManager.performScheduledImportInTests()
}
}
} | apache-2.0 | 4434b33cd0342aaf68fcc2140d9244fa | 50.436364 | 140 | 0.804809 | 4.817717 | false | true | false | false |
aporter/coursera-android | ExamplesKotlin/UIDatePickerFragment/app/src/main/java/course/examples/ui/datepicker/DatePickerFragmentActivity.kt | 1 | 2942 | package course.examples.ui.datepicker
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.view.View
import android.widget.DatePicker
import android.widget.TextView
import java.util.*
class DatePickerFragmentActivity : FragmentActivity(), OnDateSetListener {
companion object {
private const val CURRENT_DATE_KEY = "CURRENT_DATE_KEY"
}
private lateinit var mDateDisplay: TextView
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
// Capture UI element
mDateDisplay = findViewById(R.id.dateDisplay)
setupUI(savedInstanceState)
}
private fun setupUI(savedInstanceState: Bundle?) {
if (null == savedInstanceState) {
mDateDisplay.setText(R.string.no_date_selected_string)
} else {
mDateDisplay.text = savedInstanceState.getCharSequence(CURRENT_DATE_KEY)
}
}
// OnClickListener for the "Change the Date" Button
fun buttonPressedCallback(v: View) {
// Create and display a new DatePickerFragment
DatePickerFragment().show(supportFragmentManager, "DatePicker")
}
// Callback called by DatePickerFragment when user sets the time
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
// Month is 0-based so add 1
mDateDisplay.text = StringBuilder()
.append(monthOfYear + 1).append("-").append(dayOfMonth).append("-")
.append(year).append(" ")
}
// Save instance state
public override fun onSaveInstanceState(bundle: Bundle) {
// CheckBox (checkedState, visibility)
bundle.putCharSequence(CURRENT_DATE_KEY, mDateDisplay.text)
// call superclass to save any view hierarchy
super.onSaveInstanceState(bundle)
}
// Date picking Fragment
class DatePickerFragment : android.support.v4.app.DialogFragment(), OnDateSetListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Set the current date in the DatePickerFragment
val cal = Calendar.getInstance()
// Create a new instance of DatePickerDialog and return it
return DatePickerDialog(
activity as Context, this,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
)
}
// Callback called by DatePickerDialog when user sets the time
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
(activity as OnDateSetListener).onDateSet(view, year, monthOfYear, dayOfMonth)
}
}
} | mit | b4db176270cbcdd8f6af37c45828a771 | 31.340659 | 96 | 0.676071 | 5.054983 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/activity/WelcomeActivity.kt | 1 | 15380 | /*
* Copyright (C) 2019 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils.loadAnimation
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.app.ActivityCompat.checkSelfPermission
import androidx.core.content.edit
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.preference.ListPreference
import androidx.preference.PreferenceFragmentCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.TransitionManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.floatingactionbutton.FloatingActionButton
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.activity.IntroductionFragmentStateAdapter.PageItem
import org.monora.uprotocol.client.android.app.Activity
import org.monora.uprotocol.client.android.databinding.LayoutProfileEditorBinding
import org.monora.uprotocol.client.android.databinding.LayoutSplashBinding
import org.monora.uprotocol.client.android.databinding.ListPermissionBinding
import org.monora.uprotocol.client.android.util.Permissions
import org.monora.uprotocol.client.android.util.Permissions.Permission
import org.monora.uprotocol.client.android.util.Resources.attrToRes
import org.monora.uprotocol.client.android.util.Resources.resToColor
import org.monora.uprotocol.client.android.viewmodel.UserProfileViewModel
@AndroidEntryPoint
class WelcomeActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (hasIntroductionShown()) {
finish()
}
setContentView(R.layout.activity_welcome)
skipPermissionRequest = true
welcomePageDisallowed = true
val titleContainer: FrameLayout = findViewById(R.id.titleContainer)
val titleText: TextView = findViewById(R.id.title)
val nextButton: FloatingActionButton = findViewById(R.id.nextButton)
val previousButton: AppCompatImageView = findViewById(R.id.previousButton)
val progressBar = findViewById<ProgressBar>(R.id.progressBar)
val viewPager = findViewById<ViewPager2>(R.id.activity_welcome_view_pager)
val appliedColor: Int = R.attr.colorSecondary.attrToRes(this).resToColor(this)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
val wrapDrawable: Drawable = DrawableCompat.wrap(progressBar.progressDrawable)
DrawableCompat.setTint(wrapDrawable, appliedColor)
progressBar.progressDrawable = DrawableCompat.unwrap(wrapDrawable)
} else {
progressBar.progressTintList = ColorStateList.valueOf(appliedColor)
}
val adapter = IntroductionFragmentStateAdapter(this, supportFragmentManager, lifecycle)
adapter.add(PageItem(getString(R.string.welcome), IntroductionSplashFragment::class.java.name))
val permissionPosition = adapter.itemCount
if (Build.VERSION.SDK_INT >= 23) adapter.add(
PageItem(getString(R.string.introduction_set_up_permissions), IntroductionPermissionFragment::class.java.name)
)
adapter.add(PageItem(getString(R.string.introduction_set_up_profile), IntroductionProfileFragment::class.java.name))
adapter.add(PageItem(getString(R.string.introduction_personalize), IntroductionPrefsFragment::class.java.name))
adapter.add(PageItem(getString(R.string.introduction_finished), IntroductionAllSetFragment::class.java.name))
progressBar.max = (adapter.itemCount - 1) * 100
previousButton.setOnClickListener {
if (viewPager.currentItem - 1 >= 0) {
viewPager.setCurrentItem(viewPager.currentItem - 1, true)
}
}
nextButton.setOnClickListener {
if (viewPager.currentItem + 1 < adapter.itemCount) {
viewPager.currentItem = viewPager.currentItem + 1
} else {
if (Permissions.checkRunningConditions(applicationContext)) {
// end presentation
defaultPreferences.edit {
putBoolean("introduction_shown", true)
}
backend.ensureStartedAfterWelcoming()
startActivity(Intent(this@WelcomeActivity, HomeActivity::class.java))
finish()
} else {
viewPager.setCurrentItem(permissionPosition, true)
Toast.makeText(this, R.string.warning_permissions_not_accepted, Toast.LENGTH_LONG).show()
}
}
}
viewPager.registerOnPageChangeCallback(
object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
progressBar.progress = position * 100 + (positionOffset * 100).toInt()
if (position == 0) {
progressBar.alpha = positionOffset
previousButton.alpha = positionOffset
titleText.alpha = positionOffset
} else {
progressBar.alpha = 1.0f
previousButton.alpha = 1.0f
titleText.alpha = 1.0f
}
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
val lastPage = position == adapter.itemCount - 1
TransitionManager.beginDelayedTransition(titleContainer)
titleText.text = adapter.getItem(position).title
progressBar.visibility = if (lastPage) View.GONE else View.VISIBLE
nextButton.setImageResource(
if (lastPage) {
R.drawable.ic_check_white_24dp
} else {
R.drawable.ic_navigate_next_white_24dp
}
)
}
}
)
viewPager.adapter = adapter
}
}
class IntroductionSplashFragment : Fragment(R.layout.layout_splash) {
private lateinit var binding: LayoutSplashBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = LayoutSplashBinding.bind(view)
}
override fun onResume() {
super.onResume()
slideSplashView()
}
private fun slideSplashView() {
val context = context ?: return
binding.logo.animation = loadAnimation(context, R.anim.enter_from_bottom_centered)
binding.appBrand.animation = loadAnimation(context, R.anim.enter_from_bottom)
binding.welcomeText.animation = loadAnimation(context, android.R.anim.fade_in).also { it.startOffset = 1000 }
}
}
class IntroductionPermissionFragment : Fragment(R.layout.layout_permissions) {
private val requestPermissions = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
updatePermissionsState()
}
private val adapter = PermissionsAdapter {
requestPermissions.launch(it.perm.id)
}.apply {
setHasStableIds(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.adapter = adapter
updatePermissionsState()
}
override fun onResume() {
super.onResume()
updatePermissionsState()
}
private fun updatePermissionsState() {
adapter.submitList(
Permissions.getAll().map {
CheckedPermission(it, checkSelfPermission(requireContext(), it.id) == PERMISSION_GRANTED)
}
)
}
}
@AndroidEntryPoint
class IntroductionProfileFragment : Fragment(R.layout.layout_set_up_profile) {
private val viewModel: UserProfileViewModel by viewModels()
private val pickPhoto = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
if (uri != null) {
viewModel.saveProfilePicture(uri)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = LayoutProfileEditorBinding.bind(view.findViewById(R.id.profile_editor))
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
binding.pickPhotoClickListener = View.OnClickListener {
pickPhoto.launch("image/*")
}
binding.executePendingBindings()
}
}
class IntroductionPrefsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preference_introduction_look)
loadThemeOptionsTo(requireContext(), findPreference("theme"))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listView.layoutParams = FrameLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
gravity = Gravity.CENTER_VERTICAL
}
}
companion object {
fun loadThemeOptionsTo(context: Context, themePreference: ListPreference?) {
if (themePreference == null) return
val valueList: MutableList<String> = arrayListOf("light", "dark")
val titleList: MutableList<String> = arrayListOf(
context.getString(R.string.light_theme),
context.getString(R.string.dark_theme)
)
if (Build.VERSION.SDK_INT >= 26) {
valueList.add("system")
titleList.add(context.getString(R.string.follow_system_theme))
} else if (Build.VERSION.SDK_INT >= 21) {
valueList.add("battery")
titleList.add(context.getString(R.string.battery_saver_theme))
}
themePreference.entries = titleList.toTypedArray()
themePreference.entryValues = valueList.toTypedArray()
}
}
}
class IntroductionAllSetFragment : Fragment(R.layout.layout_introduction_all_set)
class IntroductionFragmentStateAdapter(
val context: Context, fm: FragmentManager, lifecycle: Lifecycle,
) : FragmentStateAdapter(fm, lifecycle) {
private val fragments: MutableList<PageItem> = ArrayList()
private val fragmentFactory: FragmentFactory = fm.fragmentFactory
fun add(fragment: PageItem) {
fragments.add(fragment)
}
override fun createFragment(position: Int): Fragment {
val item = getItem(position)
val fragment = item.fragment ?: fragmentFactory.instantiate(context.classLoader, item.clazz)
item.fragment = fragment
return fragment
}
override fun getItemCount(): Int = fragments.size
override fun getItemId(position: Int): Long {
return position.toLong()
}
fun getItem(position: Int): PageItem = synchronized(fragments) { fragments[position] }
@Parcelize
data class PageItem(var title: String, var clazz: String) : Parcelable {
@IgnoredOnParcel
var fragment: Fragment? = null
}
}
class PermissionContentViewModel(permission: CheckedPermission) {
val title = permission.perm.title
val description = permission.perm.description
val granted = permission.granted
}
data class CheckedPermission(val perm: Permission, val granted: Boolean)
class PermissionItemCallback : DiffUtil.ItemCallback<CheckedPermission>() {
override fun areItemsTheSame(oldItem: CheckedPermission, newItem: CheckedPermission): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: CheckedPermission, newItem: CheckedPermission): Boolean {
return oldItem != newItem
}
}
class PermissionViewHolder(
private val clickListener: (CheckedPermission) -> Unit,
private val binding: ListPermissionBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(permission: CheckedPermission) {
binding.viewModel = PermissionContentViewModel(permission)
binding.button.setOnClickListener {
clickListener(permission)
}
binding.executePendingBindings()
}
}
class PermissionsAdapter(
private val clickListener: (CheckedPermission) -> Unit,
) : ListAdapter<CheckedPermission, PermissionViewHolder>(PermissionItemCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PermissionViewHolder {
return PermissionViewHolder(
clickListener,
ListPermissionBinding.inflate(LayoutInflater.from(parent.context), parent, false),
)
}
override fun onBindViewHolder(holder: PermissionViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun getItemId(position: Int): Long {
return getItem(position).perm.id.hashCode().toLong()
}
override fun getItemViewType(position: Int): Int {
return VIEW_TYPE_PERMISSION
}
companion object {
private const val VIEW_TYPE_PERMISSION = 0
}
}
| gpl-2.0 | 8c687a22b3bad441b221587986e895e2 | 37.934177 | 124 | 0.693673 | 5.07223 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/pickclient/BarcodeScannerFragment.kt | 1 | 14808 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment.pickclient
import android.Manifest.permission.*
import android.content.BroadcastReceiver
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.checkSelfPermission
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.genonbeta.android.framework.ui.callback.SnackbarPlacementProvider
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.monora.android.codescanner.CodeScanner
import org.monora.uprotocol.client.android.NavPickClientDirections
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.config.Keyword
import org.monora.uprotocol.client.android.databinding.LayoutBarcodeScannerBinding
import org.monora.uprotocol.client.android.model.NetworkDescription
import org.monora.uprotocol.client.android.util.Activities
import org.monora.uprotocol.client.android.util.Connections
import org.monora.uprotocol.client.android.util.InetAddresses
import org.monora.uprotocol.client.android.viewmodel.ClientPickerViewModel
import org.monora.uprotocol.client.android.viewmodel.SharedTextsViewModel
import org.monora.uprotocol.core.CommunicationBridge
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.ConnectionFactory
import java.net.InetAddress
import java.net.UnknownHostException
import javax.inject.Inject
@AndroidEntryPoint
class BarcodeScannerFragment : Fragment(R.layout.layout_barcode_scanner) {
private val clientPickerViewModel: ClientPickerViewModel by activityViewModels()
private val sharedTextsViewModel: SharedTextsViewModel by viewModels()
private val viewModel: BarcodeScannerViewModel by viewModels()
private val requestPermissions = registerForActivityResult(RequestMultiplePermissions()) {
emitState()
if ((it[ACCESS_FINE_LOCATION] == true || it[ACCESS_COARSE_LOCATION] == true)
&& !connections.isLocationServiceEnabled()
) {
Activities.startLocationServiceSettings(requireContext())
}
}
private val connections by lazy {
Connections(requireContext())
}
private val intentFilter by lazy {
IntentFilter().apply {
addAction(ConnectivityManager.CONNECTIVITY_ACTION)
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
addAction(LocationManager.PROVIDERS_CHANGED_ACTION)
}
}
private val binding by lazy {
LayoutBarcodeScannerBinding.bind(requireView())
}
private val scanner by lazy {
CodeScanner(
requireContext(), binding.barcodeView, {
lifecycleScope.launch {
handleBarcode(it.text)
}
}
)
}
private val state = MutableLiveData<Change>()
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (WifiManager.WIFI_STATE_CHANGED_ACTION == intent.action
|| ConnectivityManager.CONNECTIVITY_ACTION == intent.action
|| LocationManager.PROVIDERS_CHANGED_ACTION == intent.action
) {
emitState()
}
}
}
private val requestPermissionsClickListener = View.OnClickListener {
state.value?.let {
if (!it.camera) {
requestPermissions.launch(arrayOf(CAMERA))
} else if (!it.location) {
connections.validateLocationAccessNoPrompt(requestPermissions)
} else if (!it.wifi) {
connections.turnOnWiFi(snackbarPlacementProvider)
}
}
}
private val snackbarPlacementProvider = SnackbarPlacementProvider { resId, objects ->
return@SnackbarPlacementProvider view?.let {
Snackbar.make(it, getString(resId, objects), Snackbar.LENGTH_LONG).addCallback(
object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
scanner.startPreview()
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
resumeIfPossible()
}
}
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
viewModel.requestPermissionsClickListener = requestPermissionsClickListener
binding.executePendingBindings()
state.observe(viewLifecycleOwner) {
viewModel.needsAccess.set(!it.camera || !it.location || !it.wifi)
with(viewModel) {
if (!it.camera) {
stateImage.set(R.drawable.ic_camera_white_144dp)
stateText.set(getString(R.string.camera_permission_notice))
stateButtonText.set(getString(R.string.request))
} else if (!it.location) {
stateImage.set(R.drawable.ic_round_location_off_144)
if (!connections.hasLocationPermission()) {
stateText.set(getString(R.string.location_permission_required_notice))
stateButtonText.set(getString(R.string.allow))
} else {
stateText.set(getString(R.string.location_service_disabled_notice))
stateButtonText.set(getString(R.string.enable))
}
} else if (!it.wifi) {
stateImage.set(R.drawable.ic_signal_wifi_off_white_144dp)
stateText.set(getString(R.string.wifi_disabled_notice))
stateButtonText.set(getString(R.string.enable))
}
}
if (viewModel.needsAccess.get()) {
scanner.releaseResources()
} else {
scanner.startPreview()
}
}
viewModel.state.observe(viewLifecycleOwner) {
when (it) {
is State.Scan -> {
}
is State.Error -> {
Toast.makeText(context, "Error ${it.e.message}", Toast.LENGTH_LONG).show()
}
is State.Result -> {
clientPickerViewModel.bridge.postValue(it.bridge)
findNavController().navigate(NavPickClientDirections.xmlPop())
}
is State.Running -> {
}
}
if (it.running) {
scanner.startPreview()
} else {
resumeIfPossible()
}
}
setFragmentResultListener(WifiConnectFragment.REQUEST_INET_ADDRESS) { _: String, bundle: Bundle ->
val inetAddress = bundle.getSerializable(WifiConnectFragment.EXTRA_INET_ADDRESS) as InetAddress?
val pin = bundle.getInt(WifiConnectFragment.EXTRA_PIN, 0)
if (inetAddress != null) {
viewModel.consume(inetAddress, pin)
}
}
}
override fun onResume() {
super.onResume()
requireContext().registerReceiver(receiver, intentFilter)
emitState()
resumeIfPossible()
}
override fun onPause() {
super.onPause()
requireContext().unregisterReceiver(receiver)
scanner.releaseResources()
}
fun emitState() {
state.postValue(
Change(
connections.canAccessLocation(),
connections.wifiManager.isWifiEnabled,
checkSelfPermission(requireContext(), CAMERA) == PERMISSION_GRANTED
)
)
}
@Synchronized
private fun handleBarcode(code: String) {
try {
val values: Array<String> = code.split(";".toRegex()).toTypedArray()
// empty-strings cause trouble and are harder to manage.
when (values[0]) {
Keyword.QR_CODE_TYPE_HOTSPOT -> {
val pin = values[1].toInt()
val ssid = values[2]
val bssid = values[3].takeIf { it.isNotEmpty() }
val password = values[4]
val description = NetworkDescription(ssid, bssid, password)
if (!connections.isConnectedToNetwork(description)) {
findNavController().navigate(
BarcodeScannerFragmentDirections.actionBarcodeScannerFragmentToWifiConnectFragment(
description, pin
)
)
} else {
val hostAddress = InetAddresses.from(connections.wifiManager.dhcpInfo.gateway)
viewModel.consume(hostAddress, pin)
}
}
Keyword.QR_CODE_TYPE_WIFI -> {
val pin = values[1].toInt()
val ssid = values[2]
val bssid = values[3]
val ip = values[4]
viewModel.consume(InetAddress.getByName(ip), pin)
}
else -> throw Exception("Request is unknown")
}
} catch (e: UnknownHostException) {
snackbarPlacementProvider.createSnackbar(R.string.error_unknown_host)?.show()
} catch (e: Exception) {
e.printStackTrace()
AlertDialog.Builder(requireActivity())
.setTitle(R.string.unrecognized_qr_code_notice)
.setMessage(code)
.setNegativeButton(R.string.close, null)
.setPositiveButton(android.R.string.copy) { _: DialogInterface?, _: Int ->
(context?.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager?)?.let {
it.setPrimaryClip(ClipData.newPlainText("copiedText", code))
snackbarPlacementProvider.createSnackbar(R.string.copy_text_to_clipboard_success)?.show()
}
}
.setOnDismissListener {
resumeIfPossible()
}
.show()
scanner.stopPreview()
}
}
private fun resumeIfPossible() {
state.value?.let {
if (it.camera && it.location && it.wifi) {
scanner.startPreview()
}
}
}
companion object {
private const val TAG = "BarcodeScannerFragment"
}
}
@HiltViewModel
class BarcodeScannerViewModel @Inject constructor(
private val connectionFactory: ConnectionFactory,
private val persistenceProvider: PersistenceProvider,
) : ViewModel() {
private val _state = MutableLiveData<State>(State.Scan())
private var _job: Job? = null
set(value) {
field = value
running.set(value != null)
}
val clickListener = View.OnClickListener {
_job?.cancel() ?: requestPermissionsClickListener?.onClick(it)
}
val needsAccess = ObservableBoolean(false)
var requestPermissionsClickListener: View.OnClickListener? = null
val running = ObservableBoolean(false)
val state = liveData {
emitSource(_state)
}
val stateButtonText = ObservableField<String>()
val stateImage = ObservableInt()
val stateText = ObservableField<String>()
@Synchronized
fun consume(inetAddress: InetAddress, pin: Int) = _job ?: viewModelScope.launch(Dispatchers.IO) {
try {
_state.postValue(State.Running())
val bridge = CommunicationBridge.Builder(connectionFactory, persistenceProvider, inetAddress).apply {
setPin(pin)
}.connect()
_state.postValue(State.Result(bridge))
} catch (e: Exception) {
_state.postValue(State.Error(e))
} finally {
_job = null
}
}.also { _job = it }
}
sealed class State(val running: Boolean) {
class Scan : State(false)
class Running : State(true)
class Error(val e: Exception) : State(false)
class Result(val bridge: CommunicationBridge) : State(false)
}
data class Change(val location: Boolean, val wifi: Boolean, val camera: Boolean)
| gpl-2.0 | f4501225601811309a8ba13282bdcbee | 36.0175 | 113 | 0.634092 | 5.139535 | false | false | false | false |
Polidea/Polithings | steppermotor/src/main/java/com/polidea/androidthings/driver/steppermotor/motor/MotorRunner.kt | 1 | 2444 | package com.polidea.androidthings.driver.steppermotor.motor
import com.polidea.androidthings.driver.steppermotor.Direction
import com.polidea.androidthings.driver.steppermotor.driver.StepDuration
import com.polidea.androidthings.driver.steppermotor.driver.StepperMotorDriver
import com.polidea.androidthings.driver.steppermotor.listener.StepsListener
abstract class MotorRunner (val motorDriver: StepperMotorDriver,
val steps: Int,
val direction: Direction,
val executionDurationNanos: Long) : Runnable {
var stepsListener: StepsListener? = null
var stepDurationNanos: Long = 0
var executionStartNanos: Long = 0
override fun run() {
stepsListener?.onStarted()
motorDriver.direction = direction
applyResolution()
stepDurationNanos = executionDurationNanos / steps.toLong()
executionStartNanos = System.nanoTime()
for (step in 1..steps) {
if (Thread.currentThread().isInterrupted) {
finishWithError(step, InterruptedException())
return
}
try {
motorDriver.performStep(getStepDuration(step))
} catch (e: InterruptedException) {
finishWithError(step, e)
return
}
}
stepsListener?.onFinishedSuccessfully()
}
abstract protected fun applyResolution()
private fun finishWithError(performedSteps: Int, exception: Exception)
= stepsListener?.onFinishedWithError(steps, performedSteps, exception)
private fun getStepDuration(stepNumber: Int): StepDuration {
val durationNanos = getStepFinishTimestamp(stepNumber) - System.nanoTime()
var millis = durationNanos / NANOS_IN_MILLISECOND
var nanos = durationNanos - (millis * NANOS_IN_MILLISECOND)
if (millis < 0 || millis == 0L && nanos < MIN_STEP_DURATION_NANOS) {
millis = 0L
nanos = MIN_STEP_DURATION_NANOS
}
return StepDuration(millis, nanos.toInt())
}
private fun getStepFinishTimestamp(stepNumber: Int): Long
= executionStartNanos + stepNumber.toLong() * stepDurationNanos
companion object {
private val NANOS_IN_MILLISECOND = 1000000L
private val MIN_STEP_DURATION_NANOS = 2000L
}
} | mit | 67848043867b0683790e5f660005253f | 39.081967 | 95 | 0.637889 | 5.112971 | false | false | false | false |
leafclick/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/issue/GradleDaemonStartupIssueChecker.kt | 1 | 4073 | // 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.issue
import com.intellij.build.BuildConsoleUtils.getMessageTitle
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.build.issue.quickfix.OpenFileQuickFix
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.util.PlatformUtils
import com.intellij.util.io.isFile
import org.gradle.initialization.BuildLayoutParameters
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.issue.quickfix.GradleSettingsQuickFix
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionErrorHandler.getRootCauseAndLocation
import org.jetbrains.plugins.gradle.settings.GradleSystemSettings
import org.jetbrains.plugins.gradle.util.GradleBundle
import java.nio.file.Paths
import java.util.*
import java.util.function.BiPredicate
/**
* This issue checker provides quick fixes to deal with known startup issues of the Gradle daemon.
*
* @author Vladislav.Soroka
*/
@ApiStatus.Experimental
class GradleDaemonStartupIssueChecker : GradleIssueChecker {
override fun check(issueData: GradleIssueData): BuildIssue? {
val rootCause = getRootCauseAndLocation(issueData.error).first
val rootCauseText = rootCause.toString()
if (!rootCauseText.startsWith("org.gradle.api.GradleException: Unable to start the daemon process.")) {
return null
}
// JDK compatibility issues should be handled by org.jetbrains.plugins.gradle.issue.IncompatibleGradleJdkIssueChecker
if(rootCauseText.contains("FAILURE: Build failed with an exception.")) {
return null
}
val quickFixDescription = StringBuilder()
val quickFixes = ArrayList<BuildIssueQuickFix>()
val projectGradleProperties = Paths.get(issueData.projectPath, "gradle.properties")
if (projectGradleProperties.isFile()) {
val openFileQuickFix = OpenFileQuickFix(projectGradleProperties, "org.gradle.jvmargs")
quickFixDescription.append(" - <a href=\"${openFileQuickFix.id}\">gradle.properties</a> in project root directory\n")
quickFixes.add(openFileQuickFix)
}
val gradleUserHomeDir = BuildLayoutParameters().gradleUserHomeDir
val commonGradleProperties = Paths.get(gradleUserHomeDir.path, "gradle.properties")
if (commonGradleProperties.isFile()) {
val openFileQuickFix = OpenFileQuickFix(commonGradleProperties, "org.gradle.jvmargs")
quickFixDescription.append(" - <a href=\"${openFileQuickFix.id}\">gradle.properties</a> in in GRADLE_USER_HOME directory\n")
quickFixes.add(openFileQuickFix)
}
val gradleVmOptions = GradleSystemSettings.getInstance().gradleVmOptions
if (!gradleVmOptions.isNullOrBlank() && "AndroidStudio" != PlatformUtils.getPlatformPrefix()) { // Android Studio doesn't have Gradle VM options setting
val gradleSettingsFix = GradleSettingsQuickFix(
issueData.projectPath, true,
BiPredicate { _, _ -> gradleVmOptions != GradleSystemSettings.getInstance().gradleVmOptions },
GradleBundle.message("gradle.settings.text.vm.options")
)
quickFixes.add(gradleSettingsFix)
quickFixDescription.append(" - <a href=\"${gradleSettingsFix.id}\">IDE Gradle VM options</a> \n")
}
val issueDescription = StringBuilder(rootCause.message)
if (quickFixDescription.isNotEmpty()) {
issueDescription.append("\n-----------------------\n")
issueDescription.append("Check the JVM arguments defined for the gradle process in:\n")
issueDescription.append(quickFixDescription)
}
val description = issueDescription.toString()
val title = getMessageTitle(description)
return object : BuildIssue {
override val title: String = title
override val description: String = description
override val quickFixes = quickFixes
override fun getNavigatable(project: Project): Navigatable? = null
}
}
}
| apache-2.0 | 0ac64594e211f8203834f58eee44c60a | 46.360465 | 156 | 0.762583 | 4.71412 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KReverseLinkedList.kt | 1 | 1291 | package me.consuegra.algorithms
import me.consuegra.datastructure.KListNode
import me.consuegra.datastructure.KStack
/**
* Implement an algorithm to return a reverse1 of a given linked list
*/
class KReverseLinkedList {
fun <T> reverseOption1(input: KListNode<T>?): KListNode<T>? {
val stack = KStack<T>()
var head = input
while (head != null) {
stack.push(head.data)
head = head.next
}
var result: KListNode<T>? = null
while (!stack.isEmpty()) {
result = result?.append(stack.pop()) ?: KListNode(data = stack.pop())
}
return result
}
fun <T> reverseOption2(input: KListNode<T>?): KListNode<T>? {
var result: KListNode<T>? = null
var head = input
while (head != null) {
val current = head
head = head.next
current.next = result
result = current
}
return result
}
fun <T> reverseOptionRec(input: KListNode<T>?): KListNode<T>? {
if (input == null || input.next == null) {
return input
}
val head = input
val result = reverseOptionRec(input.next)
head.next?.next = head
head.next = null
return result
}
}
| mit | d175d31a8129de71ee90882a6a96256e | 25.346939 | 81 | 0.555383 | 4.177994 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/MainApplication.kt | 1 | 11977 | /*
* This file is part of Blokada.
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui
import android.app.Activity
import android.app.Service
import android.os.Build
import androidx.appcompat.app.AppCompatDelegate
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import blocka.LegacyAccountImport
import com.akexorcist.localizationactivity.ui.LocalizationApplication
import com.wireguard.android.backend.Backend
import com.wireguard.android.backend.GoBackend
import com.wireguard.android.configStore.FileConfigStore
import com.wireguard.android.model.TunnelManager
import com.wireguard.android.util.RootShell
import com.wireguard.android.util.ToolsInstaller
import com.wireguard.android.util.UserKnobs
import com.wireguard.android.util.applicationScope
import engine.EngineService
import engine.FilteringService
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import model.AppState
import model.BlockaConfig
import model.BlockaRepoConfig
import model.BlockaRepoPayload
import repository.Repos
import service.*
import ui.utils.cause
import utils.Logger
import java.lang.ref.WeakReference
import java.util.*
class MainApplication: LocalizationApplication(), ViewModelStoreOwner {
private lateinit var accountVM: AccountViewModel
private lateinit var tunnelVM: TunnelViewModel
private lateinit var settingsVM: SettingsViewModel
private lateinit var blockaRepoVM: BlockaRepoViewModel
private lateinit var statsVM: StatsViewModel
private lateinit var adsCounterVM: AdsCounterViewModel
private lateinit var networksVM: NetworksViewModel
private lateinit var packsVM: PacksViewModel
private lateinit var activationVM: ActivationViewModel
private val appRepo by lazy { Repos.app }
private val appUninstall = AppUninstallService()
override fun getViewModelStore() = MainApplication.viewModelStore
override fun onCreate() {
super.onCreate()
ContextService.setApp(this)
LogService.setup()
LegacyAccountImport.setup()
DozeService.setup(this)
wgOnCreate()
setupEvents()
MonitorService.setup(settingsVM.getUseForegroundService())
Repos.start()
}
private fun setupEvents() {
networksVM = ViewModelProvider(this).get(NetworksViewModel::class.java)
EngineService.setup(
network = networksVM.getActiveNetworkConfig(),
user = PersistenceService.load(BlockaConfig::class) // TODO: not nice
)
accountVM = ViewModelProvider(this).get(AccountViewModel::class.java)
tunnelVM = ViewModelProvider(this).get(TunnelViewModel::class.java)
settingsVM = ViewModelProvider(this).get(SettingsViewModel::class.java)
blockaRepoVM = ViewModelProvider(this).get(BlockaRepoViewModel::class.java)
statsVM = ViewModelProvider(this).get(StatsViewModel::class.java)
adsCounterVM = ViewModelProvider(this).get(AdsCounterViewModel::class.java)
packsVM = ViewModelProvider(this).get(PacksViewModel::class.java)
activationVM = ViewModelProvider(this).get(ActivationViewModel::class.java)
accountVM.account.observeForever { account ->
tunnelVM.checkConfigAfterAccountChanged(account)
}
settingsVM.localConfig.observeForever {
EnvironmentService.escaped = it.escaped
TranslationService.setLocale(it.locale)
ConnectivityService.pingToCheckNetwork = it.pingToCheckNetwork
tunnelVM.refreshStatus()
}
blockaRepoVM.repoConfig.observeForever {
maybePerformAction(it)
UpdateService.checkForUpdate(it)
if (ContextService.hasActivityContext())
UpdateService.showUpdateAlertIfNecessary(
libreMode = !(tunnelVM.config.value?.vpnEnabled ?: false)
)
else
UpdateService.showUpdateNotificationIfNecessary()
}
statsVM.history.observeForever {
// Not sure how it can be null, but there was a crash report
it?.let { history ->
MonitorService.setHistory(history)
}
}
statsVM.stats.observeForever {
// Not sure how it can be null, but there was a crash report
it?.let { stats ->
adsCounterVM.setRuntimeCounter(stats.denied.toLong())
}
}
adsCounterVM.counter.observeForever {
MonitorService.setCounter(it)
}
tunnelVM.tunnelStatus.observeForever {
MonitorService.setTunnelStatus(it)
}
networksVM.activeConfig.observeForever {
GlobalScope.launch {
try { EngineService.updateConfig(network = it) } catch (ex: Exception) {}
// Without the foreground service, we will get killed while switching the VPN.
// The simplest solution is to force the flag (which will apply from the next
// app start). Not the nicest though.
if (networksVM.hasCustomConfigs() && !settingsVM.getUseForegroundService())
settingsVM.setUseForegroundService(true)
}
}
ConnectivityService.setup()
GlobalScope.launch {
Services.payment.setup()
BlocklistService.setup()
packsVM.setup()
FilteringService.reload()
}
GlobalScope.launch { onAppStateChanged_updateMonitorService() }
GlobalScope.launch { onAppStateWorking_updateMonitorService() }
GlobalScope.launch { onAppStateActive_maybeUninstallOtherApps() }
checkOtherAppsInstalled()
Repos.account.hackyAccount()
}
private suspend fun onAppStateChanged_updateMonitorService() {
appRepo.appStateHot.collect {
MonitorService.setAppState(it)
}
}
private suspend fun onAppStateWorking_updateMonitorService() {
appRepo.workingHot.collect {
MonitorService.setWorking(it)
}
}
private suspend fun onAppStateActive_maybeUninstallOtherApps() {
appRepo.appStateHot.filter { it == AppState.Activated }
.collect {
appUninstall.maybePromptToUninstall()
}
}
private fun checkOtherAppsInstalled() {
if (appUninstall.hasOtherAppsInstalled()) {
Logger.w("Main", "Other Blokada versions detected on device")
}
}
private fun maybePerformAction(repo: BlockaRepoConfig) {
// TODO: Maybe this method should be extracted to some separate file
val log = Logger("Action")
val persistence = PersistenceService
repo.payload?.let { payload ->
val previousPayload = persistence.load(BlockaRepoPayload::class)
if (previousPayload == payload) {
// Act on each payload once, this one has been acted on before.
return
}
log.v("Got repo payload: ${payload.cmd}")
try {
startService(getIntentForCommand(payload.cmd))
} catch (ex: Exception) {
log.e("Could not act on payload".cause(ex))
}
log.v("Marking repo payload as acted on")
persistence.save(payload)
}
}
override fun getDefaultLanguage(): Locale {
return TranslationService.getLocale()
}
// Stuff taken from Wireguard
private val futureBackend = CompletableDeferred<Backend>()
private val coroutineScope = CoroutineScope(Job() + Dispatchers.Main.immediate)
private var backend: Backend? = null
private lateinit var rootShell: RootShell
private lateinit var preferencesDataStore: DataStore<Preferences>
private lateinit var toolsInstaller: ToolsInstaller
private lateinit var tunnelManager: TunnelManager
private suspend fun determineBackend(): Backend {
var backend: Backend? = null
// if (UserKnobs.enableKernelModule.first() && WgQuickBackend.hasKernelSupport()) {
// try {
// rootShell.start()
// val wgQuickBackend = WgQuickBackend(applicationContext, rootShell, toolsInstaller)
// wgQuickBackend.setMultipleTunnels(UserKnobs.multipleTunnels.first())
// backend = wgQuickBackend
// UserKnobs.multipleTunnels.onEach {
// wgQuickBackend.setMultipleTunnels(it)
// }.launchIn(coroutineScope)
// } catch (ignored: Exception) {
// }
// }
if (backend == null) {
backend = GoBackend(applicationContext)
GoBackend.setAlwaysOnCallback { get().applicationScope.launch { get().tunnelManager.restoreState(true) } }
}
return backend
}
private fun wgOnCreate() {
rootShell = RootShell(applicationContext)
toolsInstaller = ToolsInstaller(applicationContext, rootShell)
preferencesDataStore = PreferenceDataStoreFactory.create { applicationContext.preferencesDataStoreFile("settings") }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
coroutineScope.launch {
AppCompatDelegate.setDefaultNightMode(
if (UserKnobs.darkTheme.first()) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)
}
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
tunnelManager = TunnelManager(FileConfigStore(applicationContext))
tunnelManager.onCreate()
coroutineScope.launch(Dispatchers.IO) {
try {
backend = determineBackend()
futureBackend.complete(backend!!)
} catch (e: Throwable) {
Logger.e("Main", "Failed to determine wg backend".cause(e))
}
}
}
// override fun onTerminate() {
// coroutineScope.cancel()
// super.onTerminate()
// }
init {
weakSelf = WeakReference(this)
}
// Stuff taken from Wireguard
companion object {
private lateinit var weakSelf: WeakReference<MainApplication>
@JvmStatic
fun get(): MainApplication {
return weakSelf.get()!!
}
@JvmStatic
suspend fun getBackend() = get().futureBackend.await()
@JvmStatic
fun getRootShell() = get().rootShell
@JvmStatic
fun getPreferencesDataStore() = get().preferencesDataStore
@JvmStatic
fun getToolsInstaller() = get().toolsInstaller
@JvmStatic
fun getTunnelManager() = get().tunnelManager
@JvmStatic
fun getCoroutineScope() = get().coroutineScope
/**
* Not sure if doing it right, but some ViewModel in our app should be scoped to the
* application, since they are relevant for when the app is started by the SystemTunnel
* (as apposed to MainActivity). This probably would be solved better if some LiveData
* objects within some of the ViewModels would not be owned by them.
*/
val viewModelStore = ViewModelStore()
}
}
fun Activity.app(): MainApplication {
return application as MainApplication
}
fun Service.app(): MainApplication {
return application as MainApplication
} | mpl-2.0 | 14b50f8641538234691f5dfdd13bc628 | 35.404255 | 124 | 0.667919 | 4.936521 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/NotebookTabs.kt | 2 | 2090 | /*
* 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.notebooks.visualization.r.inlays.components
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.notebooks.visualization.r.VisualizationBundle
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JPanel
import javax.swing.JToggleButton
/**
* This component "installs" into bottom area of given FileEditor and allows us to add tabs with custom components under editor.
*/
class NotebookTabs private constructor(private val editor: BorderLayoutPanel) : JPanel() {
companion object {
fun install(editor: FileEditor): NotebookTabs? {
val component = editor.component
if (component !is BorderLayoutPanel)
return null
val componentLayout = component.layout as? BorderLayout
if (componentLayout == null) {
return null
}
val bottomComponent = componentLayout.getLayoutComponent(BorderLayout.SOUTH)
when (bottomComponent) {
null -> return NotebookTabs(component)
is NotebookTabs -> return bottomComponent
else -> return null
}
}
}
private val tabs = HashMap<JToggleButton, Component>()
init {
editor.addToBottom(this)
val center = (editor.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER)
addTab(VisualizationBundle.message("notebook.tabs.code.title"), center)
}
fun addTab(@Nls name: String, page: Component) {
val tab = JToggleButton(name)
val action = {
val currentCenter = (editor.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER)
if (currentCenter != page) {
editor.remove(currentCenter)
editor.add(page, BorderLayout.CENTER)
editor.repaint()
}
}
tab.addActionListener { action.invoke() }
tabs[tab] = page
action.invoke()
add(tab)
}
} | apache-2.0 | 02981604b7c24de4f890fa655ea06d7d | 27.256757 | 140 | 0.716746 | 4.50431 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/OwnedPet.kt | 1 | 943 | package com.habitrpg.android.habitica.models.user
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class OwnedPet : RealmObject(), OwnedObject {
@PrimaryKey
override var combinedKey: String? = null
override var userID: String? = null
set(value) {
field = value
combinedKey = field + key
}
override var key: String? = null
set(value) {
field = value
combinedKey = field + key
}
var trained = 0
override fun equals(other: Any?): Boolean {
return if (other?.javaClass == OwnedPet::class.java) {
this.combinedKey == (other as OwnedPet).combinedKey
} else super.equals(other)
}
override fun hashCode(): Int {
var result = combinedKey.hashCode()
result = 31 * result + userID.hashCode()
result = 31 * result + key.hashCode()
return result
}
}
| gpl-3.0 | 214bd47f05aaea6baa86dc355ae07aa4 | 25.194444 | 63 | 0.599152 | 4.448113 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/equipment/EquipmentOverviewView.kt | 1 | 2378 | package com.habitrpg.android.habitica.ui.views.equipment
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.EquipmentOverviewViewBinding
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.extensions.setScaledPadding
import com.habitrpg.android.habitica.models.user.Outfit
class EquipmentOverviewView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var onNavigate: ((String, String) -> Unit)? = null
private var binding: EquipmentOverviewViewBinding = EquipmentOverviewViewBinding.inflate(context.layoutInflater, this)
init {
background = context.getDrawable(R.drawable.layout_rounded_bg_gray_50)
setScaledPadding(context, 12, 12, 12 ,12)
orientation = VERTICAL
binding.weaponItem.setOnClickListener { onNavigate?.invoke("weapon", binding.weaponItem.identifier) }
binding.shieldItem.setOnClickListener { onNavigate?.invoke("shield", binding.shieldItem.identifier) }
binding.headItem.setOnClickListener { onNavigate?.invoke("head", binding.headItem.identifier) }
binding.armorItem.setOnClickListener { onNavigate?.invoke("armor", binding.armorItem.identifier) }
binding.headAccessoryItem.setOnClickListener { onNavigate?.invoke("headAccessory", binding.headAccessoryItem.identifier) }
binding.bodyItem.setOnClickListener { onNavigate?.invoke("body", binding.bodyItem.identifier) }
binding.backItem.setOnClickListener { onNavigate?.invoke("back", binding.backItem.identifier) }
binding.eyewearItem.setOnClickListener { onNavigate?.invoke("eyewear", binding.eyewearItem.identifier) }
}
fun updateData(outfit: Outfit, isWeaponTwoHanded: Boolean = false) {
binding.weaponItem.set(outfit.weapon, isWeaponTwoHanded)
binding.shieldItem.set(outfit.shield, false, isWeaponTwoHanded)
binding.headItem.set(outfit.head)
binding.armorItem.set(outfit.armor)
binding.headAccessoryItem.set(outfit.headAccessory)
binding.bodyItem.set(outfit.body)
binding.backItem.set(outfit.back)
binding.eyewearItem.set(outfit.eyeWear)
}
} | gpl-3.0 | 574b0e88a1c6023dbdc260c636c04bf3 | 51.866667 | 130 | 0.762826 | 4.261649 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutRow.kt | 2 | 24714 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout.migLayout
import com.intellij.icons.AllIcons
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.HideableTitledSeparator
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.TitledSeparator
import com.intellij.ui.UIBundle
import com.intellij.ui.components.DialogPanel
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import net.miginfocom.layout.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.*
import javax.swing.border.LineBorder
import javax.swing.text.JTextComponent
import kotlin.math.max
import kotlin.reflect.KMutableProperty0
internal class MigLayoutRow(private val parent: MigLayoutRow?,
override val builder: MigLayoutBuilder,
val labeled: Boolean = false,
val noGrid: Boolean = false,
private val indent: Int /* level number (nested rows) */,
private val incrementsIndent: Boolean = parent != null) : Row() {
companion object {
private const val COMPONENT_ENABLED_STATE_KEY = "MigLayoutRow.enabled"
private const val COMPONENT_VISIBLE_STATE_KEY = "MigLayoutRow.visible"
// as static method to ensure that members of current row are not used
private fun createCommentRow(parent: MigLayoutRow,
component: JComponent,
indent: Int,
isParentRowLabeled: Boolean,
forComponent: Boolean,
columnIndex: Int,
anchorComponent: JComponent? = null) {
val cc = CC()
val commentRow = parent.createChildRow()
commentRow.isComment = true
commentRow.addComponent(component, cc)
if (forComponent) {
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
cc.skip = columnIndex
}
else if (isParentRowLabeled) {
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
cc.skip()
}
else if (anchorComponent == null || anchorComponent is JToggleButton) {
cc.horizontal.gapBefore = gapToBoundSize(indent + parent.spacing.indentLevel, true)
}
else {
cc.horizontal.gapBefore = gapToBoundSize(indent, true)
}
}
// as static method to ensure that members of current row are not used
private fun configureSeparatorRow(row: MigLayoutRow, @NlsContexts.Separator title: String?) {
val separatorComponent = if (title == null) SeparatorComponent(0, OnePixelDivider.BACKGROUND, null) else TitledSeparator(title)
row.addTitleComponent(separatorComponent, isEmpty = title == null)
}
}
val components: MutableList<JComponent> = SmartList()
var rightIndex = Int.MAX_VALUE
private var lastComponentConstraintsWithSplit: CC? = null
private var columnIndex = -1
internal var subRows: MutableList<MigLayoutRow>? = null
private set
var gapAfter: String? = null
set(value) {
field = value
rowConstraints?.gapAfter = if (value == null) null else ConstraintParser.parseBoundSize(value, true, false)
}
var rowConstraints: DimConstraint? = null
private var componentIndexWhenCellModeWasEnabled = -1
private val spacing: SpacingConfiguration
get() = builder.spacing
private var isTrailingSeparator = false
private var isComment = false
@ApiStatus.ScheduledForRemoval
@Deprecated("Use Kotlin UI DSL Version 2")
override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) {
if (title != null) {
label(title)
gapAfter = "${spacing.radioGroupTitleVerticalGap}px!"
}
builder.withButtonGroup(buttonGroup, body)
}
override fun checkBoxGroup(title: String?, body: () -> Unit) {
if (title != null) {
label(title)
gapAfter = "${spacing.radioGroupTitleVerticalGap}px!"
}
body()
}
override var enabled = true
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
if (!value) {
if (!c.isEnabled) {
// current state of component differs from current row state - preserve current state to apply it when row state will be changed
c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, false)
}
}
else {
if (c.getClientProperty(COMPONENT_ENABLED_STATE_KEY) == false) {
// remove because for active row component state can be changed and we don't want to add listener to update value accordingly
c.putClientProperty(COMPONENT_ENABLED_STATE_KEY, null)
// do not set to true, preserve old component state
continue
}
}
c.isEnabled = value
}
}
override var visible = true
set(value) {
if (field == value) {
return
}
field = value
for ((index, c) in components.withIndex()) {
builder.componentConstraints[c]?.hideMode = if (index == components.size - 1 && value) 2 else 3
if (!value) {
c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, if (c.isVisible) null else false)
}
else {
if (c.getClientProperty(COMPONENT_VISIBLE_STATE_KEY) == false) {
c.putClientProperty(COMPONENT_VISIBLE_STATE_KEY, null)
continue
}
}
c.isVisible = value
}
}
override var subRowsEnabled = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach {
it.enabled = value
it.subRowsEnabled = value
}
components.firstOrNull()?.parent?.repaint() // Repaint all dependent components in sync
}
override var subRowsVisible = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach {
it.visible = value
it.subRowsVisible = value
if (it != subRows!!.last()) {
it.gapAfter = if (value) null else "0px!"
}
}
}
@Deprecated("Use Kotlin UI DSL Version 2")
override var subRowIndent: Int = -1
internal val isLabeledIncludingSubRows: Boolean
get() = labeled || (subRows?.any { it.isLabeledIncludingSubRows } ?: false)
internal val columnIndexIncludingSubRows: Int
get() = max(columnIndex, subRows?.asSequence()?.map { it.columnIndexIncludingSubRows }?.maxOrNull() ?: -1)
override fun createChildRow(label: JLabel?, isSeparated: Boolean, noGrid: Boolean, title: String?): MigLayoutRow {
return createChildRow(indent, label, isSeparated, noGrid, title)
}
private fun createChildRow(indent: Int,
label: JLabel? = null,
isSeparated: Boolean = false,
noGrid: Boolean = false,
@NlsContexts.Separator title: String? = null,
incrementsIndent: Boolean = true): MigLayoutRow {
val subRows = getOrCreateSubRowsList()
val newIndent = if (!this.incrementsIndent) indent else indent + spacing.indentLevel
val row = MigLayoutRow(this, builder,
labeled = label != null,
noGrid = noGrid,
indent = if (subRowIndent >= 0) subRowIndent * spacing.indentLevel else newIndent,
incrementsIndent = incrementsIndent)
if (isSeparated) {
val separatorRow = MigLayoutRow(this, builder, indent = newIndent, noGrid = true)
configureSeparatorRow(separatorRow, title)
separatorRow.enabled = subRowsEnabled
separatorRow.subRowsEnabled = subRowsEnabled
separatorRow.visible = subRowsVisible
separatorRow.subRowsVisible = subRowsVisible
row.getOrCreateSubRowsList().add(separatorRow)
}
var insertIndex = subRows.size
if (insertIndex > 0 && subRows[insertIndex-1].isTrailingSeparator) {
insertIndex--
}
if (insertIndex > 0 && subRows[insertIndex-1].isComment) {
insertIndex--
}
subRows.add(insertIndex, row)
row.enabled = subRowsEnabled
row.subRowsEnabled = subRowsEnabled
row.visible = subRowsVisible
row.subRowsVisible = subRowsVisible
if (label != null) {
row.addComponent(label)
}
return row
}
private fun <T : JComponent> addTitleComponent(titleComponent: T, isEmpty: Boolean) {
val cc = CC()
if (isEmpty) {
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false)
isTrailingSeparator = true
}
else {
// TitledSeparator doesn't grow by default opposite to SeparatorComponent
cc.growX()
}
addComponent(titleComponent, cc)
}
override fun titledRow(@NlsContexts.Separator title: String, init: Row.() -> Unit): Row {
return createBlockRow(title, true, init)
}
override fun blockRow(init: Row.() -> Unit): Row {
return createBlockRow(null, false, init)
}
private fun createBlockRow(@NlsContexts.Separator title: String?, isSeparated: Boolean, init: Row.() -> Unit): Row {
val parentRow = createChildRow(indent = indent, title = title, isSeparated = isSeparated, incrementsIndent = isSeparated)
parentRow.init()
val result = parentRow.createChildRow()
result.placeholder()
result.largeGapAfter()
return result
}
override fun hideableRow(title: String, incrementsIndent: Boolean, init: Row.() -> Unit): Row {
val titledSeparator = HideableTitledSeparator(title)
val separatorRow = createChildRow()
separatorRow.addTitleComponent(titledSeparator, isEmpty = false)
builder.hideableRowNestingLevel++
try {
val panelRow = createChildRow(indent, incrementsIndent = incrementsIndent)
panelRow.init()
titledSeparator.row = panelRow
titledSeparator.collapse()
return panelRow
}
finally {
builder.hideableRowNestingLevel--
}
}
override fun nestedPanel(title: String?, init: LayoutBuilder.() -> Unit): CellBuilder<DialogPanel> {
val nestedBuilder = createLayoutBuilder()
nestedBuilder.init()
val panel = DialogPanel(title, layout = null)
nestedBuilder.builder.build(panel, arrayOf())
builder.validateCallbacks.addAll(nestedBuilder.builder.validateCallbacks)
builder.componentValidateCallbacks.putAll(nestedBuilder.builder.componentValidateCallbacks)
mergeCallbacks(builder.customValidationRequestors, nestedBuilder.builder.customValidationRequestors)
mergeCallbacks(builder.applyCallbacks, nestedBuilder.builder.applyCallbacks)
mergeCallbacks(builder.resetCallbacks, nestedBuilder.builder.resetCallbacks)
mergeCallbacks(builder.isModifiedCallbacks, nestedBuilder.builder.isModifiedCallbacks)
lateinit var panelBuilder: CellBuilder<DialogPanel>
row {
panelBuilder = panel(CCFlags.growX)
}
return panelBuilder
}
private fun <K, V> mergeCallbacks(map: MutableMap<K, MutableList<V>>, nestedMap: Map<K, List<V>>) {
for ((requestor, callbacks) in nestedMap) {
map.getOrPut(requestor) { mutableListOf() }.addAll(callbacks)
}
}
private fun getOrCreateSubRowsList(): MutableList<MigLayoutRow> {
var subRows = subRows
if (subRows == null) {
// subRows in most cases > 1
subRows = ArrayList()
this.subRows = subRows
}
return subRows
}
// cell mode not tested with "gear" button, wait first user request
override fun setCellMode(value: Boolean, isVerticalFlow: Boolean, fullWidth: Boolean) {
if (value) {
assert(componentIndexWhenCellModeWasEnabled == -1)
componentIndexWhenCellModeWasEnabled = components.size
}
else {
val firstComponentIndex = componentIndexWhenCellModeWasEnabled
componentIndexWhenCellModeWasEnabled = -1
val componentCount = components.size - firstComponentIndex
if (componentCount == 0) return
val component = components.get(firstComponentIndex)
val cc = component.constraints
// do not add split if cell empty or contains the only component
if (componentCount > 1) {
cc.split(componentCount)
}
if (fullWidth) {
cc.spanX(LayoutUtil.INF)
}
if (isVerticalFlow) {
cc.flowY()
// because when vertical buttons placed near scroll pane, it wil be centered by baseline (and baseline not applicable for grow elements, so, will be centered)
cc.alignY("top")
}
}
}
override fun <T : JComponent> component(component: T): CellBuilder<T> {
addComponent(component)
return CellBuilderImpl(builder, this, component)
}
override fun <T : JComponent> component(component: T, viewComponent: JComponent): CellBuilder<T> {
addComponent(viewComponent)
return CellBuilderImpl(builder, this, component, viewComponent)
}
internal fun addComponent(component: JComponent, cc: CC = CC()) {
components.add(component)
builder.componentConstraints.put(component, cc)
if (!visible) {
component.isVisible = false
}
if (!enabled) {
component.isEnabled = false
}
if (!shareCellWithPreviousComponentIfNeeded(component, cc)) {
// increase column index if cell mode not enabled or it is a first component of cell
if (componentIndexWhenCellModeWasEnabled == -1 || componentIndexWhenCellModeWasEnabled == (components.size - 1)) {
columnIndex++
}
}
if (labeled && components.size == 2 && component.border is LineBorder) {
builder.componentConstraints.get(components.first())?.vertical?.gapBefore = builder.defaultComponentConstraintCreator.vertical1pxGap
}
if (component is JRadioButton) {
builder.topButtonGroup?.add(component)
}
builder.defaultComponentConstraintCreator.addGrowIfNeeded(cc, component, spacing)
if (!noGrid && indent > 0 && components.size == 1) {
cc.horizontal.gapBefore = gapToBoundSize(indent, true)
}
if (builder.hideableRowNestingLevel > 0) {
cc.hideMode = 3
}
// if this row is not labeled and:
// a. previous row is labeled and first component is a "Remember" checkbox, skip one column (since this row doesn't have a label)
// b. some previous row is labeled and first component is a checkbox, span (since this checkbox should span across label and content cells)
if (!labeled && components.size == 1 && component is JCheckBox) {
val siblings = parent!!.subRows
if (siblings != null && siblings.size > 1) {
if (siblings.get(siblings.size - 2).labeled && component.text == UIBundle.message("auth.remember.cb")) {
cc.skip(1)
cc.horizontal.gapBefore = BoundSize.NULL_SIZE
}
else if (siblings.any { it.labeled }) {
cc.spanX(2)
}
}
}
// MigLayout doesn't check baseline if component has grow
if (labeled && component is JScrollPane && component.viewport.view is JTextArea) {
val labelCC = components.get(0).constraints
labelCC.alignY("top")
val labelTop = component.border?.getBorderInsets(component)?.top ?: 0
if (labelTop != 0) {
labelCC.vertical.gapBefore = gapToBoundSize(labelTop, false)
}
}
}
private val JComponent.constraints: CC
get() = builder.componentConstraints.getOrPut(this) { CC() }
fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean) {
addCommentRow(comment, maxLineLength, forComponent, null)
}
// not using @JvmOverloads to maintain binary compatibility
fun addCommentRow(@Nls comment: String, maxLineLength: Int, forComponent: Boolean, anchorComponent: JComponent?) {
val commentComponent = ComponentPanelBuilder.createCommentComponent(comment, true, maxLineLength, true)
addCommentRow(commentComponent, forComponent, anchorComponent)
}
// not using @JvmOverloads to maintain binary compatibility
fun addCommentRow(component: JComponent, forComponent: Boolean) {
addCommentRow(component, forComponent, null)
}
fun addCommentRow(component: JComponent, forComponent: Boolean, anchorComponent: JComponent?) {
gapAfter = "${spacing.commentVerticalTopGap}px!"
val isParentRowLabeled = labeled
createCommentRow(this, component, indent, isParentRowLabeled, forComponent, columnIndex, anchorComponent)
}
private fun shareCellWithPreviousComponentIfNeeded(component: JComponent, componentCC: CC): Boolean {
if (components.size > 1 && component is JLabel && component.icon === AllIcons.General.GearPlain) {
componentCC.horizontal.gapBefore = builder.defaultComponentConstraintCreator.horizontalUnitSizeGap
if (lastComponentConstraintsWithSplit == null) {
val prevComponent = components.get(components.size - 2)
val prevCC = prevComponent.constraints
prevCC.split++
lastComponentConstraintsWithSplit = prevCC
}
else {
lastComponentConstraintsWithSplit!!.split++
}
return true
}
else {
lastComponentConstraintsWithSplit = null
return false
}
}
override fun alignRight() {
if (rightIndex != Int.MAX_VALUE) {
throw IllegalStateException("right allowed only once")
}
rightIndex = components.size
}
override fun largeGapAfter() {
gapAfter = "${spacing.largeVerticalGap}px!"
}
override fun createRow(label: String?): Row {
return createChildRow(label = label?.let { Label(it) })
}
override fun createNoteOrCommentRow(component: JComponent): Row {
val cc = CC()
cc.vertical.gapBefore = gapToBoundSize(if (subRows == null) spacing.verticalGap else spacing.largeVerticalGap, false)
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap, false)
val row = createChildRow(label = null, noGrid = true)
row.addComponent(component, cc)
return row
}
override fun radioButton(text: String, comment: String?): CellBuilder<JBRadioButton> {
val result = super.radioButton(text, comment)
attachSubRowsEnabled(result.component)
return result
}
override fun radioButton(text: String, prop: KMutableProperty0<Boolean>, comment: String?): CellBuilder<JBRadioButton> {
return super.radioButton(text, prop, comment).also { attachSubRowsEnabled(it.component) }
}
override fun onGlobalApply(callback: () -> Unit): Row {
builder.applyCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
override fun onGlobalReset(callback: () -> Unit): Row {
builder.resetCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
override fun onGlobalIsModified(callback: () -> Boolean): Row {
builder.isModifiedCallbacks.getOrPut(null, { SmartList() }).add(callback)
return this
}
private val labeledComponents = listOf(JTextComponent::class, JComboBox::class, JSpinner::class, JSlider::class)
/**
* Assigns next to label REASONABLE component with the label
*/
override fun row(label: JLabel?, separated: Boolean, init: Row.() -> Unit): Row {
val result = super.row(label, separated, init)
if (label != null && result is MigLayoutRow && result.components.size > 1) {
val component = result.components[1]
if (labeledComponents.any { clazz -> clazz.isInstance(component) }) {
label.labelFor = component
}
}
return result
}
}
private class CellBuilderImpl<T : JComponent>(
private val builder: MigLayoutBuilder,
private val row: MigLayoutRow,
override val component: T,
private val viewComponent: JComponent = component
) : CellBuilder<T>, CheckboxCellBuilder, ScrollPaneCellBuilder {
private var applyIfEnabled = false
private var property: GraphProperty<*>? = null
override fun withGraphProperty(property: GraphProperty<*>): CellBuilder<T> {
this.property = property
return this
}
override fun comment(text: String, maxLineLength: Int, forComponent: Boolean): CellBuilder<T> {
row.addCommentRow(text, maxLineLength, forComponent, viewComponent)
return this
}
@Deprecated("Use Kotlin UI DSL Version 2")
override fun commentComponent(component: JComponent, forComponent: Boolean): CellBuilder<T> {
row.addCommentRow(component, forComponent, viewComponent)
return this
}
override fun focused(): CellBuilder<T> {
builder.preferredFocusedComponent = viewComponent
return this
}
override fun withValidationOnApply(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> {
builder.validateCallbacks.add { callback(ValidationInfoBuilder(component.origin), component) }
return this
}
override fun withValidationOnInput(callback: ValidationInfoBuilder.(T) -> ValidationInfo?): CellBuilder<T> {
builder.componentValidateCallbacks[component.origin] = { callback(ValidationInfoBuilder(component.origin), component) }
property?.let { builder.customValidationRequestors.getOrPut(component.origin, { SmartList() }).add(it::afterPropagation) }
return this
}
override fun onApply(callback: () -> Unit): CellBuilder<T> {
builder.applyCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun onReset(callback: () -> Unit): CellBuilder<T> {
builder.resetCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun onIsModified(callback: () -> Boolean): CellBuilder<T> {
builder.isModifiedCallbacks.getOrPut(component, { SmartList() }).add(callback)
return this
}
override fun enabled(isEnabled: Boolean) {
viewComponent.isEnabled = isEnabled
}
override fun enableIf(predicate: ComponentPredicate): CellBuilder<T> {
viewComponent.isEnabled = predicate()
predicate.addListener { viewComponent.isEnabled = it }
return this
}
override fun visible(isVisible: Boolean) {
viewComponent.isVisible = isVisible
}
override fun visibleIf(predicate: ComponentPredicate): CellBuilder<T> {
viewComponent.isVisible = predicate()
predicate.addListener { viewComponent.isVisible = it }
return this
}
override fun applyIfEnabled(): CellBuilder<T> {
applyIfEnabled = true
return this
}
override fun shouldSaveOnApply(): Boolean {
return !(applyIfEnabled && !viewComponent.isEnabled)
}
@Deprecated("Use Kotlin UI DSL Version 2")
override fun actsAsLabel() {
builder.updateComponentConstraints(viewComponent) { spanX = 1 }
}
@Deprecated("Use Kotlin UI DSL Version 2")
override fun noGrowY() {
builder.updateComponentConstraints(viewComponent) {
growY(0.0f)
pushY(0.0f)
}
}
@Deprecated("Use Kotlin UI DSL Version 2, see Cell.widthGroup()")
override fun sizeGroup(name: String): CellBuilderImpl<T> {
builder.updateComponentConstraints(viewComponent) {
sizeGroup(name)
}
return this
}
@Deprecated("Use Kotlin UI DSL Version 2")
override fun growPolicy(growPolicy: GrowPolicy): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
builder.defaultComponentConstraintCreator.applyGrowPolicy(this, growPolicy)
}
return this
}
override fun constraints(vararg constraints: CCFlags): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
overrideFlags(this, constraints)
}
return this
}
override fun withLargeLeftGap(): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(builder.spacing.largeHorizontalGap, true)
}
return this
}
override fun withLeftGap(): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(builder.spacing.horizontalGap, true)
}
return this
}
override fun withLeftGap(gapLeft: Int): CellBuilder<T> {
builder.updateComponentConstraints(viewComponent) {
horizontal.gapBefore = gapToBoundSize(gapLeft, true)
}
return this
}
}
private val JComponent.origin: JComponent
get() {
return when (this) {
is TextFieldWithBrowseButton -> textField
else -> this
}
} | apache-2.0 | b6a9e1297ab49d0087d5e608840d7f0f | 33.7609 | 166 | 0.684713 | 4.786752 | false | false | false | false |
leafclick/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/project/impl/ProjectOpeningTest.kt | 1 | 5683 | // 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.project.impl
import com.intellij.configurationStore.StoreUtil
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
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.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.io.createDirectories
import junit.framework.TestCase
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
@Suppress("UsePropertyAccessSyntax")
class ProjectOpeningTest {
companion object {
@JvmStatic
internal fun closeProject(project: Project?) {
if (project != null && !project.isDisposed) {
ProjectManagerEx.getInstanceEx().forceCloseProject(project)
}
}
@ClassRule
@JvmField
val appRule = ApplicationRule()
}
@Rule
@JvmField
val disposableRule = DisposableRule()
@Rule
@JvmField
val tempDir = TemporaryDirectory()
@Test
fun openProjectCancelling() {
val activity = MyStartupActivity()
ExtensionTestUtil.maskExtensions(StartupActivity.POST_STARTUP_ACTIVITY, listOf(activity), disposableRule.disposable, fireEvents = false)
val manager = ProjectManagerEx.getInstanceEx()
val foo = tempDir.newPath()
val project = manager.createProject(null, foo.toString())!!
try {
ProgressManager.getInstance().run(object : Task.Modal(null, "", true) {
override fun run(indicator: ProgressIndicator) {
assertThat(manager.openProject(project)).isFalse()
}
})
assertThat(project.isOpen).isFalse()
// 1 on maskExtensions call, second call our call
assertThat(activity.passed.get()).isTrue()
}
finally {
runInEdtAndWait {
closeProject(project)
}
}
}
@Test
fun cancelOnLoadingModules() {
val foo = tempDir.newPath()
val manager: ProjectManagerEx? = ProjectManagerEx.getInstanceEx()
var project = manager!!.createProject(null, foo.toString())!!
try {
StoreUtil.saveSettings(project, false)
runInEdtAndWait {
closeProject(project)
}
ApplicationManager.getApplication().messageBus.connect(disposableRule.disposable).subscribe(ProjectLifecycleListener.TOPIC,
object : ProjectLifecycleListener {
override fun projectComponentsInitialized(project: Project) {
val indicator: ProgressIndicator? = ProgressManager.getInstance().progressIndicator
TestCase.assertNotNull(indicator)
indicator!!.cancel()
indicator.checkCanceled()
}
})
runInEdtAndWait {
project = manager.loadAndOpenProject(foo)!!
}
assertThat(project.isOpen).isFalse()
assertThat(project.isDisposed).isTrue()
}
finally {
runInEdtAndWait {
closeProject(project)
}
}
}
@Test
fun isSameProjectForDirectoryBasedProject() {
val projectDir = tempDir.newPath()
projectDir.createDirectories()
val dirBasedProject = ProjectManager.getInstance().createProject("project", projectDir.toAbsolutePath().toString())!!
Disposer.register(disposableRule.disposable, Disposable {
runInEdtAndWait { closeProject(dirBasedProject) }
})
assertThat(ProjectUtil.isSameProject(projectDir.toAbsolutePath().toString(), dirBasedProject)).isTrue()
assertThat(ProjectUtil.isSameProject(tempDir.newPath("project2").toAbsolutePath().toString(), dirBasedProject)).isFalse()
val iprFilePath = projectDir.resolve("project.ipr")
assertThat(ProjectUtil.isSameProject(iprFilePath.toAbsolutePath().toString(), dirBasedProject)).isTrue()
val miscXmlFilePath = projectDir.resolve(".idea/misc.xml")
assertThat(ProjectUtil.isSameProject(miscXmlFilePath.toAbsolutePath().toString(), dirBasedProject)).isTrue()
val someOtherFilePath = projectDir.resolve("misc.xml")
assertThat(ProjectUtil.isSameProject(someOtherFilePath.toAbsolutePath().toString(), dirBasedProject)).isFalse()
}
@Test
fun isSameProjectForFileBasedProject() {
val projectDir = tempDir.newPath()
projectDir.createDirectories()
val iprFilePath = projectDir.resolve("project.ipr")
val fileBasedProject = ProjectManager.getInstance().createProject(iprFilePath.fileName.toString(), iprFilePath.toAbsolutePath().toString())!!
Disposer.register(disposableRule.disposable, Disposable {
runInEdtAndWait { closeProject(fileBasedProject) }
})
assertThat(ProjectUtil.isSameProject(projectDir.toAbsolutePath().toString(), fileBasedProject)).isTrue()
assertThat(ProjectUtil.isSameProject(tempDir.newPath("project2").toAbsolutePath().toString(), fileBasedProject)).isFalse()
val iprFilePath2 = projectDir.resolve("project2.ipr")
assertThat(ProjectUtil.isSameProject(iprFilePath2.toAbsolutePath().toString(), fileBasedProject)).isFalse()
}
}
private class MyStartupActivity : StartupActivity.DumbAware {
val passed = AtomicBoolean()
override fun runActivity(project: Project) {
passed.set(true)
ProgressManager.getInstance().progressIndicator!!.cancel()
}
} | apache-2.0 | e5610d67541bdcc2dcfecb323180a5e6 | 37.147651 | 145 | 0.742566 | 5.002641 | false | true | false | false |
sewerk/Bill-Calculator | app/src/test/java/pl/srw/billcalculator/history/list/HistoryVMTest.kt | 1 | 1274 | package pl.srw.billcalculator.history.list
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import pl.srw.billcalculator.data.ApplicationRepo
import pl.srw.billcalculator.data.bill.HistoryRepo
import pl.srw.billcalculator.db.History
class HistoryVMTest {
@get:Rule val rule: TestRule = InstantTaskExecutorRule()
val historyData = MutableLiveData<List<History>>()
val applicationRepo: ApplicationRepo = mock()
val historyRepo: HistoryRepo = mock {
on { getAll() } doReturn historyData
}
val sut = HistoryVM(applicationRepo, historyRepo)
@Test fun `retrieve history data on construction`() {
verify(historyRepo).getAll()
}
@Test
fun `share history data when retirved from repository`() {
val observer: Observer<List<History>> = mock()
sut.data.observeForever(observer)
val data = emptyList<History>()
historyData.value = data
verify(observer).onChanged(data)
}
}
| mit | 4682621498593d003aa1b8a3ed8d8f86 | 29.333333 | 65 | 0.742543 | 4.304054 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/settings/StandaloneScriptsUIComponent.kt | 1 | 4711 | // 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.scripting.gradle.settings
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.table.JBTable
import com.intellij.ui.table.TableView
import com.intellij.util.ui.JBUI
import org.jetbrains.kotlin.idea.KotlinIdeaGradleBundle
import org.jetbrains.kotlin.idea.scripting.gradle.roots.GradleBuildRootsLocator
import org.jetbrains.kotlin.idea.scripting.gradle.roots.GradleBuildRootsManager
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.ListSelectionModel
import javax.swing.plaf.BorderUIResource
class StandaloneScriptsUIComponent(val project: Project) : UnnamedConfigurable {
private val fileChooser: FileChooserDescriptor = object : FileChooserDescriptor(
true, false, false,
false, false, true
) {
override fun isFileSelectable(file: VirtualFile): Boolean {
val rootsManager = GradleBuildRootsManager.getInstance(project)
val scriptUnderRoot = rootsManager?.findScriptBuildRoot(file)
val notificationKind = scriptUnderRoot?.notificationKind
return notificationKind == GradleBuildRootsLocator.NotificationKind.legacyOutside || notificationKind == GradleBuildRootsLocator.NotificationKind.notEvaluatedInLastImport
}
}
private var panel: JPanel? = null
private val scriptsFromStorage = StandaloneScriptsStorage.getInstance(project)?.files?.toList() ?: emptyList()
private val scriptsInTable = scriptsFromStorage.toMutableList()
private val table: JBTable
private val model: KotlinStandaloneScriptsModel
init {
model = KotlinStandaloneScriptsModel.createModel(scriptsInTable)
table = TableView(model)
table.preferredScrollableViewportSize = JBUI.size(300, -1)
table.selectionModel.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
model.addTableModelListener(table)
}
override fun reset() {
scriptsInTable.clear()
scriptsInTable.addAll(scriptsFromStorage)
model.items = scriptsInTable
}
override fun apply() {
GradleBuildRootsManager.getInstance(project)?.updateStandaloneScripts {
val previousScripts = scriptsFromStorage
scriptsInTable
.filterNot { previousScripts.contains(it) }
.forEach { addStandaloneScript(it) }
previousScripts
.filterNot { scriptsInTable.contains(it) }
.forEach { removeStandaloneScript(it) }
}
}
override fun createComponent(): JComponent? {
if (panel == null) {
val panel = JPanel(BorderLayout())
panel.border = BorderUIResource.TitledBorderUIResource(KotlinIdeaGradleBundle.message("standalone.scripts.settings.title"))
panel.add(
ToolbarDecorator.createDecorator(table)
.setAddAction { addScripts() }
.setRemoveAction { removeScripts() }
.setRemoveActionUpdater { table.selectedRow >= 0 }
.disableUpDownActions()
.createPanel()
)
this.panel = panel
}
return panel
}
override fun isModified(): Boolean {
return scriptsFromStorage != scriptsInTable
}
override fun disposeUIResources() {
panel = null
}
private fun addScripts() {
val chosen = FileChooser.chooseFiles(fileChooser, project, null)
for (chosenFile in chosen) {
val path = chosenFile.path
if (scriptsInTable.contains(path)) continue
scriptsInTable.add(path)
model.addRow(path)
}
}
private fun removeScripts() {
val selected = table.selectedRows
if (selected == null || selected.isEmpty()) {
return
}
for ((removedCount, indexToRemove) in selected.withIndex()) {
val row = indexToRemove - removedCount
scriptsInTable.removeAt(row)
model.removeRow(row)
}
IdeFocusManager.getGlobalInstance()
.doWhenFocusSettlesDown { IdeFocusManager.getGlobalInstance().requestFocus(table, true) }
}
} | apache-2.0 | a542045f5c394ba94d834b71260b125a | 36.696 | 182 | 0.688601 | 5.222838 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceCallChecker.kt | 1 | 1459 | // 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.debugger.sequence.psi.sequence
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
class SequenceCallChecker : StreamCallChecker {
override fun isIntermediateCall(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType() ?: return false
return isSequenceInheritor(receiverType) && isSequenceInheritor(expression.resolveType())
}
override fun isTerminationCall(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType() ?: return false
return isSequenceInheritor(receiverType) && !isSequenceInheritor(expression.resolveType())
}
private fun isSequenceInheritor(type: KotlinType): Boolean =
isSequenceType(type) || type.supertypes().any(this::isSequenceType)
private fun isSequenceType(type: KotlinType): Boolean =
"kotlin.sequences.Sequence" == KotlinPsiUtil.getTypeWithoutTypeParameters(type)
} | apache-2.0 | 27fde7d0d7c2cd135ed98c70f40e2e14 | 49.344828 | 158 | 0.787526 | 4.631746 | false | false | false | false |
jwren/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/actions/OpenFeaturesInScratchFileAction.kt | 1 | 5070 | package com.intellij.ide.actions.searcheverywhere.ml.actions
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManager
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlSessionService
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereTabWithMl
import com.intellij.ide.scratch.ScratchFileCreationHelper
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.json.JsonFileType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
class OpenFeaturesInScratchFileAction : AnAction() {
companion object {
private const val SHOULD_ORDER_BY_ML_KEY = "shouldOrderByMl"
private const val CONTEXT_INFO_KEY = "contextInfo"
private const val SEARCH_STATE_FEATURES_KEY = "searchStateFeatures"
private const val FOUND_ELEMENTS_KEY = "foundElements"
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = shouldActionBeEnabled(e)
}
private fun shouldActionBeEnabled(e: AnActionEvent): Boolean {
val seManager = SearchEverywhereManager.getInstance(e.project)
val session = SearchEverywhereMlSessionService.getService().getCurrentSession()
return e.project != null
&& seManager.isShown
&& session != null
&& session.getCurrentSearchState() != null
}
override fun actionPerformed(e: AnActionEvent) {
val searchEverywhereUI = SearchEverywhereManager.getInstance(e.project).currentlyShownUI
val report = getFeaturesReport(searchEverywhereUI)
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(report)
val context = createScratchFileContext(json)
val scratchFile = createNewJsonScratchFile(e.project!!, context)
openScratchFile(scratchFile, e.project!!)
}
private fun getFeaturesReport(searchEverywhereUI: SearchEverywhereUI): Map<String, Any> {
val mlSessionService = SearchEverywhereMlSessionService.getService()
val searchSession = mlSessionService.getCurrentSession()!!
val state = searchSession.getCurrentSearchState()
val features = searchEverywhereUI.foundElementsInfo.map { info ->
val rankingWeight = info.priority
val contributor = info.contributor.searchProviderId
val elementName = StringUtil.notNullize(info.element.toString(), "undefined")
val elementId = searchSession.itemIdProvider.getId(info.element)
if (elementId != null) {
val mlWeight = if (isTabWithMl(searchEverywhereUI.selectedTabID)) {
mlSessionService.getMlWeight(info.contributor, info.element, rankingWeight)
} else {
null
}
return@map ElementFeatures(
elementName,
mlWeight,
rankingWeight,
contributor,
state!!.getElementFeatures(elementId, info.element, info.contributor, rankingWeight).featuresAsMap().toSortedMap()
)
}
else {
return@map ElementFeatures(elementName, null, rankingWeight, contributor, emptyMap())
}
}
return mapOf(
SHOULD_ORDER_BY_ML_KEY to mlSessionService.shouldOrderByMl(searchEverywhereUI.selectedTabID),
CONTEXT_INFO_KEY to searchSession.cachedContextInfo.features.associate { it.field.name to it.data },
SEARCH_STATE_FEATURES_KEY to state!!.searchStateFeatures.associate { it.field.name to it.data },
FOUND_ELEMENTS_KEY to features
)
}
private fun isTabWithMl(tabId: String): Boolean {
return SearchEverywhereTabWithMl.findById(tabId) != null
}
private fun createScratchFileContext(json: String) = ScratchFileCreationHelper.Context().apply {
text = json
fileExtension = JsonFileType.DEFAULT_EXTENSION
createOption = ScratchFileService.Option.create_if_missing
}
private fun createNewJsonScratchFile(project: Project, context: ScratchFileCreationHelper.Context): VirtualFile {
val fileName = "search-everywhere-features.${context.fileExtension}"
return ScratchRootType.getInstance().createScratchFile(project, fileName, context.language, context.text, context.createOption)!!
}
private fun openScratchFile(file: VirtualFile, project: Project) {
FileEditorManager.getInstance(project).openFile(file, true)
}
@JsonPropertyOrder("name", "mlWeight", "rankingWeight", "contributor", "features")
private data class ElementFeatures(val name: String,
val mlWeight: Double?,
val rankingWeight: Int,
val contributor: String,
val features: Map<String, Any>)
} | apache-2.0 | c69a94b3b17847c6549eaf599de881d7 | 42.715517 | 133 | 0.741223 | 4.889103 | false | false | false | false |
BijoySingh/Quick-Note-Android | scarlet/src/main/java/com/bijoysingh/quicknote/database/RemoteUploadDatabase.kt | 1 | 671 | package com.bijoysingh.quicknote.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
var remoteDatabase: RemoteUploadDataDao? = null
fun genRemoteDatabase(context: Context): RemoteUploadDataDao? {
if (remoteDatabase === null) {
remoteDatabase = Room.databaseBuilder(context, RemoteUploadDatabase::class.java, "google_drive_db")
.fallbackToDestructiveMigration()
.build().remote()
}
return remoteDatabase
}
@Database(entities = [RemoteUploadData::class], version = 4)
abstract class RemoteUploadDatabase : RoomDatabase() {
abstract fun remote(): RemoteUploadDataDao
} | gpl-3.0 | 43b57f3fb9ca8df448018db33b5d81ad | 31 | 103 | 0.780924 | 4.385621 | false | false | false | false |
vhromada/Catalog | core/src/test/kotlin/com/github/vhromada/catalog/utils/ProgramUtils.kt | 1 | 15021 | package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.domain.filter.ProgramFilter
import com.github.vhromada.catalog.domain.io.ProgramStatistics
import com.github.vhromada.catalog.entity.ChangeProgramRequest
import com.github.vhromada.catalog.entity.Program
import com.github.vhromada.catalog.filter.NameFilter
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* Updates program fields.
*
* @return updated program
*/
fun com.github.vhromada.catalog.domain.Program.updated(): com.github.vhromada.catalog.domain.Program {
name = "Name"
normalizedName = "Name"
wikiEn = "enWiki"
wikiCz = "czWiki"
mediaCount = 1
format = "STEAM"
crack = true
serialKey = true
otherData = "Other data"
note = "Note"
return this
}
/**
* Updates program fields.
*
* @return updated program
*/
fun Program.updated(): Program {
return copy(
name = "Name",
wikiEn = "enWiki",
wikiCz = "czWiki",
mediaCount = 1,
format = "STEAM",
crack = true,
serialKey = true,
otherData = "Other data",
note = "Note"
)
}
/**
* A class represents utility class for programs.
*
* @author Vladimir Hromada
*/
object ProgramUtils {
/**
* Count of programs
*/
const val PROGRAMS_COUNT = 3
/**
* Multiplier for media count
*/
private const val MEDIA_COUNT_MULTIPLIER = 100
/**
* Returns programs.
*
* @return programs
*/
fun getDomainPrograms(): List<com.github.vhromada.catalog.domain.Program> {
val programs = mutableListOf<com.github.vhromada.catalog.domain.Program>()
for (i in 1..PROGRAMS_COUNT) {
programs.add(getDomainProgram(index = i))
}
return programs
}
/**
* Returns programs.
*
* @return programs
*/
fun getPrograms(): List<Program> {
val programs = mutableListOf<Program>()
for (i in 1..PROGRAMS_COUNT) {
programs.add(getProgram(index = i))
}
return programs
}
/**
* Returns program for index.
*
* @param index index
* @return program for index
*/
fun getDomainProgram(index: Int): com.github.vhromada.catalog.domain.Program {
val name = "Program $index name"
return com.github.vhromada.catalog.domain.Program(
id = index,
uuid = getUuid(index = index),
name = name,
normalizedName = name,
wikiEn = if (index != 3) "Program $index English Wikipedia" else null,
wikiCz = if (index != 3) "Program $index Czech Wikipedia" else null,
mediaCount = index * MEDIA_COUNT_MULTIPLIER,
format = getFormat(index = index),
crack = index == 3,
serialKey = index != 1,
otherData = if (index == 3) "Program $index other data" else null,
note = if (index == 3) "Program $index note" else null
).fillAudit(audit = AuditUtils.getAudit())
}
/**
* Returns UUID for index.
*
* @param index index
* @return UUID for index
*/
private fun getUuid(index: Int): String {
return when (index) {
1 -> "bd6b8a6f-5983-494b-aabb-9046162f6bbb"
2 -> "f5593664-e2c0-4219-881c-59ee040f0305"
3 -> "860c1aa7-d4c0-40f9-9fb4-eb657c121d84"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns format for index.
*
* @param index index
* @return format for index
*/
private fun getFormat(index: Int): String {
return when (index) {
1 -> "ISO"
2 -> "STEAM"
3 -> "BINARY"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns program.
*
* @param entityManager entity manager
* @param id program ID
* @return program
*/
fun getDomainProgram(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Program? {
return entityManager.find(com.github.vhromada.catalog.domain.Program::class.java, id)
}
/**
* Returns program for index.
*
* @param index index
* @return program for index
*/
fun getProgram(index: Int): Program {
return Program(
uuid = getUuid(index = index),
name = "Program $index name",
wikiEn = if (index != 3) "Program $index English Wikipedia" else null,
wikiCz = if (index != 3) "Program $index Czech Wikipedia" else null,
mediaCount = index * MEDIA_COUNT_MULTIPLIER,
format = getFormat(index = index),
crack = index == 3,
serialKey = index != 1,
otherData = if (index == 3) "Program $index other data" else null,
note = if (index == 3) "Program $index note" else null
)
}
/**
* Returns statistics for programs.
*
* @return statistics for programs
*/
fun getDomainStatistics(): ProgramStatistics {
return ProgramStatistics(count = PROGRAMS_COUNT.toLong(), mediaCount = 600L)
}
/**
* Returns statistics for programs.
*
* @return statistics for programs
*/
fun getStatistics(): com.github.vhromada.catalog.entity.ProgramStatistics {
return com.github.vhromada.catalog.entity.ProgramStatistics(count = PROGRAMS_COUNT, mediaCount = 600)
}
/**
* Returns count of programs.
*
* @param entityManager entity manager
* @return count of programs
*/
fun getProgramsCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(p.id) FROM Program p", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns program.
*
* @param id ID
* @return program
*/
fun newDomainProgram(id: Int?): com.github.vhromada.catalog.domain.Program {
return com.github.vhromada.catalog.domain.Program(
id = id,
uuid = TestConstants.UUID,
name = "",
normalizedName = "",
wikiEn = null,
wikiCz = null,
mediaCount = 0,
format = "STEAM",
crack = false,
serialKey = false,
otherData = null,
note = null
).updated()
}
/**
* Returns program.
*
* @return program
*/
fun newProgram(): Program {
return Program(
uuid = TestConstants.UUID,
name = "",
wikiEn = null,
wikiCz = null,
mediaCount = 0,
format = "STEAM",
crack = false,
serialKey = false,
otherData = null,
note = null
).updated()
}
/**
* Returns request for changing program.
*
* @return request for changing program
*/
fun newRequest(): ChangeProgramRequest {
return ChangeProgramRequest(
name = "Name",
wikiEn = "enWiki",
wikiCz = "czWiki",
mediaCount = 1,
format = "STEAM",
crack = true,
serialKey = true,
otherData = "Other data",
note = "Note"
)
}
/**
* Asserts list of programs deep equals.
*
* @param expected expected list of programs
* @param actual actual list of programs
*/
fun assertDomainProgramsDeepEquals(expected: List<com.github.vhromada.catalog.domain.Program>, actual: List<com.github.vhromada.catalog.domain.Program>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertProgramDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts program deep equals.
*
* @param expected expected program
* @param actual actual program
*/
fun assertProgramDeepEquals(expected: com.github.vhromada.catalog.domain.Program?, actual: com.github.vhromada.catalog.domain.Program?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.normalizedName).isEqualTo(expected.normalizedName)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.format).isEqualTo(expected.format)
it.assertThat(actual.crack).isEqualTo(expected.crack)
it.assertThat(actual.serialKey).isEqualTo(expected.serialKey)
it.assertThat(actual.otherData).isEqualTo(expected.otherData)
it.assertThat(actual.note).isEqualTo(expected.note)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
}
}
/**
* Asserts list of programs deep equals.
*
* @param expected expected list of programs
* @param actual actual list of programs
*/
fun assertProgramsDeepEquals(expected: List<com.github.vhromada.catalog.domain.Program>, actual: List<Program>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertProgramDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts program deep equals.
*
* @param expected expected program
* @param actual actual program
*/
fun assertProgramDeepEquals(expected: com.github.vhromada.catalog.domain.Program, actual: Program) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.format).isEqualTo(expected.format)
it.assertThat(actual.crack).isEqualTo(expected.crack)
it.assertThat(actual.serialKey).isEqualTo(expected.serialKey)
it.assertThat(actual.otherData).isEqualTo(expected.otherData)
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts list of programs deep equals.
*
* @param expected expected list of programs
* @param actual actual list of programs
*/
fun assertProgramListDeepEquals(expected: List<Program>, actual: List<Program>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertProgramDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts program deep equals.
*
* @param expected expected program
* @param actual actual program
*/
fun assertProgramDeepEquals(expected: Program, actual: Program) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.format).isEqualTo(expected.format)
it.assertThat(actual.crack).isEqualTo(expected.crack)
it.assertThat(actual.serialKey).isEqualTo(expected.serialKey)
it.assertThat(actual.otherData).isEqualTo(expected.otherData)
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts request and program deep equals.
*
* @param expected expected request for changing program
* @param actual actual program
* @param uuid UUID
*/
fun assertRequestDeepEquals(expected: ChangeProgramRequest, actual: com.github.vhromada.catalog.domain.Program, uuid: String) {
assertSoftly {
it.assertThat(actual.id).isNull()
it.assertThat(actual.uuid).isEqualTo(uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.normalizedName).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.format).isEqualTo(expected.format)
it.assertThat(actual.crack).isEqualTo(expected.crack)
it.assertThat(actual.serialKey).isEqualTo(expected.serialKey)
it.assertThat(actual.otherData).isEqualTo(expected.otherData)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.createdUser).isNull()
it.assertThat(actual.createdTime).isNull()
it.assertThat(actual.updatedUser).isNull()
it.assertThat(actual.updatedTime).isNull()
}
}
/**
* Asserts filter deep equals.
*
* @param expected expected filter
* @param actual actual filter
*/
fun assertFilterDeepEquals(expected: NameFilter, actual: ProgramFilter) {
assertThat(actual.name).isEqualTo(expected.name)
}
/**
* Asserts statistics for programs deep equals.
*
* @param expected expected statistics for programs
* @param actual actual statistics for programs
*/
fun assertStatisticsDeepEquals(expected: ProgramStatistics, actual: ProgramStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
}
}
/**
* Asserts statistics for programs deep equals.
*
* @param expected expected statistics for programs
* @param actual actual statistics for programs
*/
fun assertStatisticsDeepEquals(expected: ProgramStatistics, actual: com.github.vhromada.catalog.entity.ProgramStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount!!.toInt())
}
}
}
| mit | dc9e64b1f7fb1d4839fafccf7261919b | 32.305987 | 158 | 0.607217 | 4.536696 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/units/Velocity.kt | 3 | 6056 | /*
* 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.health.connect.client.units
/**
* Represents a unit of speed. Supported units:
*
* - metersPerSecond - see [Velocity.metersPerSecond], [Double.metersPerSecond]
* - kilometersPerHour - see [Velocity.kilometersPerHour], [Double.kilometersPerHour]
* - milesPerHour - see [Velocity.milesPerHour], [Double.milesPerHour]
*/
class Velocity private constructor(
private val value: Double,
private val type: Type,
) : Comparable<Velocity> {
/** Returns the velocity in meters per second. */
@get:JvmName("getMetersPerSecond")
val inMetersPerSecond: Double
get() = value * type.metersPerSecondPerUnit
/** Returns the velocity in kilometers per hour. */
@get:JvmName("getKilometersPerHour")
val inKilometersPerHour: Double
get() = get(type = Type.KILOMETERS_PER_HOUR)
/** Returns the velocity in miles per hour. */
@get:JvmName("getMilesPerHour")
val inMilesPerHour: Double
get() = get(type = Type.MILES_PER_HOUR)
private fun get(type: Type): Double =
if (this.type == type) value else inMetersPerSecond / type.metersPerSecondPerUnit
/** Returns zero [Velocity] of the same [Type]. */
internal fun zero(): Velocity = ZEROS.getValue(type)
override fun compareTo(other: Velocity): Int =
if (type == other.type) {
value.compareTo(other.value)
} else {
inMetersPerSecond.compareTo(other.inMetersPerSecond)
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Velocity) return false
if (value != other.value) return false
if (type != other.type) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = value.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String = "$value ${type.title}"
companion object {
private val ZEROS = Type.values().associateWith { Velocity(value = 0.0, type = it) }
/** Creates [Velocity] with the specified value in meters per second. */
@JvmStatic
fun metersPerSecond(value: Double): Velocity = Velocity(value, Type.METERS_PER_SECOND)
/** Creates [Velocity] with the specified value in kilometers per hour. */
@JvmStatic
fun kilometersPerHour(value: Double): Velocity = Velocity(value, Type.KILOMETERS_PER_HOUR)
/** Creates [Velocity] with the specified value in miles per hour. */
@JvmStatic
fun milesPerHour(value: Double): Velocity = Velocity(value, Type.MILES_PER_HOUR)
}
private enum class Type {
METERS_PER_SECOND {
override val metersPerSecondPerUnit: Double = 1.0
override val title: String = "meters/sec"
},
KILOMETERS_PER_HOUR {
override val metersPerSecondPerUnit: Double = 1.0 / 3.6
override val title: String = "km/h"
},
MILES_PER_HOUR {
override val metersPerSecondPerUnit: Double = 0.447040357632
override val title: String = "miles/h"
};
abstract val metersPerSecondPerUnit: Double
abstract val title: String
}
}
/** Creates [Velocity] with the specified value in meters per second. */
@get:JvmSynthetic
val Double.metersPerSecond: Velocity
get() = Velocity.metersPerSecond(value = this)
/** Creates [Velocity] with the specified value in meters per second. */
@get:JvmSynthetic
val Long.metersPerSecond: Velocity
get() = toDouble().metersPerSecond
/** Creates [Velocity] with the specified value in meters per second. */
@get:JvmSynthetic
val Float.metersPerSecond: Velocity
get() = toDouble().metersPerSecond
/** Creates [Velocity] with the specified value in meters per second. */
@get:JvmSynthetic
val Int.metersPerSecond: Velocity
get() = toDouble().metersPerSecond
/** Creates [Velocity] with the specified value in kilometers per hour. */
@get:JvmSynthetic
val Double.kilometersPerHour: Velocity
get() = Velocity.kilometersPerHour(value = this)
/** Creates [Velocity] with the specified value in kilometers per hour. */
@get:JvmSynthetic
val Long.kilometersPerHour: Velocity
get() = toDouble().kilometersPerHour
/** Creates [Velocity] with the specified value in kilometers per hour. */
@get:JvmSynthetic
val Float.kilometersPerHour: Velocity
get() = toDouble().kilometersPerHour
/** Creates [Velocity] with the specified value in kilometers per hour. */
@get:JvmSynthetic
val Int.kilometersPerHour: Velocity
get() = toDouble().kilometersPerHour
/** Creates [Velocity] with the specified value in miles per hour. */
@get:JvmSynthetic
val Double.milesPerHour: Velocity
get() = Velocity.milesPerHour(value = this)
/** Creates [Velocity] with the specified value in miles per hour. */
@get:JvmSynthetic
val Long.milesPerHour: Velocity
get() = toDouble().milesPerHour
/** Creates [Velocity] with the specified value in miles per hour. */
@get:JvmSynthetic
val Float.milesPerHour: Velocity
get() = toDouble().milesPerHour
/** Creates [Velocity] with the specified value in miles per hour. */
@get:JvmSynthetic
val Int.milesPerHour: Velocity
get() = toDouble().milesPerHour
| apache-2.0 | c9a48006100d3cf5c3bc6bca4fab6a86 | 33.409091 | 98 | 0.681143 | 4.185211 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/AbstractKotlinApplicatorBasedIntention.kt | 1 | 3162 | // 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.codeinsight.api.applicators
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.psi.KtElement
import kotlin.reflect.KClass
@Deprecated("Please don't use this for new intentions. Use `KotlinApplicableIntention` or `KotlinApplicableContextIntention` instead.")
abstract class AbstractKotlinApplicatorBasedIntention<PSI : KtElement, INPUT : KotlinApplicatorInput>(
elementType: KClass<PSI>,
) : SelfTargetingIntention<PSI>(elementType.java, { "" }) {
abstract fun getApplicator(): KotlinApplicator<PSI, INPUT>
abstract fun getApplicabilityRange(): KotlinApplicabilityRange<PSI>
abstract fun getInputProvider(): KotlinApplicatorInputProvider<PSI, INPUT>
init {
setFamilyNameGetter { getApplicator().getFamilyName() }
}
final override fun isApplicableTo(element: PSI, caretOffset: Int): Boolean {
val project = element.project// TODO expensive operation, may require traversing the tree up to containing PsiFile
val applicator = getApplicator()
if (!applicator.isApplicableByPsi(element, project)) return false
val ranges = getApplicabilityRange().getApplicabilityRanges(element)
if (ranges.isEmpty()) return false
// An KotlinApplicabilityRange should be relative to the element, while `caretOffset` is absolute
val relativeCaretOffset = caretOffset - element.textRange.startOffset
if (ranges.none { it.containsOffset(relativeCaretOffset) }) return false
val input = getInput(element)
if (input != null && input.isValidFor(element)) {
val actionText = applicator.getActionName(element, input)
val familyName = applicator.getFamilyName()
setFamilyNameGetter { familyName }
setTextGetter { actionText }
return true
}
return false
}
final override fun applyTo(element: PSI, project: Project, editor: Editor?) {
val input = getInput(element) ?: return
if (input.isValidFor(element)) {
val applicator = getApplicator() // TODO reuse existing applicator
runWriteActionIfPhysical(element) {
applicator.applyTo(element, input, project, editor)
}
}
}
final override fun applyTo(element: PSI, editor: Editor?) {
applyTo(element, element.project, editor)
}
@OptIn(KtAllowAnalysisOnEdt::class)
private fun getInput(element: PSI): INPUT? = allowAnalysisOnEdt {
analyzeWithReadAction(element) {
with(getInputProvider()) { provideInput(element) }
}
}
}
| apache-2.0 | ed8649787052aa620e1fffb1ace91454 | 41.72973 | 135 | 0.720746 | 5.051118 | false | false | false | false |
idea4bsd/idea4bsd | platform/lang-api/src/com/intellij/configurationStore/UnknownElementManager.kt | 16 | 2722 | /*
* 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 com.intellij.configurationStore
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jdom.Element
import java.util.function.Consumer
import java.util.function.Function
// Empty unknown tags supported to simplify client write code (with and without unknown elements)
class UnknownElementWriter internal constructor(private val unknownElements: Map<String, Element> = emptyMap()) {
companion object {
@JvmField
val EMPTY = UnknownElementWriter()
}
fun <T> write(outElement: Element, items: Collection<T>, itemToTagName: Function<T, String>, writer: Consumer<T>) {
val knownNameToWriter = THashMap<String, T>(items.size)
for (item in items) {
knownNameToWriter.put(itemToTagName.apply(item), item)
}
write(outElement, knownNameToWriter, writer)
}
fun <T> write(outElement: Element, knownNameToWriter: Map<String, T>, writer: Consumer<T>) {
val names: Set<String>
if (unknownElements.isEmpty()) {
names = knownNameToWriter.keys
}
else {
names = THashSet<String>(unknownElements.keys)
names.addAll(knownNameToWriter.keys)
}
val sortedNames = names.toTypedArray()
sortedNames.sort()
for (name in sortedNames) {
val known = knownNameToWriter.get(name)
if (known == null) {
outElement.addContent(unknownElements.get(name)!!.clone())
}
else {
writer.accept(known)
}
}
}
}
class UnknownElementCollector {
private val knownTagNames = THashSet<String>()
fun addKnownName(name: String) {
knownTagNames.add(name)
}
fun createWriter(element: Element): UnknownElementWriter? {
var unknownElements: MutableMap<String, Element>? = null
val iterator = element.children.iterator()
for (child in iterator) {
if (child.name != "option" && !knownTagNames.contains(child.name)) {
if (unknownElements == null) {
unknownElements = THashMap()
}
unknownElements.put(child.name, child)
iterator.remove()
}
}
return unknownElements?.let(::UnknownElementWriter) ?: UnknownElementWriter.EMPTY
}
} | apache-2.0 | a98a4600fa82dd653eb44b49af61751f | 31.035294 | 117 | 0.699118 | 4.062687 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereGeneralActionFeaturesProvider.kt | 7 | 2340 | package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.searcheverywhere.ActionSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.TopHitSEContributor
import com.intellij.ide.util.gotoByName.GotoActionItemProvider
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
internal class SearchEverywhereGeneralActionFeaturesProvider
: SearchEverywhereElementFeaturesProvider(ActionSearchEverywhereContributor::class.java, TopHitSEContributor::class.java) {
companion object {
internal val IS_ENABLED = EventFields.Boolean("isEnabled")
internal val ITEM_TYPE = EventFields.Enum<GotoActionModel.MatchedValueType>("type")
internal val TYPE_WEIGHT = EventFields.Int("typeWeight")
internal val IS_HIGH_PRIORITY = EventFields.Boolean("isHighPriority")
}
override fun getFeaturesDeclarations(): List<EventField<*>> {
return arrayListOf(
IS_ENABLED, ITEM_TYPE, TYPE_WEIGHT, IS_HIGH_PRIORITY
)
}
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val data = arrayListOf<EventPair<*>>()
addIfTrue(data, IS_HIGH_PRIORITY, isHighPriority(elementPriority))
// (element is GotoActionModel.MatchedValue) for actions and option provided by 'ActionSearchEverywhereContributor'
// (element is OptionDescription || element is AnAction) for actions and option provided by 'TopHitSEContributor'
if (element is GotoActionModel.MatchedValue) {
data.add(ITEM_TYPE.with(element.type))
data.add(TYPE_WEIGHT.with(element.valueTypeWeight))
}
val value = if (element is GotoActionModel.MatchedValue) element.value else element
val actionText = GotoActionItemProvider.getActionText(value)
actionText?.let {
data.addAll(getNameMatchingFeatures(it, searchQuery))
}
return data
}
private fun isHighPriority(priority: Int): Boolean = priority >= 11001
} | apache-2.0 | 1c5e6b46e3f3d27b27dd5f0920608af4 | 44.901961 | 125 | 0.741026 | 4.864865 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/KotlinIdeaAnalysisIndependentBundle.kt | 1 | 981 | // 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
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.KotlinIdeaAnalysisIndependentBundle"
object KotlinIdeaAnalysisIndependentBundle : AbstractKotlinIndependentBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
@Nls
@JvmStatic
fun htmlMessage(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String =
getMessage(key, *params).withHtml()
@Nls
@JvmStatic
fun lazyMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): () -> String = { getMessage(key, *params) }
} | apache-2.0 | 5367affd72c2d2515e49810ae8d2bfc6 | 39.916667 | 158 | 0.755352 | 4.379464 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt | 2 | 9320 | // 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.
@file:JvmName("FuzzyTypeUtils")
package org.jetbrains.kotlin.idea.util
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.resolve.calls.inference.CallHandle
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl
import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPositionKind
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker
import org.jetbrains.kotlin.types.typeUtil.*
import java.util.*
fun CallableDescriptor.fuzzyReturnType() = returnType?.toFuzzyType(typeParameters)
fun CallableDescriptor.fuzzyExtensionReceiverType() = extensionReceiverParameter?.type?.toFuzzyType(typeParameters)
fun FuzzyType.makeNotNullable() = type.makeNotNullable().toFuzzyType(freeParameters)
fun FuzzyType.makeNullable() = type.makeNullable().toFuzzyType(freeParameters)
fun FuzzyType.nullability() = type.nullability()
fun FuzzyType.isAlmostEverything(): Boolean {
if (freeParameters.isEmpty()) return false
val typeParameter = type.constructor.declarationDescriptor as? TypeParameterDescriptor ?: return false
if (typeParameter !in freeParameters) return false
return typeParameter.upperBounds.singleOrNull()?.isAnyOrNullableAny() ?: false
}
/**
* Replaces free parameters inside the type with corresponding type parameters of the class (when possible)
*/
fun FuzzyType.presentationType(): KotlinType {
if (freeParameters.isEmpty()) return type
val map = HashMap<TypeConstructor, TypeProjection>()
for ((argument, typeParameter) in type.arguments.zip(type.constructor.parameters)) {
if (argument.projectionKind == Variance.INVARIANT) {
val equalToFreeParameter = freeParameters.firstOrNull {
StrictEqualityTypeChecker.strictEqualTypes(it.defaultType, argument.type.unwrap())
} ?: continue
map[equalToFreeParameter.typeConstructor] = createProjection(typeParameter.defaultType, Variance.INVARIANT, null)
}
}
val substitutor = TypeSubstitutor.create(map)
return substitutor.substitute(type, Variance.INVARIANT)!!
}
fun KotlinType.toFuzzyType(freeParameters: Collection<TypeParameterDescriptor>) = FuzzyType(this, freeParameters)
class FuzzyType(
val type: KotlinType,
freeParameters: Collection<TypeParameterDescriptor>
) {
val freeParameters: Set<TypeParameterDescriptor>
init {
if (freeParameters.isNotEmpty()) {
// we allow to pass type parameters from another function with the same original in freeParameters
val usedTypeParameters = HashSet<TypeParameterDescriptor>().apply { addUsedTypeParameters(type) }
if (usedTypeParameters.isNotEmpty()) {
val originalFreeParameters = freeParameters.map { it.toOriginal() }.toSet()
this.freeParameters = usedTypeParameters.filter { it.toOriginal() in originalFreeParameters }.toSet()
} else {
this.freeParameters = emptySet()
}
} else {
this.freeParameters = emptySet()
}
}
// Diagnostic for EA-109046
@Suppress("USELESS_ELVIS")
private fun TypeParameterDescriptor.toOriginal(): TypeParameterDescriptor {
val callableDescriptor = containingDeclaration as? CallableMemberDescriptor ?: return this
val original = callableDescriptor.original ?: error("original = null for $callableDescriptor")
val typeParameters = original.typeParameters ?: error("typeParameters = null for $original")
return typeParameters[index]
}
override fun equals(other: Any?) = other is FuzzyType && other.type == type && other.freeParameters == freeParameters
override fun hashCode() = type.hashCode()
private fun MutableSet<TypeParameterDescriptor>.addUsedTypeParameters(type: KotlinType) {
val typeParameter = type.constructor.declarationDescriptor as? TypeParameterDescriptor
if (typeParameter != null && add(typeParameter)) {
typeParameter.upperBounds.forEach { addUsedTypeParameters(it) }
}
for (argument in type.arguments) {
if (!argument.isStarProjection) { // otherwise we can fall into infinite recursion
addUsedTypeParameters(argument.type)
}
}
}
fun checkIsSubtypeOf(otherType: FuzzyType): TypeSubstitutor? = matchedSubstitutor(otherType, MatchKind.IS_SUBTYPE)
fun checkIsSuperTypeOf(otherType: FuzzyType): TypeSubstitutor? = matchedSubstitutor(otherType, MatchKind.IS_SUPERTYPE)
fun checkIsSubtypeOf(otherType: KotlinType): TypeSubstitutor? = checkIsSubtypeOf(otherType.toFuzzyType(emptyList()))
fun checkIsSuperTypeOf(otherType: KotlinType): TypeSubstitutor? = checkIsSuperTypeOf(otherType.toFuzzyType(emptyList()))
private enum class MatchKind {
IS_SUBTYPE,
IS_SUPERTYPE
}
private fun matchedSubstitutor(otherType: FuzzyType, matchKind: MatchKind): TypeSubstitutor? {
if (type.isError) return null
if (otherType.type.isError) return null
if (otherType.type.isUnit() && matchKind == MatchKind.IS_SUBTYPE) return TypeSubstitutor.EMPTY
fun KotlinType.checkInheritance(otherType: KotlinType): Boolean {
return when (matchKind) {
MatchKind.IS_SUBTYPE -> this.isSubtypeOf(otherType)
MatchKind.IS_SUPERTYPE -> otherType.isSubtypeOf(this)
}
}
if (freeParameters.isEmpty() && otherType.freeParameters.isEmpty()) {
return if (type.checkInheritance(otherType.type)) TypeSubstitutor.EMPTY else null
}
val builder = ConstraintSystemBuilderImpl()
val typeVariableSubstitutor = builder.registerTypeVariables(CallHandle.NONE, freeParameters + otherType.freeParameters)
val typeInSystem = typeVariableSubstitutor.substitute(type, Variance.INVARIANT)
val otherTypeInSystem = typeVariableSubstitutor.substitute(otherType.type, Variance.INVARIANT)
when (matchKind) {
MatchKind.IS_SUBTYPE ->
builder.addSubtypeConstraint(typeInSystem, otherTypeInSystem, ConstraintPositionKind.RECEIVER_POSITION.position())
MatchKind.IS_SUPERTYPE ->
builder.addSubtypeConstraint(otherTypeInSystem, typeInSystem, ConstraintPositionKind.RECEIVER_POSITION.position())
}
builder.fixVariables()
val constraintSystem = builder.build()
if (constraintSystem.status.hasContradiction()) return null
// currently ConstraintSystem return successful status in case there are problems with nullability
// that's why we have to check subtyping manually
val substitutor = constraintSystem.resultingSubstitutor
val substitutedType = substitutor.substitute(type, Variance.INVARIANT) ?: return null
if (substitutedType.isError) return TypeSubstitutor.EMPTY
val otherSubstitutedType = substitutor.substitute(otherType.type, Variance.INVARIANT) ?: return null
if (otherSubstitutedType.isError) return TypeSubstitutor.EMPTY
if (!substitutedType.checkInheritance(otherSubstitutedType)) return null
val substitutorToKeepCapturedTypes = object : DelegatedTypeSubstitution(substitutor.substitution) {
override fun approximateCapturedTypes() = false
}.buildSubstitutor()
val substitutionMap: Map<TypeConstructor, TypeProjection> = constraintSystem.typeVariables
.map { it.originalTypeParameter }
.associateBy(
keySelector = { it.typeConstructor },
valueTransform = {
val typeProjection = TypeProjectionImpl(Variance.INVARIANT, it.defaultType)
val substitutedProjection = substitutorToKeepCapturedTypes.substitute(typeProjection)
substitutedProjection?.takeUnless { ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection
})
return TypeConstructorSubstitution.createByConstructorsMap(substitutionMap, approximateCapturedTypes = true).buildSubstitutor()
}
}
fun TypeSubstitution.hasConflictWith(other: TypeSubstitution, freeParameters: Collection<TypeParameterDescriptor>): Boolean {
return freeParameters.any { parameter ->
val type = parameter.defaultType
val substituted1 = this[type] ?: return@any false
val substituted2 = other[type] ?: return@any false
!StrictEqualityTypeChecker.strictEqualTypes(
substituted1.type.unwrap(),
substituted2.type.unwrap()
) || substituted1.projectionKind != substituted2.projectionKind
}
}
fun TypeSubstitutor.combineIfNoConflicts(other: TypeSubstitutor, freeParameters: Collection<TypeParameterDescriptor>): TypeSubstitutor? {
if (this.substitution.hasConflictWith(other.substitution, freeParameters)) return null
return TypeSubstitutor.createChainedSubstitutor(this.substitution, other.substitution)
}
| apache-2.0 | 3d689085803196928584d9604714001d | 47.795812 | 158 | 0.729721 | 5.283447 | false | false | false | false |
smmribeiro/intellij-community | java/idea-ui/src/com/intellij/ide/starters/local/wizard/StarterInitialStep.kt | 1 | 15763 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.local.wizard
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.local.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.starters.shared.ValidationFunctions.*
import com.intellij.ide.util.projectWizard.ModuleNameGenerator
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.properties.map
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ui.configuration.JdkComboBox
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.openapi.roots.ui.configuration.validateJavaVersion
import com.intellij.openapi.roots.ui.configuration.validateSdk
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.EMPTY_LABEL
import com.intellij.ui.layout.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded
import org.jdom.Element
import java.io.File
import java.net.SocketTimeoutException
import java.nio.file.Files
import java.nio.file.Path
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JTextField
open class StarterInitialStep(contextProvider: StarterContextProvider) : ModuleWizardStep() {
protected val moduleBuilder: StarterModuleBuilder = contextProvider.moduleBuilder
protected val wizardContext: WizardContext = contextProvider.wizardContext
protected val starterContext: StarterContext = contextProvider.starterContext
protected val starterSettings: StarterWizardSettings = contextProvider.settings
protected val parentDisposable: Disposable = contextProvider.parentDisposable
private val starterPackProvider: () -> StarterPack = contextProvider.starterPackProvider
private val validatedTextComponents: MutableList<JTextField> = mutableListOf()
protected val propertyGraph: PropertyGraph = PropertyGraph()
private val entityNameProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestName)
private val locationProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestLocationByName)
private val groupIdProperty: GraphProperty<String> = propertyGraph.graphProperty { starterContext.group }
private val artifactIdProperty: GraphProperty<String> = propertyGraph.graphProperty { entityName }
protected val sdkProperty: GraphProperty<Sdk?> = propertyGraph.graphProperty { null }
private val projectTypeProperty: GraphProperty<StarterProjectType?> = propertyGraph.graphProperty { starterContext.projectType }
private val languageProperty: GraphProperty<StarterLanguage> = propertyGraph.graphProperty { starterContext.language }
private val testFrameworkProperty: GraphProperty<StarterTestRunner?> = propertyGraph.graphProperty { starterContext.testFramework }
private val applicationTypeProperty: GraphProperty<StarterAppType?> = propertyGraph.graphProperty { starterContext.applicationType }
private val exampleCodeProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { starterContext.includeExamples }
private val gitProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { false }
private var entityName: String by entityNameProperty.map { it.trim() }
private var location: String by locationProperty
private var groupId: String by groupIdProperty.map { it.trim() }
private var artifactId: String by artifactIdProperty.map { it.trim() }
private val contentPanel: DialogPanel by lazy { createComponent() }
private val sdkModel: ProjectSdksModel = ProjectSdksModel()
protected lateinit var sdkComboBox: JdkComboBox
protected lateinit var languageRow: Row
protected lateinit var groupRow: Row
protected lateinit var artifactRow: Row
@Volatile
private var isDisposed: Boolean = false
override fun getHelpId(): String? = moduleBuilder.getHelpId()
init {
Disposer.register(parentDisposable, Disposable {
isDisposed = true
sdkModel.disposeUIResources()
})
}
override fun updateDataModel() {
starterContext.projectType = projectTypeProperty.get()
starterContext.language = languageProperty.get()
starterContext.group = groupId
starterContext.artifact = artifactId
starterContext.testFramework = testFrameworkProperty.get()
starterContext.includeExamples = exampleCodeProperty.get()
starterContext.gitIntegration = gitProperty.get()
wizardContext.projectName = entityName
wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName))
val sdk = sdkProperty.get()
moduleBuilder.moduleJdk = sdk
if (wizardContext.project == null) {
wizardContext.projectJdk = sdk
}
}
override fun getComponent(): JComponent {
return contentPanel
}
private fun createComponent(): DialogPanel {
entityNameProperty.dependsOn(artifactIdProperty) { artifactId }
artifactIdProperty.dependsOn(entityNameProperty) { entityName }
// query dependencies from builder, called only once
val starterPack = starterPackProvider.invoke()
starterContext.starterPack = starterPack
updateStartersDependencies(starterPack)
return panel {
row(JavaStartersBundle.message("title.project.name.label")) {
textField(entityNameProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(listOf(CHECK_NOT_EMPTY, CHECK_SIMPLE_NAME_FORMAT),
createLocationWarningValidator(locationProperty))
.focused()
for (nameGenerator in ModuleNameGenerator.EP_NAME.extensionList) {
val nameGeneratorUi = nameGenerator.getUi(moduleBuilder.builderId) { entityNameProperty.set(it) }
if (nameGeneratorUi != null) {
component(nameGeneratorUi).constraints(pushX)
}
}
}.largeGapAfter()
addProjectLocationUi()
addFieldsBefore(this)
if (starterSettings.applicationTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.app.type.label")) {
val applicationTypesModel = DefaultComboBoxModel<StarterAppType>()
applicationTypesModel.addAll(starterSettings.applicationTypes)
comboBox(applicationTypesModel, applicationTypeProperty, SimpleListCellRenderer.create("") { it?.title ?: "" })
.growPolicy(GrowPolicy.SHORT_TEXT)
}.largeGapAfter()
}
if (starterSettings.languages.size > 1) {
row(JavaStartersBundle.message("title.project.language.label")) {
languageRow = this
segmentedButton(starterSettings.languages, languageProperty) { it.title }
}.largeGapAfter()
}
if (starterSettings.projectTypes.isNotEmpty()) {
val messages = starterSettings.customizedMessages
row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.build.system.label")) {
segmentedButton(starterSettings.projectTypes, projectTypeProperty) { it?.title ?: "" }
}.largeGapAfter()
}
if (starterSettings.testFrameworks.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.test.framework.label")) {
segmentedButton(starterSettings.testFrameworks, testFrameworkProperty) { it?.title ?: "" }
}.largeGapAfter()
}
row(JavaStartersBundle.message("title.project.group.label")) {
groupRow = this
textField(groupIdProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_GROUP_FORMAT, CHECK_NO_RESERVED_WORDS)
}.largeGapAfter()
row(JavaStartersBundle.message("title.project.artifact.label")) {
artifactRow = this
textField(artifactIdProperty)
.growPolicy(GrowPolicy.SHORT_TEXT)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_ARTIFACT_SIMPLE_FORMAT, CHECK_NO_RESERVED_WORDS)
}.largeGapAfter()
row(JavaStartersBundle.message("title.project.sdk.label")) {
sdkComboBox = sdkComboBox(sdkModel, sdkProperty, wizardContext.project, moduleBuilder)
.growPolicy(GrowPolicy.SHORT_TEXT)
.component
}.largeGapAfter()
if (starterSettings.isExampleCodeProvided) {
row {
checkBox(JavaStartersBundle.message("title.project.examples.label"), exampleCodeProperty)
}
}
addFieldsAfter(this)
}.withVisualPadding(topField = true)
}
private fun LayoutBuilder.addProjectLocationUi() {
val locationRow = row(JavaStartersBundle.message("title.project.location.label")) {
projectLocationField(locationProperty, wizardContext)
.withSpecialValidation(CHECK_NOT_EMPTY, CHECK_LOCATION_FOR_ERROR)
}
if (wizardContext.isCreatingNewProject) {
// Git should not be enabled for single module
row(EMPTY_LABEL) {
checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox"), gitProperty)
}.largeGapAfter()
} else {
locationRow.largeGapAfter()
}
}
protected open fun addFieldsBefore(layout: LayoutBuilder) {}
protected open fun addFieldsAfter(layout: LayoutBuilder) {}
override fun validate(): Boolean {
if (!validateFormFields(component, contentPanel, validatedTextComponents)) {
return false
}
if (!validateSdk(sdkProperty, sdkModel)) {
return false
}
if (!validateJavaVersion(sdkProperty, moduleBuilder.getMinJavaVersionInternal()?.toFeatureString(), moduleBuilder.presentableName)) {
return false
}
return true
}
private fun updateStartersDependencies(starterPack: StarterPack) {
val starters = starterPack.starters
AppExecutorUtil.getAppExecutorService().submit {
checkDependencyUpdates(starters)
}
}
@RequiresBackgroundThread
private fun checkDependencyUpdates(starters: List<Starter>) {
for (starter in starters) {
val localUpdates = loadStarterDependencyUpdatesFromFile(starter.id)
if (localUpdates != null) {
setStarterDependencyUpdates(starter.id, localUpdates)
return
}
val externalUpdates = loadStarterDependencyUpdatesFromNetwork(starter.id) ?: return
val (dependencyUpdates, resourcePath) = externalUpdates
if (isDisposed) return
val dependencyConfig = StarterUtils.parseDependencyConfig(dependencyUpdates, resourcePath)
if (isDisposed) return
saveStarterDependencyUpdatesToFile(starter.id, dependencyUpdates)
setStarterDependencyUpdates(starter.id, dependencyConfig)
}
}
private fun suggestName(): String {
return suggestName(starterContext.artifact)
}
private fun suggestName(prefix: String): String {
val projectFileDirectory = File(wizardContext.projectFileDirectory)
return FileUtil.createSequentFileName(projectFileDirectory, prefix, "")
}
private fun suggestLocationByName(): String {
return wizardContext.projectFileDirectory // no project name included
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromFile(starterId: String): DependencyConfig? {
val configUpdateDir = File(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
val configUpdateFile = File(configUpdateDir, getPatchFileName(starterId))
if (!configUpdateFile.exists()
|| StarterUtils.isDependencyUpdateFileExpired(configUpdateFile)) {
return null
}
val resourcePath = configUpdateFile.absolutePath
return try {
StarterUtils.parseDependencyConfig(JDOMUtil.load(configUpdateFile), resourcePath)
}
catch (e: Exception) {
logger<StarterInitialStep>().warn("Failed to load starter dependency updates from file: $resourcePath. The file will be deleted.")
FileUtil.delete(configUpdateFile)
null
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromNetwork(starterId: String): Pair<Element, String>? {
val url = buildStarterPatchUrl(starterId) ?: return null
return try {
val content = HttpRequests.request(url)
.accept("application/xml")
.readString()
return JDOMUtil.load(content) to url
}
catch (e: Exception) {
if (e is HttpRequests.HttpStatusException
&& (e.statusCode == 403 || e.statusCode == 404)) {
logger<StarterInitialStep>().debug("No updates for $starterId: $url")
}
else if (e is SocketTimeoutException) {
logger<StarterInitialStep>().debug("Socket timeout for $starterId: $url")
}
else {
logger<StarterInitialStep>().warn("Unable to load external starter $starterId dependency updates from: $url", e)
}
null
}
}
@RequiresBackgroundThread
private fun saveStarterDependencyUpdatesToFile(starterId: String, dependencyConfigUpdate: Element) {
val configUpdateDir = Path.of(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
if (!configUpdateDir.exists()) {
Files.createDirectories(configUpdateDir)
}
val configUpdateFile = configUpdateDir.resolve(getPatchFileName(starterId))
JDOMUtil.write(dependencyConfigUpdate, configUpdateFile)
}
private fun setStarterDependencyUpdates(starterId: String, dependencyConfigUpdate: DependencyConfig) {
invokeLaterIfNeeded {
if (isDisposed) return@invokeLaterIfNeeded
starterContext.startersDependencyUpdates[starterId] = dependencyConfigUpdate
}
}
private fun buildStarterPatchUrl(starterId: String): String? {
val host = Registry.stringValue("starters.dependency.update.host").nullize(true) ?: return null
val ideVersion = ApplicationInfoImpl.getShadowInstance().let { "${it.majorVersion}.${it.minorVersion}" }
val patchFileName = getPatchFileName(starterId)
return "$host/starter/$starterId/$ideVersion/$patchFileName"
}
private fun getDependencyConfigUpdatesDirLocation(starterId: String): String = "framework-starters/$starterId/"
private fun getPatchFileName(starterId: String): String = "${starterId}_patch.pom"
@Suppress("SameParameterValue")
private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(vararg errorValidationUnits: TextValidationFunction): CellBuilder<T> =
withValidation(this, errorValidationUnits.asList(), null, validatedTextComponents, parentDisposable)
private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(
errorValidationUnits: List<TextValidationFunction>,
warningValidationUnit: TextValidationFunction?
): CellBuilder<T> {
return withValidation(this, errorValidationUnits, warningValidationUnit, validatedTextComponents, parentDisposable)
}
} | apache-2.0 | 48e0916707bab3184a935dd553ca5e94 | 40.593668 | 140 | 0.75747 | 5.207466 | false | true | false | false |
BenWoodworth/FastCraft | fastcraft-bukkit/bukkit-1.7/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/text/FcTextConverter_Bukkit_1_7.kt | 1 | 10781 | package net.benwoodworth.fastcraft.bukkit.text
import net.benwoodworth.fastcraft.platform.text.FcText
import net.benwoodworth.fastcraft.platform.text.FcTextColor
import net.benwoodworth.fastcraft.util.JsonStringBuilder
import org.bukkit.ChatColor
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FcTextConverter_Bukkit_1_7 @Inject constructor(
private val localizer: BukkitLocalizer,
fcTextColorOperations: FcTextColor.Operations,
) : FcTextConverter_Bukkit,
FcTextColor_Bukkit.Operations by fcTextColorOperations.bukkit {
override fun toRaw(text: FcText): String {
return JsonStringBuilder()
.appendFcText(text)
.toString()
}
private fun JsonStringBuilder.appendFcText(text: FcText): JsonStringBuilder {
text as FcText_Bukkit
return when (text) {
is FcText_Bukkit.Legacy -> appendFcText(text)
is FcText_Bukkit.Component -> appendFcText(text)
}
}
private fun JsonStringBuilder.appendFcText(text: FcText_Bukkit.Legacy): JsonStringBuilder {
return appendString(text.legacyText)
}
private fun JsonStringBuilder.appendFcText(text: FcText_Bukkit.Component): JsonStringBuilder {
appendObject {
when (text) {
is FcText_Bukkit.Component.Text ->
appendElement("text") { appendString(text.text) }
is FcText_Bukkit.Component.Translate ->
appendElement("translate") { appendString(text.translate) }
}
with(text) {
color?.let {
appendElement("color") { appendString(it.id) }
}
bold?.let {
appendElement("bold") { appendBoolean(it) }
}
italic?.let {
appendElement("italic") { appendBoolean(it) }
}
underline?.let {
appendElement("underline") { appendBoolean(it) }
}
strikethrough?.let {
appendElement("strikethrough") { appendBoolean(it) }
}
obfuscate?.let {
appendElement("obfuscate") { appendBoolean(it) }
}
if (extra.any()) {
appendElement("extra") {
appendArray {
extra.forEach { appendFcText(it) }
}
}
}
}
}
return this
}
override fun toLegacy(text: FcText, locale: Locale): String {
text as FcText_Bukkit
return when (text) {
is FcText_Bukkit.Legacy ->
text.legacyText
is FcText_Bukkit.Component ->
LegacyTextBuilder(locale)
.appendText(text)
.toString()
}
}
private data class LegacyFormat(
var color: ChatColor = ChatColor.RESET,
var bold: Boolean = false,
var italic: Boolean = false,
var underline: Boolean = false,
var strikethrough: Boolean = false,
var obfuscate: Boolean = false,
)
private inner class LegacyTextBuilder(
private val locale: Locale,
) {
private val stringBuilder = StringBuilder().append(ChatColor.RESET)
// Formatting that has been appended.
val appliedFormat = LegacyFormat()
// Formatting that will be appended the next time plaintext is appended.
var pendingFormat = LegacyFormat()
override fun toString(): String {
return stringBuilder.toString()
}
fun appendText(text: FcText_Bukkit): LegacyTextBuilder {
appendText(text, LegacyFormat())
return this
}
private fun appendText(text: FcText, parentFormat: LegacyFormat) {
text as FcText_Bukkit
when (text) {
is FcText_Bukkit.Component ->
appendTextComponent(text, parentFormat)
is FcText_Bukkit.Legacy ->
appendLegacyText(text.legacyText)
}
}
private fun appendTextComponent(text: FcText_Bukkit.Component, parentFormat: LegacyFormat) {
// The text format, inheriting from parentFormat in place of nulls.
val format = LegacyFormat(
color = text.color?.chatColor ?: parentFormat.color,
bold = text.bold ?: parentFormat.bold,
italic = text.italic ?: parentFormat.italic,
underline = text.underline ?: parentFormat.underline,
strikethrough = text.strikethrough ?: parentFormat.strikethrough,
obfuscate = text.obfuscate ?: parentFormat.obfuscate
)
// Get the legacy to append
val legacyText = when (text) {
is FcText_Bukkit.Component.Text ->
text.text
is FcText_Bukkit.Component.Translate ->
localizer.localize(text.translate, locale) ?: text.translate
}
// Set the format, and append the text.
legacyText.let {
pendingFormat = format.copy()
appendLegacyText(it)
}
// Append the extra text.
text.extra.forEach {
appendText(it, format)
}
}
private fun appendLegacyText(text: String) {
var i = -1
while (++i < text.length) {
if (text[i] == ChatColor.COLOR_CHAR) {
// Read the formatting code, and append it.
if (++i <= text.lastIndex) {
appendFormat(text[i])
}
} else {
// Read plaintext until the next formatting code or the end.
val start = i
while (i <= text.lastIndex && text[i] != ChatColor.COLOR_CHAR) {
i++
}
// Append un-applied formatting codes and plaintext
applyFormat()
stringBuilder.append(text, start, i)
}
}
}
private fun appendFormat(char: Char) {
when (val format = ChatColor.getByChar(char)) {
null -> {
}
ChatColor.BOLD -> this.pendingFormat.bold = true
ChatColor.ITALIC -> this.pendingFormat.italic = true
ChatColor.UNDERLINE -> this.pendingFormat.underline = true
ChatColor.STRIKETHROUGH -> this.pendingFormat.strikethrough = true
ChatColor.MAGIC -> this.pendingFormat.obfuscate = true
else -> this.pendingFormat.apply {
// Set color, and clear other formatting
color = format
bold = false
italic = false
underline = false
strikethrough = false
obfuscate = false
}
}
}
private fun applyFormat() {
// If the color code resets, or if some formatting needs to be removed,
// then add color formatting, since it resets formatting.
if (
appliedFormat.color != pendingFormat.color ||
appliedFormat.bold && !pendingFormat.bold ||
appliedFormat.italic && !pendingFormat.italic ||
appliedFormat.underline && !pendingFormat.underline ||
appliedFormat.strikethrough && !pendingFormat.strikethrough ||
appliedFormat.obfuscate && !pendingFormat.obfuscate
) {
stringBuilder.append(pendingFormat.color)
appliedFormat.apply {
color = pendingFormat.color
bold = false
italic = false
underline = false
strikethrough = false
obfuscate = false
}
}
// If bold format needs to be applied, then apply it.
if (pendingFormat.bold && !appliedFormat.bold) {
stringBuilder.append(ChatColor.BOLD)
appliedFormat.bold = true
}
// If italic format needs to be applied, then apply it.
if (pendingFormat.italic && !appliedFormat.italic) {
stringBuilder.append(ChatColor.ITALIC)
appliedFormat.italic = true
}
// If underline format needs to be applied, then apply it.
if (pendingFormat.underline && !appliedFormat.underline) {
stringBuilder.append(ChatColor.UNDERLINE)
appliedFormat.underline = true
}
// If strikethrough format needs to be applied, then apply it.
if (pendingFormat.strikethrough && !appliedFormat.strikethrough) {
stringBuilder.append(ChatColor.STRIKETHROUGH)
appliedFormat.strikethrough = true
}
// If obfuscate format needs to be applied, then apply it.
if (pendingFormat.obfuscate && !appliedFormat.obfuscate) {
stringBuilder.append(ChatColor.MAGIC)
appliedFormat.obfuscate = true
}
}
}
override fun toPlaintext(text: FcText, locale: Locale): String {
return buildString {
fun appendLegacy(text: String) {
var i = 0
while (i < text.length) {
when (val ch = text[i]) {
'§' -> i += 2
else -> {
append(ch)
i++
}
}
}
}
fun appendText(text: FcText) {
text as FcText_Bukkit
when (text) {
is FcText_Bukkit.Legacy -> appendLegacy(text.legacyText)
is FcText_Bukkit.Component -> {
when (text) {
is FcText_Bukkit.Component.Text -> appendLegacy(text.text)
is FcText_Bukkit.Component.Translate -> appendLegacy(
localizer.localize(text.translate, locale) ?: text.translate
)
}
text.extra.forEach { appendText(it) }
}
}
}
appendText(text)
}
}
}
| gpl-3.0 | 25588cf575bdff499e6a5c61c1dca9fd | 35.053512 | 100 | 0.5141 | 5.373878 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/LocalApplicationStatisticManager.kt | 1 | 3556 | package sk.styk.martin.apkanalyzer.manager.appanalysis
import android.annotation.SuppressLint
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import androidx.annotation.WorkerThread
import kotlinx.coroutines.flow.flow
import sk.styk.martin.apkanalyzer.model.statistics.StatisticsAppData
import sk.styk.martin.apkanalyzer.model.statistics.StatisticsData
import sk.styk.martin.apkanalyzer.model.statistics.StatisticsDataBuilder
import sk.styk.martin.apkanalyzer.util.TAG_APP_ANALYSIS
import timber.log.Timber
import javax.inject.Inject
@SuppressLint("PackageManagerGetSignatures")
private const val ANALYSIS_FLAGS = PackageManager.GET_SIGNATURES or
PackageManager.GET_ACTIVITIES or
PackageManager.GET_SERVICES or
PackageManager.GET_PROVIDERS or
PackageManager.GET_RECEIVERS or
PackageManager.GET_PERMISSIONS
@WorkerThread
class LocalApplicationStatisticManager @Inject constructor(
private val packageManager: PackageManager,
private val installedAppsManager: InstalledAppsManager,
private val generalDataService: AppGeneralDataManager,
private val certificateService: CertificateManager,
) {
sealed class StatisticsLoadingStatus {
data class Loading(val currentProgress: Int, val totalProgress: Int) : StatisticsLoadingStatus()
data class Data(val data: StatisticsData) : StatisticsLoadingStatus()
}
suspend fun loadStatisticsData() = flow {
val allApps = installedAppsManager.getAll()
emit(StatisticsLoadingStatus.Loading(0, allApps.size))
val statsBuilder = StatisticsDataBuilder(allApps.size)
allApps.forEachIndexed { index, appListData ->
statsBuilder.add(get(appListData.packageName))
emit(StatisticsLoadingStatus.Loading(index, allApps.size))
}
emit(StatisticsLoadingStatus.Data(statsBuilder.build()))
}
fun get(packageName: String): StatisticsAppData? {
val packageInfo = try {
packageManager.getPackageInfo(packageName, ANALYSIS_FLAGS)
} catch (e: Exception) {
Timber.tag(TAG_APP_ANALYSIS).w(e, "Package info for statistics failed. Package name= $packageName")
return null
}
val applicationInfo = packageInfo.applicationInfo ?: return null
val isSystemApp = (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
return StatisticsAppData(
packageName = packageName,
isSystemApp = isSystemApp,
installLocation = packageInfo.installLocation,
targetSdk = applicationInfo.targetSdkVersion,
minSdk = AndroidManifestManager.getMinSdkVersion(applicationInfo, packageManager)
?: 0,
apkSize = if (applicationInfo.sourceDir != null) generalDataService.computeApkSize(applicationInfo.sourceDir) else 0,
appSource = AppGeneralDataManager.getAppSource(packageManager, packageName, isSystemApp),
signAlgorithm = certificateService.getSignAlgorithm(packageInfo) ?: "Unknown",
activities = packageInfo.activities?.size ?: 0,
services = packageInfo.services?.size ?: 0,
providers = packageInfo.providers?.size ?: 0,
receivers = packageInfo.receivers?.size ?: 0,
definedPermissions = packageInfo.permissions?.size ?: 0,
usedPermissions = packageInfo.requestedPermissions?.size ?: 0
)
}
}
| gpl-3.0 | 487a85b3cb50b9c99324fd6bd1a92941 | 42.365854 | 133 | 0.706412 | 5.221733 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/RequestUtil.kt | 1 | 1033 | package ch.rmy.android.http_shortcuts.http
import ch.rmy.android.http_shortcuts.exceptions.InvalidContentTypeException
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import java.net.URLEncoder
object RequestUtil {
const val FORM_MULTIPART_BOUNDARY = "----53014704754052338"
const val FORM_MULTIPART_CONTENT_TYPE = "multipart/form-data; boundary=$FORM_MULTIPART_BOUNDARY"
const val FORM_URLENCODE_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8"
private const val DEFAULT_CONTENT_TYPE = "text/plain"
private const val PARAMETER_ENCODING = "UTF-8"
fun encode(text: String): String =
URLEncoder.encode(text, PARAMETER_ENCODING)
fun sanitize(text: String): String =
text.replace("\"", "")
fun getMediaType(contentType: String?): MediaType =
try {
(contentType ?: DEFAULT_CONTENT_TYPE).toMediaType()
} catch (e: IllegalArgumentException) {
throw InvalidContentTypeException(contentType!!)
}
}
| mit | b840f0b0b2c088e87b1b1197cf9ca684 | 34.62069 | 100 | 0.715392 | 4.182186 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/util/HomeRoomsViewModel.kt | 2 | 4256 | /*
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.util
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.data.Room
import org.matrix.androidsdk.data.RoomTag
/**
* This class is responsible for filtering and ranking rooms whenever there is a need to update in the context of the HomeScreens
*/
class HomeRoomsViewModel(private val session: MXSession) {
/**
* A data class holding the result of filtering and ranking algorithm
* A room can't be in multiple lists at the same time.
* Order is favourites -> directChats -> otherRooms -> lowPriorities -> serverNotices
*/
data class Result(val favourites: List<Room> = emptyList(),
val directChats: List<Room> = emptyList(),
val otherRooms: List<Room> = emptyList(),
val lowPriorities: List<Room> = emptyList(),
val serverNotices: List<Room> = emptyList()) {
/**
* Use this method when you need to get all the directChats, favorites included
* Low Priorities are always excluded
*/
fun getDirectChatsWithFavorites(): List<Room> {
return directChats + favourites.filter { it.isDirect }
}
/**
* Use this method when you need to get all the other rooms, favorites included
* Low Priorities are always excluded
*/
fun getOtherRoomsWithFavorites(): List<Room> {
return otherRooms + favourites.filter { !it.isDirect }
}
}
/**
* The last result
*/
var result = Result()
/**
* The update method
* This method should be called whenever the room data have changed
*/
//TODO Take it off the main thread using coroutine
fun update(): Result {
val favourites = ArrayList<Room>()
val directChats = ArrayList<Room>()
val otherRooms = ArrayList<Room>()
val lowPriorities = ArrayList<Room>()
val serverNotices = ArrayList<Room>()
val joinedRooms = getJoinedRooms()
for (room in joinedRooms) {
val tags = room.accountData?.keys ?: emptySet()
when {
tags.contains(RoomTag.ROOM_TAG_SERVER_NOTICE) -> serverNotices.add(room)
tags.contains(RoomTag.ROOM_TAG_FAVOURITE) -> favourites.add(room)
tags.contains(RoomTag.ROOM_TAG_LOW_PRIORITY) -> lowPriorities.add(room)
RoomUtils.isDirectChat(session, room.roomId) -> directChats.add(room)
else -> otherRooms.add(room)
}
}
result = Result(
favourites = favourites,
directChats = directChats,
otherRooms = otherRooms,
lowPriorities = lowPriorities,
serverNotices = serverNotices)
Log.d("HomeRoomsViewModel", result.toString())
return result
}
//region private methods
private fun getJoinedRooms(): List<Room> {
return session.dataHandler.store?.rooms?.filter {
val isJoined = it.isJoined
val tombstoneContent = it.state.roomTombstoneContent
val redirectRoom = if (tombstoneContent?.replacementRoom != null) {
session.dataHandler.getRoom(tombstoneContent.replacementRoom)
} else {
null
}
val isVersioned = redirectRoom?.isJoined
?: false
isJoined && !isVersioned && !it.isConferenceUserRoom
} .orEmpty()
}
//endregion
}
| apache-2.0 | 1096eccdc3deb77fdb40d90018425f5c | 36.663717 | 129 | 0.608318 | 4.798196 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/androidTest/java/androidx/core/text/SpannableStringTest.kt | 1 | 2803 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.text
import android.graphics.Typeface.BOLD
import android.text.SpannableString
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class SpannableStringTest {
@Test fun toSpannableString() = assertTrue("Hello, World".toSpannable() is SpannableString)
@Test fun plusAssign() {
val s = "Hello, World".toSpannable()
val bold = StyleSpan(BOLD)
s += bold
assertEquals(0, s.getSpanStart(bold))
assertEquals(s.length, s.getSpanEnd(bold))
}
@Test fun minusAssign() {
val s = "Hello, World".toSpannable()
val bold = StyleSpan(BOLD)
s += bold
assertTrue(s.getSpans<Any>().isNotEmpty())
s -= bold
assertTrue(s.getSpans<Any>().isEmpty())
}
@Test fun clearSpans() {
val s = "Hello, World".toSpannable()
s += StyleSpan(BOLD)
s += UnderlineSpan()
assertTrue(s.getSpans<Any>().isNotEmpty())
s.clearSpans()
assertTrue(s.getSpans<Any>().isEmpty())
}
@Test fun setIndices() {
val s = "Hello, World".toSpannable()
s[0, 5] = StyleSpan(BOLD)
s[7, 12] = UnderlineSpan()
val spans = s.getSpans<Any>()
val bold = spans.filterIsInstance<StyleSpan>().single()
assertEquals(0, s.getSpanStart(bold))
assertEquals(5, s.getSpanEnd(bold))
val underline = spans.filterIsInstance<UnderlineSpan>().single()
assertEquals(7, s.getSpanStart(underline))
assertEquals(12, s.getSpanEnd(underline))
}
@Test fun setRange() {
val s = "Hello, World".toSpannable()
s[0..5] = StyleSpan(BOLD)
s[7..12] = UnderlineSpan()
val spans = s.getSpans<Any>()
val bold = spans.filterIsInstance<StyleSpan>().single()
assertEquals(0, s.getSpanStart(bold))
assertEquals(5, s.getSpanEnd(bold))
val underline = spans.filterIsInstance<UnderlineSpan>().single()
assertEquals(7, s.getSpanStart(underline))
assertEquals(12, s.getSpanEnd(underline))
}
}
| apache-2.0 | 1b73b247683e377b10103dec0b048d27 | 30.494382 | 95 | 0.651445 | 4.196108 | false | true | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/settings/ui/SdkTable.kt | 1 | 3597 | package settings.ui
import MayaBundle as Loc
import settings.ApplicationSettings
import utils.Delegate
import utils.Event
import flavors.MayaSdkFlavor as MyMayaSdkFlavor
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.AddEditRemovePanel
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.ToolbarDecorator
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.python.sdk.flavors.MayaSdkFlavor
import com.jetbrains.python.sdk.getOrCreateAdditionalData
import java.awt.BorderLayout
private class SdkTableModel : AddEditRemovePanel.TableModel<ApplicationSettings.SdkInfo>() {
override fun getColumnCount(): Int {
return 2
}
override fun getColumnName(cIndex: Int): String {
return if (cIndex == 0) Loc.message("mayacharm.sdktable.MayaVersion") else Loc.message("mayacharm.sdktable.CommandPort")
}
override fun getField(o: ApplicationSettings.SdkInfo, cIndex: Int): Any {
return if (cIndex == 0) o.mayaPyPath else o.port
}
}
private val model = SdkTableModel()
class SdkTablePanel(private val project: Project) :
AddEditRemovePanel<ApplicationSettings.SdkInfo>(model, arrayListOf()) {
private val onChanged = Delegate<SdkTablePanel>()
val changed: Event<SdkTablePanel> get() = onChanged
override fun addItem(): ApplicationSettings.SdkInfo? {
val existingSdks = PythonSdkUtil.getAllLocalCPythons().filter {
!data.map { sdkInfo -> sdkInfo.mayaPyPath }.contains(it.homePath) && it.getOrCreateAdditionalData().run {
flavor == MayaSdkFlavor.INSTANCE || flavor == MyMayaSdkFlavor.INSTANCE
}
}
val dialog = SdkAddDialog(project, existingSdks)
dialog.show()
val selectedSdk = dialog.getOrCreateSdk() ?: return null
SdkConfigurationUtil.addSdk(selectedSdk)
selectedSdk.homePath?.let {
val unusedPort = ApplicationSettings.INSTANCE.getUnusedPort()
onChanged(this)
return ApplicationSettings.SdkInfo(it, unusedPort)
}
return null
}
override fun removeItem(sdkInfo: ApplicationSettings.SdkInfo): Boolean {
val result = Messages.showDialog(
Loc.message("mayacharm.sdkremove.RemoveWarning"), Loc.message("mayacharm.sdkremove.Title"),
arrayOf(Loc.message("mayacharm.Yes"), Loc.message("mayacharm.No")), 0,
IconLoader.getIcon("/icons/[email protected]", this::class.java)
) == 0
if (result) {
val sdk = PythonSdkUtil.findSdkByPath(sdkInfo.mayaPyPath) ?: return false
SdkConfigurationUtil.removeSdk(sdk)
}
onChanged(this)
return result
}
override fun editItem(o: ApplicationSettings.SdkInfo): ApplicationSettings.SdkInfo {
val dialog = SdkEditDialog(project, o)
dialog.show()
onChanged(this)
return dialog.result
}
override fun initPanel() {
layout = BorderLayout()
val decorator = ToolbarDecorator.createDecorator(table).apply {
setAddAction { doAdd() }
setEditAction { doEdit() }
setRemoveAction { doRemove() }
}
val panel = decorator.createPanel()
add(panel, BorderLayout.CENTER)
labelText?.apply {
UIUtil.addBorder(panel, IdeBorderFactory.createTitledBorder(this, false))
}
}
}
| mit | cba9fbe9f8becc972cfe3b6c0ef7fe9d | 34.613861 | 128 | 0.693078 | 4.653299 | false | false | false | false |
bdelville/bohurt-mapper | app/src/main/java/eu/hithredin/bohurt/mapper/view/framework/BaseActivity.kt | 1 | 1957 | package eu.hithredin.bohurt.mapper.view.framework
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.github.salomonbrys.kodein.KodeinInjector
import eu.hithredin.bohurt.common.mvp.presenter.Presenter
import eu.hithredin.bohurt.mapper.R
import eu.hithredin.bohurt.mapper.app.BohurtApp
/**
* Functionality needed by all activities are declared here
*/
abstract class BaseActivity : AppCompatActivity() {
protected val injector = KodeinInjector()
// Allow Composition of Presenters for a View
private var presenters: List<Lazy<Presenter>> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injector.inject((application as BohurtApp).kodein)
}
override fun onStart() {
super.onStart()
presenters.forEach { it.value.screenOpen() }
}
override fun onStop() {
presenters.forEach { it.value.screenClose() }
super.onStop()
}
protected fun <T : Presenter> loadPresenter(init: () -> T) = lazy(init)
.also { presenters += it }
/**
* Set the main LayoutFragment to the activity. Can be overridden for custom animations
*/
protected fun setFragment(fragment: Fragment) {
if (fragment.arguments == null) fragment.arguments = Bundle()
fragment.arguments.putAll(intent.extras)
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_layout, fragment, "MainFragment")
transaction.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// Respond to the action bar's Up/Home button
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
} | gpl-3.0 | 958eae389fde1031843606efbd42b557 | 31.098361 | 91 | 0.677057 | 4.368304 | false | false | false | false |
blhps/lifeograph-android | app/src/main/java/net/sourceforge/lifeograph/FragmentDiaryEditor.kt | 1 | 3384 | /* *********************************************************************************
Copyright (C) 2012-2021 Ahmet Öztürk ([email protected])
This file is part of Lifeograph.
Lifeograph 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.
Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
package net.sourceforge.lifeograph
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
abstract class FragmentDiaryEditor : Fragment() {
// VARIABLES ===================================================================================
protected abstract val mLayoutId: Int
protected abstract val mMenuId: Int
protected lateinit var mMenu: Menu
val isMenuInitialized get() = this::mMenu.isInitialized
// METHODS =====================================================================================
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(mMenuId > 0)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstState: Bundle?): View? {
Log.d(Lifeograph.TAG, "FragmentChartList.onCreateView()")
return inflater.inflate(mLayoutId, container, false)
}
// override fun onResume() {
// super.onResume()
// if(this::mMenu.isInitialized)
// updateMenuVisibilities()
// }
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
if(mMenuId > 0)
inflater.inflate(mMenuId, menu)
super.onCreateOptionsMenu(menu, inflater)
mMenu = menu
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
updateMenuVisibilities()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
R.id.home -> {
handleBack()
}
R.id.enable_edit -> {
Lifeograph.enableEditing(this)
true
}
R.id.logout_wo_save -> {
Lifeograph.logoutWithoutSaving(requireView())
true
}
else ->
super.onOptionsItemSelected(item)
}
}
open fun updateMenuVisibilities() {
val flagWritable = Diary.d.is_in_edit_mode
mMenu.findItem(R.id.enable_edit).isVisible = !flagWritable &&
Diary.d.can_enter_edit_mode()
mMenu.findItem(R.id.logout_wo_save).isVisible = flagWritable
}
open fun enableEditing() {
updateMenuVisibilities()
}
open fun handleBack(): Boolean {
return false
}
}
| gpl-3.0 | 26f155e31d535fd83d44f8e1675c9d1a | 32.485149 | 100 | 0.570373 | 5.195084 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/impl/mixins/SkinResourceMixin.kt | 1 | 3852 | package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.mixins
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinClassSpecification
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinObject
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinResource
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinStringLiteral
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.SkinElementImpl
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.factory
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.getRealClassNamesAsString
import com.gmail.blueboxware.libgdxplugin.utils.COLOR_CLASS_NAME
import com.gmail.blueboxware.libgdxplugin.utils.createColorIcon
import com.gmail.blueboxware.libgdxplugin.utils.firstParent
import com.intellij.icons.AllIcons
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.search.allScope
import java.awt.Color
import javax.swing.Icon
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
abstract class SkinResourceMixin(node: ASTNode) : SkinResource, SkinElementImpl(node) {
override fun getName() = resourceName.stringLiteral.value
override fun getNameIdentifier() = resourceName
override fun getObject(): SkinObject? = value as? SkinObject
override fun getString(): SkinStringLiteral? = value as? SkinStringLiteral
override fun getClassSpecification(): SkinClassSpecification? = firstParent()
override fun getUseScope() = project.allScope()
override fun findDefinition(): SkinResource? {
var element: SkinResource? = this
while (element?.string != null) {
element = element.string?.reference?.resolve() as? SkinResource
}
return element
}
override fun asColor(force: Boolean): Color? =
(findDefinition()?.value as? SkinObject)
?.asColor(
force || classSpecification?.getRealClassNamesAsString()?.contains(COLOR_CLASS_NAME) == true
)
override fun setName(name: String): PsiElement? {
factory()?.createResourceName(name, nameIdentifier.stringLiteral.isQuoted)?.let { newResourceName ->
resourceName.replace(newResourceName)
return newResourceName
}
return null
}
override fun getPresentation(): ItemPresentation = object : ItemPresentation {
override fun getLocationString(): String? =
project.guessProjectDir()?.let {
VfsUtil.getRelativeLocation(containingFile.virtualFile, it)
}
override fun getIcon(unused: Boolean): Icon {
val force = this@SkinResourceMixin
.firstParent<SkinClassSpecification>()
?.getRealClassNamesAsString()
?.contains(COLOR_CLASS_NAME)
?: false
return (value as? SkinObject)?.asColor(force)?.let { createColorIcon(it) } ?: AllIcons.FileTypes.Properties
}
override fun getPresentableText(): String = name
}
override fun toString(): String = "SkinResource(${resourceName.stringLiteral.text})"
}
| apache-2.0 | 82eb6b52ac5df0d2b4591a0712b3f61e | 37.909091 | 119 | 0.729491 | 4.749692 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/onboarding/steps/LoginStep.kt | 1 | 6010 | package com.voipgrid.vialer.onboarding.steps
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.voipgrid.vialer.*
import com.voipgrid.vialer.logging.Logger
import com.voipgrid.vialer.onboarding.VoipgridLogin
import com.voipgrid.vialer.onboarding.VoipgridLogin.LoginResult
import com.voipgrid.vialer.onboarding.VoipgridLogin.LoginResult.*
import com.voipgrid.vialer.onboarding.core.Step
import com.voipgrid.vialer.util.ConnectivityHelper
import com.voipgrid.vialer.util.TwoFactorFragmentHelper
import com.voipgrid.vialer.voipgrid.PasswordResetWebActivity
import kotlinx.android.synthetic.main.onboarding_step_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import javax.inject.Inject
class LoginStep : Step() {
override val layout = R.layout.onboarding_step_login
@Inject lateinit var connectivityHelper: ConnectivityHelper
@Inject lateinit var login: VoipgridLogin
private val logger = Logger(this).forceRemoteLogging(true)
private var twoFactorHelper: TwoFactorFragmentHelper? = null
private var twoFactorDialog: AlertDialog? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
VialerApplication.get().component().inject(this)
val enableSubmitButton: (_: Editable?) -> Unit = {
button_login.isEnabled = emailTextDialog.length() > 0 && passwordTextDialog.length() > 0
}
emailTextDialog.onTextChanged(enableSubmitButton)
passwordTextDialog.onTextChanged(enableSubmitButton)
passwordTextDialog.setOnEditorActionListener { _: TextView, actionId: Int, _: KeyEvent? ->
actionId == EditorInfo.IME_ACTION_DONE && button_login.performClick()
}
button_login.setOnClickListenerAndDisable {
emailTextDialog.clearFocus()
passwordTextDialog.clearFocus()
attemptLogin()
}
button_forgot_password.setOnClickListener { launchForgottenPasswordActivity() }
automaticallyLogInIfWeHaveCredentials()
}
override fun onResume() {
super.onResume()
twoFactorHelper?.pasteCodeFromClipboard()
}
/**
* If this activity has been started with an intent containing credentials, log in with them automatically.
*
*/
private fun automaticallyLogInIfWeHaveCredentials() {
val intent = activity?.intent ?: return
if (!intent.hasExtra(PasswordResetWebActivity.USERNAME_EXTRA) || !intent.hasExtra(PasswordResetWebActivity.PASSWORD_EXTRA)) {
return
}
emailTextDialog.setText(intent.getStringExtra(PasswordResetWebActivity.USERNAME_EXTRA))
passwordTextDialog.setText(intent.getStringExtra(PasswordResetWebActivity.PASSWORD_EXTRA))
if (button_login.isEnabled) button_login.performClick()
}
/**
* Attempt to log the user into VoIPGRID by launching a co-routine.
*
*/
private fun attemptLogin(code: String? = null) = GlobalScope.launch(Dispatchers.Main) {
onboarding?.isLoading = true
logger.i("Attempting to log the user into VoIPGRID, with the following 2FA code: $code")
val result = login.attempt(emailTextDialog.text.toString(), passwordTextDialog.text.toString(), code)
onboarding?.isLoading = false
handleLoginResult(result)
}
/**
* Perform different actions based on the result of an attempted login.
*
*/
private fun handleLoginResult(result: LoginResult) = when(result) {
FAIL -> {
logger.w("User failed to login to VoIPGRID")
login.lastError?.let { error(it.title, it.description) }
button_login.isEnabled = true
}
SUCCESS -> {
logger.i("Login to VoIPGRID was successful, progressing the user in onboarding")
twoFactorDialog?.dismiss()
onboarding?.progress(this)
}
TWO_FACTOR_REQUIRED -> {
logger.i("User logged into VoIPGRID with the correct username/password but is now required to input a valid 2FA code")
button_login.isEnabled = true
showTwoFactorDialog()
}
MUST_CHANGE_PASSWORD -> {
logger.i("User must change their password before we can login")
activity?.let {
PasswordResetWebActivity.launch(it, emailTextDialog.text.toString(), passwordTextDialog.text.toString())
}
}
}
/**
* Create and show a dialog for the user to enter a two-factor token.
*
*/
private fun showTwoFactorDialog() {
activity?.let {
val twoFactorDialog = AlertDialog.Builder(it)
.setView(R.layout.onboarding_dialog_two_factor)
.show()
val codeField = (twoFactorDialog.findViewById(R.id.two_factor_code_field) as EditText)
twoFactorHelper = TwoFactorFragmentHelper(it, codeField).apply {
focusOnTokenField()
pasteCodeFromClipboard()
}
(twoFactorDialog.findViewById(R.id.button_continue) as Button).setOnClickListener {
onboarding?.isLoading = true
attemptLogin(codeField.text.toString())
}
this.twoFactorDialog = twoFactorDialog
}
}
/**
* Launches an activity to allow the user to reset their password.
*
*/
private fun launchForgottenPasswordActivity() {
logger.i("Detected forgot password click, launching activity")
ForgottenPasswordActivity.launchForEmail(onboarding as Context, emailTextDialog.text.toString())
}
} | gpl-3.0 | b37819272437e70b383b2af90795e3df | 36.805031 | 133 | 0.687188 | 4.781225 | false | false | false | false |
codeforgreenville/trolley-tracker-android-client | app/src/main/java/com/codeforgvl/trolleytrackerclient/Constants.kt | 1 | 2601 | package com.codeforgvl.trolleytrackerclient
import android.content.Context
import android.support.v4.content.ContextCompat
class Constants {
companion object {
const val LOG_TAG = "TROLLEYTRACKER"
const val ROUTE_UPDATE_INTERVAL = 15
const val SLEEP_INTERVAL = 5000
const val LOCATION_PERMISSION_REQUEST_ID = 1
val HOST =
if (BuildConfig.DEBUG) "yeahthattrolley.azurewebsites.net" else "api.yeahthattrolley.com"
val API_PATH = "/api/v1/"
// var ALL_TROLLEYS_ENDPOINT =
// var RUNNING_TROLLEYS_ENDPOINT =
// var ACTIVE_ROUTES_ENDPOINT =
// var ROUTE_SCHEDULE_ENDPOINT =
private val ROUTE_DETAILS_ENDPOINT = "http://" + HOST + API_PATH + "Routes/"
fun getRouteDetailsEndpoint(routeId: Int): String {
return ROUTE_DETAILS_ENDPOINT + routeId
}
fun getAllTrolleysEndpoint(): String {
return """http://$HOST${API_PATH}Trolleys""" // Complete trolley record - all trolleys
}
fun getRunningTrolleysEndpoint(): String {
return """http://$HOST${API_PATH}Trolleys/Running"""
}
fun getActiveRoutesEndpoint(): String {
return """http://$HOST${API_PATH}Routes/Active"""
}
fun getRouteScheduleEndpoint(): String {
return """http://$HOST${API_PATH}RouteSchedules"""
}
fun getRouteColorForRouteNumber(context: Context, ndx: Int): Int {
val routeNo = ndx % 5 + 1
return when (routeNo) {
1 -> ContextCompat.getColor(context, R.color.route1)
2 -> ContextCompat.getColor(context, R.color.route2)
3 -> ContextCompat.getColor(context, R.color.route3)
4 -> ContextCompat.getColor(context, R.color.route4)
else -> ContextCompat.getColor(context, R.color.route5)
}
}
fun getStopColorForRouteNumber(context: Context, ndx: Int): Int {
val routeNo = ndx % 5 + 1
return when (routeNo) {
1 -> ContextCompat.getColor(context, R.color.stop1)
2 -> ContextCompat.getColor(context, R.color.stop2)
3 -> ContextCompat.getColor(context, R.color.stop3)
4 -> ContextCompat.getColor(context, R.color.stop4)
else -> ContextCompat.getColor(context, R.color.stop5)
}
}
}
enum class DayOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
} | mit | 5bc52327e0386d64b27e154f627cc22d | 33.236842 | 101 | 0.583237 | 4.076803 | false | false | false | false |
faruktoptas/FancyShowCaseView | fancyshowcaseview/src/main/java/me/toptas/fancyshowcase/internal/DeviceParams.kt | 1 | 1638 | package me.toptas.fancyshowcase.internal
import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat
import me.toptas.fancyshowcase.R
internal interface DeviceParams {
fun currentBackgroundColor(): Int
fun deviceWidth(): Int
fun deviceHeight(): Int
fun getStatusBarHeight(): Int
fun isFullScreen(): Boolean
fun aboveAPI19(): Boolean
}
internal class DeviceParamsImpl(private val activity: Activity, view: View) : DeviceParams {
private val metrics = DisplayMetrics()
init {
activity.windowManager.defaultDisplay.getMetrics(metrics)
}
override fun currentBackgroundColor() = ContextCompat
.getColor(activity, R.color.fancy_showcase_view_default_background_color)
override fun deviceWidth() = metrics.widthPixels
override fun deviceHeight() = metrics.heightPixels
override fun getStatusBarHeight() = getStatusBarHeight(activity)
override fun isFullScreen(): Boolean {
val windowFlags = activity.window.attributes.flags
return (windowFlags and WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
}
override fun aboveAPI19() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
}
internal fun getStatusBarHeight(context: Context): Int {
var result = 0
val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = context.resources.getDimensionPixelSize(resourceId)
}
return result
} | apache-2.0 | b5e83a185128744f926f7241874ea487 | 29.924528 | 93 | 0.7442 | 4.653409 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/map/EmptyStateMap.kt | 3 | 506 | package com.github.sybila.checker.map
import com.github.sybila.checker.StateMap
class EmptyStateMap<out Params : Any>(
private val default: Params
) : StateMap<Params> {
override fun states(): Iterator<Int> = emptySequence<Int>().iterator()
override fun entries(): Iterator<Pair<Int, Params>> = emptySequence<Pair<Int, Params>>().iterator()
override fun get(state: Int): Params = default
override fun contains(state: Int): Boolean = false
override val sizeHint: Int = 0
} | gpl-3.0 | dca1219e1a0328881cadf709b30f8d30 | 27.166667 | 103 | 0.705534 | 4.147541 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/main/kotlin/edu/kit/iti/formal/automation/st0/trans/TimerSimplifier.kt | 1 | 3080 | package edu.kit.iti.formal.automation.st0.trans
/*-
* #%L
* iec-symbex
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.automation.datatypes.TimeType
import edu.kit.iti.formal.automation.datatypes.UINT
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.RefTo
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstMutableVisitor
import edu.kit.iti.formal.automation.st0.MultiCodeTransformation
import edu.kit.iti.formal.automation.st0.TransformationState
import java.math.BigInteger
/**
* @author Alexander Weigl (06.07.2014), Augusto Modanese
* @version 1
*/
class TimerSimplifier(val cycleTime: Long = DEFAULT_CYCLE_TIME) : MultiCodeTransformation() {
init {
transformations += TimeLiteralToCounter()
}
inner class TimeLiteralToCounter : AstMutableVisitor(), CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(this) as StatementList
state.scope = state.scope.accept(this) as Scope
return state
}
override fun visit(vd: VariableDeclaration): VariableDeclaration {
if (vd.dataType === TimeType.TIME_TYPE) {
val newVariable = VariableDeclaration(vd.name, vd.type, UINT)
val cycles = (vd.init as TimeLit?)
val sd = SimpleTypeDeclaration(
baseType = RefTo(UINT),
initialization = translate(cycles)
)
newVariable.typeDeclaration = sd
return newVariable
}
return super.visit(vd)
}
override fun visit(literal: Literal) =
when (literal) {
is TimeLit -> translate(literal)
else -> super.visit(literal)
}
private fun translate(literal: TimeLit?): IntegerLit {
if (literal == null) {
return IntegerLit(UINT, BigInteger.ZERO)
}
val value = literal.asValue()
val data = value.value
val cycles = (data.milliseconds / cycleTime).toInt()
return IntegerLit(UINT, cycles.toBigInteger())
}
}
companion object {
var DEFAULT_CYCLE_TIME: Long = 4
}
}
| gpl-3.0 | 0d516d10e56b094cfdbbfc169631cdf0 | 34.813953 | 93 | 0.646104 | 4.307692 | false | false | false | false |
SoulBeaver/Arena--7DRL- | src/test/java/com/sbg/arena/core/procedural_content_generation/CaveGeneratorSpec.kt | 1 | 1161 | package com.sbg.arena.core.procedural_content_generation
import org.spek.Spek
import com.sbg.arena.configuration.loadConfiguration
import kotlin.test.assertTrue
import kotlin.test.assertEquals
import com.sbg.arena.core.Dimension
import com.sbg.arena.util.iterable
import com.sbg.arena.core.Level
import java.util.Random
import com.sbg.arena.core.level.FloorType
class CaveGeneratorSpec: Spek() {{
given("A cave generator with sensible configuration") {
val configurationUrl = javaClass<CaveGeneratorSpec>().getClassLoader()!!.getResource("settings.yml")!!
val configuration = loadConfiguration(configurationUrl.getPath()!!.substring(1))
val caveGenerator = CaveGenerator(configuration)
on("generating a 50x50 cave") {
val cave = caveGenerator.generate(Dimension(50, 50))
it("should be 2500 floors large") {
assertEquals(50*50, cave.area)
}
it("should be partially filled with walls") {
val numberOfWalls = cave.iterable().count { it == FloorType.Wall }
assertTrue(numberOfWalls != 0)
}
}
}
}}
| apache-2.0 | 5cf67ea65af52bef936fc611f1fe09f4 | 34.181818 | 110 | 0.67528 | 4.3 | false | true | false | false |
AlmasB/FXGL | fxgl-core/src/main/kotlin/com/almasb/fxgl/logging/LoggerConfig.kt | 1 | 710 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.logging
import java.time.format.DateTimeFormatter
/**
* Config data structure that allows setting custom date-time and message formatters.
*
* @author Almas Baimagambetov ([email protected])
*/
class LoggerConfig {
var dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS")
var messageFormatter = DefaultMessageFormatter()
internal fun copy(): LoggerConfig {
val copy = LoggerConfig()
copy.dateTimeFormatter = dateTimeFormatter
copy.messageFormatter = messageFormatter
return copy
}
} | mit | ed338abb2d7512c92406acff1ac13e6f | 25.333333 | 85 | 0.714085 | 4.4375 | false | true | false | false |
android/android-dev-challenge-compose | app/src/main/java/com/google/ads22/speedchallenge/data/ForecastRepository.kt | 1 | 5679 | /*
* 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.google.ads22.speedchallenge.data
import com.google.ads22.speedchallenge.data.WeatherIcon.CLOUDY
import com.google.ads22.speedchallenge.data.WeatherIcon.OVERCAST
import com.google.ads22.speedchallenge.data.WeatherIcon.SUNNY
import com.google.ads22.speedchallenge.data.WeatherIcon.THUNDERSTORM
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
interface ForecastRepository {
fun getForecast(locationId: String) : Flow<Forecast>
}
class DefaultForecastRepository @Inject constructor() : ForecastRepository {
override fun getForecast(locationId: String): Flow<Forecast> = flow {
when(locationId) {
"Sunnyvale" -> emit(fakeForecast1)
"Mountain View" -> emit(fakeForecast2)
else -> throw IllegalArgumentException()
}
}
}
data class Location(
val name: String,
// var uid: String = ""
)
data class Forecast(
val location: Location,
val forecastToday: List<ForecastTime>,
val forecastWeek: List<ForecastDay>
)
data class ForecastDay(
val day: String,
val maxTemp: Int,
val minTemp: Int,
val icon: WeatherIcon,
val times: List<ForecastTime>
)
data class ForecastTime(
val time: String,
val temp: Int,
val icon: WeatherIcon
)
enum class WeatherIcon {
SUNNY, CLOUDY, THUNDERSTORM, OVERCAST
}
val fakeForecast1 = Forecast(
location = Location("Sunnyvale"),
forecastToday = listOf(
ForecastTime(
time = "8:00 AM",
temp = 25,
icon = OVERCAST
),
ForecastTime(
time = "10:00 AM",
temp = 30,
icon = SUNNY
),
ForecastTime(
time = "Noon",
temp = 25,
icon = SUNNY
),
ForecastTime(
time = "12:00 PM",
temp = 25,
icon = OVERCAST
),
ForecastTime(
time = "2:00 PM",
temp = 25,
icon = OVERCAST
)
),
forecastWeek = listOf(
ForecastDay(
day = "Tomorrow",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(10)
),
ForecastDay(
day = "Tuesday",
maxTemp = 22,
minTemp = 14,
icon = THUNDERSTORM,
generateForecastTimes(15)
),
ForecastDay(
day = "Wednesday",
maxTemp = 27,
minTemp = 17,
icon = CLOUDY,
generateForecastTimes(20)
),
ForecastDay(
day = "Thursday",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(25)
),
ForecastDay(
day = "Friday",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(30)
),
ForecastDay(
day = "Saturday",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(35)
),
)
)
private fun generateForecastTimes(seed: Int): List<ForecastTime> {
return listOf(
ForecastTime(
time = "8:00 AM",
temp = seed + 0,
icon = CLOUDY
),
ForecastTime(
time = "10:00 AM",
temp = seed + 1,
icon = SUNNY
),
ForecastTime(
time = "Noon",
temp = seed + 2,
icon = SUNNY
),
ForecastTime(
time = "12:00 PM",
temp = seed + 3,
icon = CLOUDY
),
ForecastTime(
time = "2:00 PM",
temp = seed + 4,
icon = CLOUDY
)
)
}
val fakeForecast2 = Forecast(
location = Location("Mountain View"),
forecastToday = listOf(
ForecastTime(
time = "8:00 AM",
temp = 25,
icon = CLOUDY
),
ForecastTime(
time = "10:00 AM",
temp = 30,
icon = SUNNY
),
ForecastTime(
time = "Noon",
temp = 25,
icon = SUNNY
),
ForecastTime(
time = "12:00 PM",
temp = 25,
icon = CLOUDY
),
ForecastTime(
time = "2:00 PM",
temp = 25,
icon = CLOUDY
)
),
forecastWeek = listOf(
ForecastDay(
day = "Tomorrow",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(11)
),
ForecastDay(
day = "Wednesday",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(16)
),
ForecastDay(
day = "Thursday",
maxTemp = 32,
minTemp = 18,
icon = SUNNY,
generateForecastTimes(21)
)
)
)
| apache-2.0 | 807e4e06b2ab22bd372736866c6657db | 23.691304 | 76 | 0.514175 | 4.228593 | false | false | false | false |
industrial-data-space/trusted-connector | ids-route-manager/src/main/kotlin/de/fhg/aisec/ids/rm/util/GraphProcessor.kt | 1 | 3949 | /*-
* ========================LICENSE_START=================================
* ids-route-manager
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.rm.util
import de.fhg.aisec.ids.api.router.graph.Edge
import de.fhg.aisec.ids.api.router.graph.GraphData
import de.fhg.aisec.ids.api.router.graph.Node
import org.apache.camel.model.ChoiceDefinition
import org.apache.camel.model.OptionalIdentifiedDefinition
import org.apache.camel.model.ProcessorDefinition
import org.apache.camel.model.RouteDefinition
import java.util.concurrent.atomic.AtomicInteger
object GraphProcessor {
/**
* Prints a single Camel route in Prolog representation.
*
* @param route The route to be transformed
*/
fun processRoute(route: RouteDefinition): GraphData {
val gd = GraphData()
// Print route entry points
processInput(gd, route)
return gd
}
/**
* Prints a single node of a Camel route in Prolog representation.
*
* @param graphData
* @param current
* @param preds
* @return
*/
private fun processNode(
graphData: GraphData,
current: ProcessorDefinition<*>,
preds: List<OptionalIdentifiedDefinition<*>>
): List<ProcessorDefinition<*>> {
for (p in preds) {
graphData.addEdge(Edge(p.id, current.id))
}
graphData.addNode(
Node(
current.id,
current.label,
if (current is ChoiceDefinition) Node.NodeType.ChoiceNode else Node.NodeType.Node
)
)
// predecessor of next recursion is the current node
val newPreds: MutableList<ProcessorDefinition<*>> = ArrayList()
newPreds.add(current)
for (out in current.outputs) {
// if this is a ChoiceDefinition, there is no link between its WhereDefinitions.
val myPreds = ArrayList<OptionalIdentifiedDefinition<*>>()
if (current is ChoiceDefinition) {
myPreds.add(current)
} else {
// @TODO: Looks somewhat strange... is this correct?
myPreds.addAll(newPreds)
}
// Recursion ...
val p = processNode(graphData, out, myPreds)
// Predecessors of a ChoiceDefinition are all last stmts of its Where- and
// OtherwiseDefinitions
if (current is ChoiceDefinition) {
newPreds.addAll(p)
} else {
newPreds.clear()
newPreds.addAll(p)
}
}
return newPreds
}
/** Prints a single FromDefinition (= a route entry point) in Prolog representation. */
private fun processInput(graphData: GraphData, route: RouteDefinition) {
val counter = AtomicInteger(0)
val i = route.input
// Make sure every input node has a unique id
if (i.id == null) {
i.customId = true
i.id = "input$counter"
}
graphData.addNode(Node(i.id, i.label, Node.NodeType.EntryNode))
var prev: OptionalIdentifiedDefinition<*>? = i
for (next in route.outputs) {
processNode(graphData, next, prev?.let { listOf(it) } ?: emptyList())
prev = next
}
}
}
| apache-2.0 | b653d474a1398ddfcdd2f20d673bdacc | 34.258929 | 97 | 0.601925 | 4.472254 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/customselector/ui/selector/CustomSelectorActivity.kt | 2 | 14122 | package fr.free.nrw.commons.customselector.ui.selector
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.ViewModelProvider
import fr.free.nrw.commons.R
import fr.free.nrw.commons.customselector.database.NotForUploadStatus
import fr.free.nrw.commons.customselector.database.NotForUploadStatusDao
import fr.free.nrw.commons.customselector.helper.CustomSelectorConstants
import fr.free.nrw.commons.customselector.helper.CustomSelectorConstants.SHOULD_REFRESH
import fr.free.nrw.commons.customselector.listeners.FolderClickListener
import fr.free.nrw.commons.customselector.listeners.ImageSelectListener
import fr.free.nrw.commons.customselector.model.Image
import fr.free.nrw.commons.databinding.ActivityCustomSelectorBinding
import fr.free.nrw.commons.databinding.CustomSelectorBottomLayoutBinding
import fr.free.nrw.commons.databinding.CustomSelectorToolbarBinding
import fr.free.nrw.commons.filepicker.Constants
import fr.free.nrw.commons.media.ZoomableActivity
import fr.free.nrw.commons.theme.BaseActivity
import fr.free.nrw.commons.upload.FileUtilsWrapper
import fr.free.nrw.commons.utils.CustomSelectorUtils
import kotlinx.coroutines.*
import java.io.File
import javax.inject.Inject
/**
* Custom Selector Activity.
*/
class CustomSelectorActivity : BaseActivity(), FolderClickListener, ImageSelectListener {
/**
* ViewBindings
*/
private lateinit var binding: ActivityCustomSelectorBinding
private lateinit var toolbarBinding: CustomSelectorToolbarBinding
private lateinit var bottomSheetBinding: CustomSelectorBottomLayoutBinding
/**
* View model.
*/
private lateinit var viewModel: CustomSelectorViewModel
/**
* isImageFragmentOpen is true when the image fragment is in view.
*/
private var isImageFragmentOpen = false
/**
* Current ImageFragment attributes.
*/
private var bucketId: Long = 0L
private lateinit var bucketName: String
/**
* Pref for saving selector state.
*/
private lateinit var prefs: SharedPreferences
/**
* View Model Factory.
*/
@Inject
lateinit var customSelectorViewModelFactory: CustomSelectorViewModelFactory
/**
* NotForUploadStatus Dao class for database operations
*/
@Inject
lateinit var notForUploadStatusDao: NotForUploadStatusDao
/**
* FileUtilsWrapper class to get imageSHA1 from uri
*/
@Inject
lateinit var fileUtilsWrapper: FileUtilsWrapper
/**
* Coroutine Dispatchers and Scope.
*/
private val scope: CoroutineScope = MainScope()
private var ioDispatcher: CoroutineDispatcher = Dispatchers.IO
/**
* Image Fragment instance
*/
var imageFragment: ImageFragment? = null
/**
* onCreate Activity, sets theme, initialises the view model, setup view.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCustomSelectorBinding.inflate(layoutInflater)
toolbarBinding = CustomSelectorToolbarBinding.bind(binding.root)
bottomSheetBinding = CustomSelectorBottomLayoutBinding.bind(binding.root)
val view = binding.root
setContentView(view)
prefs = applicationContext.getSharedPreferences("CustomSelector", MODE_PRIVATE)
viewModel = ViewModelProvider(this, customSelectorViewModelFactory).get(
CustomSelectorViewModel::class.java
)
setupViews()
if (prefs.getBoolean("customSelectorFirstLaunch", true)) {
// show welcome dialog on first launch
showWelcomeDialog()
prefs.edit().putBoolean("customSelectorFirstLaunch", false).apply()
}
// Open folder if saved in prefs.
if (prefs.contains(FOLDER_ID)) {
val lastOpenFolderId: Long = prefs.getLong(FOLDER_ID, 0L)
val lastOpenFolderName: String? = prefs.getString(FOLDER_NAME, null)
val lastItemId: Long = prefs.getLong(ITEM_ID, 0)
lastOpenFolderName?.let { onFolderClick(lastOpenFolderId, it, lastItemId) }
}
}
/**
* When data will be send from full screen mode, it will be passed to fragment
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Constants.RequestCodes.RECEIVE_DATA_FROM_FULL_SCREEN_MODE &&
resultCode == Activity.RESULT_OK
) {
val selectedImages: ArrayList<Image> =
data!!
.getParcelableArrayListExtra(CustomSelectorConstants.NEW_SELECTED_IMAGES)!!
val shouldRefresh = data.getBooleanExtra(SHOULD_REFRESH, false)
imageFragment!!.passSelectedImages(selectedImages, shouldRefresh)
}
}
/**
* Show Custom Selector Welcome Dialog.
*/
private fun showWelcomeDialog() {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.custom_selector_info_dialog)
(dialog.findViewById(R.id.btn_ok) as Button).setOnClickListener { dialog.dismiss() }
dialog.show()
}
/**
* Set up view, default folder view.
*/
private fun setupViews() {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, FolderFragment.newInstance())
.commit()
fetchData()
setUpToolbar()
setUpBottomLayout()
}
/**
* Set up bottom layout
*/
private fun setUpBottomLayout() {
val done: Button = findViewById(R.id.upload)
done.setOnClickListener { onDone() }
val notForUpload: Button = findViewById(R.id.not_for_upload)
notForUpload.setOnClickListener { onClickNotForUpload() }
}
/**
* Gets selected images and proceed for database operations
*/
private fun onClickNotForUpload() {
val selectedImages = viewModel.selectedImages.value
if (selectedImages.isNullOrEmpty()) {
markAsNotForUpload(arrayListOf())
return
}
var i = 0
while (i < selectedImages.size) {
val path = selectedImages[i].path
val file = File(path)
if (!file.exists()) {
selectedImages.removeAt(i)
i--
}
i++
}
markAsNotForUpload(selectedImages)
}
/**
* Insert selected images in the database
*/
private fun markAsNotForUpload(images: ArrayList<Image>) {
insertIntoNotForUpload(images)
}
/**
* Initializing ImageFragment
*/
fun setOnDataListener(imageFragment: ImageFragment?) {
this.imageFragment = imageFragment
}
/**
* Insert images into not for upload
* Remove images from not for upload
* Refresh the UI
*/
private fun insertIntoNotForUpload(images: ArrayList<Image>) {
scope.launch {
var allImagesAlreadyNotForUpload = true
images.forEach {
val imageSHA1 = CustomSelectorUtils.getImageSHA1(
it.uri,
ioDispatcher,
fileUtilsWrapper,
contentResolver
)
val exists = notForUploadStatusDao.find(imageSHA1)
// If image exists in not for upload table make allImagesAlreadyNotForUpload false
if (exists < 1) {
allImagesAlreadyNotForUpload = false
}
}
// if all images is not already marked as not for upload, insert all images in
// not for upload table
if (!allImagesAlreadyNotForUpload) {
images.forEach {
val imageSHA1 = CustomSelectorUtils.getImageSHA1(
it.uri,
ioDispatcher,
fileUtilsWrapper,
contentResolver
)
notForUploadStatusDao.insert(
NotForUploadStatus(
imageSHA1
)
)
}
// if all images is already marked as not for upload, delete all images from
// not for upload table
} else {
images.forEach {
val imageSHA1 = CustomSelectorUtils.getImageSHA1(
it.uri,
ioDispatcher,
fileUtilsWrapper,
contentResolver
)
notForUploadStatusDao.deleteNotForUploadWithImageSHA1(imageSHA1)
}
}
imageFragment!!.refresh()
val bottomLayout: ConstraintLayout = findViewById(R.id.bottom_layout)
bottomLayout.visibility = View.GONE
}
}
/**
* Start data fetch in view model.
*/
private fun fetchData() {
viewModel.fetchImages()
}
/**
* Change the title of the toolbar.
*/
private fun changeTitle(title: String) {
val titleText = findViewById<TextView>(R.id.title)
if (titleText != null) {
titleText.text = title
}
}
/**
* Set up the toolbar, back listener, done listener.
*/
private fun setUpToolbar() {
val back: ImageButton = findViewById(R.id.back)
back.setOnClickListener { onBackPressed() }
}
/**
* override on folder click, change the toolbar title on folder click.
*/
override fun onFolderClick(folderId: Long, folderName: String, lastItemId: Long) {
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, ImageFragment.newInstance(folderId, lastItemId))
.addToBackStack(null)
.commit()
changeTitle(folderName)
bucketId = folderId
bucketName = folderName
isImageFragmentOpen = true
}
/**
* override Selected Images Change, update view model selected images and change UI.
*/
override fun onSelectedImagesChanged(
selectedImages: ArrayList<Image>,
selectedNotForUploadImages: Int
) {
viewModel.selectedImages.value = selectedImages
if (selectedNotForUploadImages > 0) {
bottomSheetBinding.upload.isEnabled = false
bottomSheetBinding.upload.alpha = 0.5f
} else {
bottomSheetBinding.upload.isEnabled = true
bottomSheetBinding.upload.alpha = 1f
}
bottomSheetBinding.notForUpload.text =
when (selectedImages.size == selectedNotForUploadImages) {
true -> getString(R.string.unmark_as_not_for_upload)
else -> getString(R.string.mark_as_not_for_upload)
}
val bottomLayout: ConstraintLayout = findViewById(R.id.bottom_layout)
bottomLayout.visibility = if (selectedImages.isEmpty()) View.GONE else View.VISIBLE
}
/**
* onLongPress
* @param imageUri : uri of image
*/
override fun onLongPress(
position: Int,
images: ArrayList<Image>,
selectedImages: ArrayList<Image>
) {
val intent = Intent(this, ZoomableActivity::class.java)
intent.putExtra(CustomSelectorConstants.PRESENT_POSITION, position)
intent.putParcelableArrayListExtra(
CustomSelectorConstants.TOTAL_SELECTED_IMAGES,
selectedImages
)
intent.putExtra(CustomSelectorConstants.BUCKET_ID, bucketId)
startActivityForResult(intent, Constants.RequestCodes.RECEIVE_DATA_FROM_FULL_SCREEN_MODE)
}
/**
* OnDone clicked.
* Get the selected images. Remove any non existent file, forward the data to finish selector.
*/
fun onDone() {
val selectedImages = viewModel.selectedImages.value
if (selectedImages.isNullOrEmpty()) {
finishPickImages(arrayListOf())
return
}
var i = 0
while (i < selectedImages.size) {
val path = selectedImages[i].path
val file = File(path)
if (!file.exists()) {
selectedImages.removeAt(i)
i--
}
i++
}
finishPickImages(selectedImages)
}
/**
* finishPickImages, Load the data to the intent and set result.
* Finish the activity.
*/
private fun finishPickImages(images: ArrayList<Image>) {
val data = Intent()
data.putParcelableArrayListExtra("Images", images)
setResult(Activity.RESULT_OK, data)
finish()
}
/**
* Back pressed.
* Change toolbar title.
*/
override fun onBackPressed() {
super.onBackPressed()
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment != null && fragment is FolderFragment) {
isImageFragmentOpen = false
changeTitle(getString(R.string.custom_selector_title))
}
}
/**
* On activity destroy
* If image fragment is open, overwrite its attributes otherwise discard the values.
*/
override fun onDestroy() {
if (isImageFragmentOpen) {
prefs.edit().putLong(FOLDER_ID, bucketId).putString(FOLDER_NAME, bucketName).apply()
} else {
prefs.edit().remove(FOLDER_ID).remove(FOLDER_NAME).apply()
}
super.onDestroy()
}
companion object {
const val FOLDER_ID: String = "FolderId"
const val FOLDER_NAME: String = "FolderName"
const val ITEM_ID: String = "ItemId"
}
} | apache-2.0 | f06df11134c3f5f6f74382d4d3ac2193 | 31.920746 | 98 | 0.628948 | 5.022048 | false | false | false | false |
mbernier85/pet-finder | app/src/main/java/im/bernier/petfinder/adapter/PetAdapter.kt | 1 | 3002 | /*
* 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/.
*
* If it is not possible or desirable to put the notice in a particular
* file, then You may include the notice in a location (such as a LICENSE
* file in a relevant directory) where a recipient would be likely to look
* for such a notice.
*
* You may add additional accurate notices of copyright ownership.
*/
package im.bernier.petfinder.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import im.bernier.petfinder.GlideApp
import im.bernier.petfinder.R
import im.bernier.petfinder.model.Pet
import java.util.*
/**
* Created by Michael on 2016-07-09.
*/
class PetAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<PetAdapter.PetViewHolder>() {
private var pets = ArrayList<Pet>()
private var petClick: PetClick? = null
interface PetClick {
fun onClick(pet: Pet)
}
fun setPetClick(petClick: PetClick) {
this.petClick = petClick
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PetViewHolder {
val holder = PetViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_pet, parent, false))
holder.cardView.setOnClickListener { _ ->
if (petClick != null) {
holder.pet?.let { petClick?.onClick(it) }
}
}
return holder
}
override fun onBindViewHolder(holder: PetViewHolder, position: Int) {
holder.bind(pets[position])
}
fun setPets(pets: ArrayList<Pet>) {
this.pets = pets
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return pets.size
}
class PetViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
@BindView(R.id.item_pet_name)
lateinit var petName: TextView
@BindView(R.id.item_pet_picture)
lateinit var imageView: ImageView
@BindView(R.id.item_pet_breed)
lateinit var breed: TextView
@BindView(R.id.item_pet_card_view)
lateinit var cardView: androidx.cardview.widget.CardView
var pet: Pet? = null
init {
ButterKnife.bind(this, itemView)
}
fun bind(pet: Pet) {
this.pet = pet
petName.text = String.format("%s, %s, %s", pet.name, pet.age, pet.sex)
breed.text = pet.breed
val url = pet.media!!.thumbnail
if (url != null) {
GlideApp.with(itemView).load(url).fitCenter().centerCrop().into(imageView)
} else {
imageView.setImageResource(R.drawable.ic_broken_image_black_24dp)
}
}
}
}
| mpl-2.0 | 982fa2a33da4176d9ceda08457f13cf9 | 29.02 | 113 | 0.651899 | 4.018742 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/event/EventActivity.kt | 1 | 4791 | package app.opass.ccip.ui.event
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import app.opass.ccip.R
import app.opass.ccip.extension.asyncExecute
import app.opass.ccip.extension.setOnApplyWindowInsetsListenerCompat
import app.opass.ccip.model.Event
import app.opass.ccip.network.PortalClient
import app.opass.ccip.ui.MainActivity
import app.opass.ccip.util.PreferenceUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class EventActivity : AppCompatActivity(), CoroutineScope {
private lateinit var mActivity: Activity
private lateinit var noNetworkView: RelativeLayout
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private lateinit var mJob: Job
override val coroutineContext: CoroutineContext
get() = mJob + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_event)
mActivity = this
swipeRefreshLayout = findViewById(R.id.swipeContainer)
recyclerView = findViewById(R.id.events)
mJob = Job()
setSupportActionBar(findViewById(R.id.toolbar))
setTitle(R.string.select_event)
swipeRefreshLayout.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
recyclerView.setOnApplyWindowInsetsListenerCompat { v, insets, insetsCompat ->
v.updatePadding(bottom = insetsCompat.systemGestureInsets.bottom)
insets
}
noNetworkView = findViewById(R.id.no_network)
noNetworkView.setOnClickListener {
swipeRefreshLayout.isRefreshing = true
swipeRefreshLayout.isEnabled = true
getEvents()
}
noNetworkView.setOnApplyWindowInsetsListenerCompat { v, insets, insetsCompat ->
v.updatePadding(bottom = insetsCompat.systemGestureInsets.bottom)
insets
}
getEvents()
}
override fun onDestroy() {
super.onDestroy()
mJob.cancel()
}
private fun getEvents() {
viewManager = LinearLayoutManager(mActivity)
swipeRefreshLayout.isRefreshing = true
swipeRefreshLayout.isEnabled = true
noNetworkView.visibility = View.GONE
recyclerView.visibility = View.GONE
launch {
try {
val response = PortalClient.get().getEvents().asyncExecute()
if (response.isSuccessful) {
swipeRefreshLayout.isRefreshing = false
swipeRefreshLayout.isEnabled = false
noNetworkView.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
if (response.body()?.size == 1 && PreferenceUtil.getCurrentEvent(mActivity).eventId == "") {
val event = (response.body() as List<Event>)[0]
val eventConfig = PortalClient.get().getEventConfig(event.eventId).asyncExecute()
if (eventConfig.isSuccessful) {
val eventConfig = eventConfig.body()!!
PreferenceUtil.setCurrentEvent(mActivity, eventConfig)
val intent = Intent()
intent.setClass(mActivity, MainActivity::class.java)
mActivity.startActivity(intent)
mActivity.finish()
}
}
viewAdapter = EventAdapter(mActivity, response.body())
recyclerView.apply {
setHasFixedSize(true)
layoutManager = viewManager
adapter = viewAdapter
}
}
} catch (t: Throwable) {
swipeRefreshLayout.isRefreshing = false
swipeRefreshLayout.isEnabled = false
recyclerView.visibility = View.GONE
noNetworkView.visibility = View.VISIBLE
}
}
}
}
| gpl-3.0 | 2d2895133516a4399f5d39a6e9eb00e3 | 38.270492 | 132 | 0.649343 | 5.649764 | false | false | false | false |
owntracks/android | project/app/src/main/java/org/owntracks/android/model/messages/MessageWaypoints.kt | 1 | 891 | package org.owntracks.android.model.messages
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonTypeInfo
import org.owntracks.android.support.MessageWaypointCollection
import org.owntracks.android.support.Preferences
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "_type")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class MessageWaypoints : MessageBase() {
var waypoints: MessageWaypointCollection? = null
override fun addMqttPreferences(preferences: Preferences) {
topic = preferences.pubTopicWaypoints
qos = preferences.pubQosWaypoints
retained = preferences.pubRetainWaypoints
}
companion object {
const val TYPE = "waypoints"
}
}
| epl-1.0 | 0ec6bf5ccbb32b67e94f63b72b59ba73 | 37.73913 | 106 | 0.787879 | 4.714286 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/Reputations.kt | 1 | 412 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import org.jetbrains.exposed.dao.id.LongIdTable
object Reputations : LongIdTable() {
val givenById = long("given_by").index()
val givenByIp = text("given_by_ip").index()
val givenByEmail = text("given_by_email").index()
val receivedById = long("received_by").index()
val receivedAt = long("received_at")
val content = text("content").nullable()
} | agpl-3.0 | ed8743f6ba8c33799cb8934cb8898ac7 | 33.416667 | 57 | 0.737864 | 3.377049 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/activity/SearchActivity.kt | 1 | 6002 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import fr.cph.chicago.R
import fr.cph.chicago.core.adapter.SearchAdapter
import fr.cph.chicago.databinding.ActivitySearchBinding
import fr.cph.chicago.exception.BaseException
import fr.cph.chicago.service.BikeService
import fr.cph.chicago.service.BusService
import fr.cph.chicago.service.TrainService
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import org.apache.commons.lang3.StringUtils
import timber.log.Timber
class SearchActivity : AppCompatActivity() {
companion object {
private val trainService = TrainService
private val busService = BusService
private val bikeService = BikeService
}
private lateinit var searchView: SearchView
private lateinit var searchAdapter: SearchAdapter
private lateinit var searchItem: MenuItem
private lateinit var binding: ActivitySearchBinding
private var query: String = StringUtils.EMPTY
private var clearFocus: Boolean = false
private val supportActionBarNotNull: ActionBar
get() = supportActionBar ?: throw BaseException()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = ActivitySearchBinding.inflate(layoutInflater)
setContentView(binding.root)
setupToolbar()
searchAdapter = SearchAdapter(this)
handleIntent(intent)
binding.searchListView.adapter = searchAdapter
// Associate searchable configuration with the SearchView
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView = SearchView(supportActionBarNotNull.themedContext)
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.isSubmitButtonEnabled = true
searchView.setIconifiedByDefault(false)
searchView.isIconified = false
searchView.maxWidth = 1000
searchView.isFocusable = true
searchView.isFocusableInTouchMode = true
searchView.requestFocus()
searchView.requestFocusFromTouch()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
searchItem = menu.add(android.R.string.search_go)
searchItem.setIcon(R.drawable.ic_search_white_24dp)
searchItem.actionView = searchView
searchItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM or MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW)
searchItem.expandActionView()
// Trigger search
searchView.setQuery(query, true)
if (clearFocus) {
searchView.clearFocus()
}
return super.onCreateOptionsMenu(menu)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish()
}
return super.onKeyDown(keyCode, event)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(SearchManager.QUERY, query)
super.onSaveInstanceState(outState)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
query = savedInstanceState.getString(SearchManager.QUERY, StringUtils.EMPTY)
clearFocus = true
}
private fun setupToolbar() {
setSupportActionBar(binding.included.toolbar)
val actionBar = supportActionBarNotNull
actionBar.setDisplayShowHomeEnabled(true)
actionBar.setDisplayHomeAsUpEnabled(true)
}
@SuppressLint("CheckResult")
private fun handleIntent(intent: Intent) {
if (Intent.ACTION_SEARCH == intent.action) {
query = ((intent.getStringExtra(SearchManager.QUERY)) ?: StringUtils.EMPTY).trim { it <= ' ' }
val foundStations = trainService.searchStations(query)
val foundBusRoutes = busService.searchBusRoutes(query)
val foundBikeStations = bikeService.searchBikeStations(query)
Single.zip(foundStations, foundBusRoutes, foundBikeStations, { trains, buses, bikes -> Triple(trains, buses, bikes) })
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result ->
searchAdapter.updateData(result.first, result.second, result.third)
searchAdapter.notifyDataSetChanged()
},
{ error -> Timber.e(error) }
)
}
}
}
| apache-2.0 | 4fd283f2f6ae3076e7f41a2f014e89bd | 36.049383 | 130 | 0.695102 | 5.064979 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/travisci/TravisCIAuthInterceptor.kt | 1 | 4280 | package com.baulsupp.okurl.services.travisci
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.oksocial.output.UsageException
import com.baulsupp.oksocial.output.process.exec
import com.baulsupp.oksocial.output.stdErrLogging
import com.baulsupp.okurl.authenticator.AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.services.AbstractServiceDefinition
import com.baulsupp.okurl.services.travisci.model.RepositoryList
import com.baulsupp.okurl.services.travisci.model.User
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
class TravisCIAuthInterceptor : AuthInterceptor<TravisToken>() {
override val serviceDefinition = object :
AbstractServiceDefinition<TravisToken>(
"api.travis-ci.org", "Travis CI API", "travisci",
"https://docs.travis-ci.com/api/", null
) {
override fun parseCredentialsString(s: String): TravisToken {
return TravisToken(s)
}
override fun formatCredentialsString(credentials: TravisToken): String {
return credentials.token!!
}
}
override suspend fun intercept(chain: Interceptor.Chain, credentials: TravisToken): Response {
var request = chain.request()
request = request.newBuilder()
.addHeader("Travis-API-Version", "3")
.addHeader("Authorization", "token " + credentials.token)
.build()
var response = chain.proceed(request)
// TODO incorrect response type for errors
if (!response.isSuccessful && response.header("Content-Type") == "application/json") {
val newBody = response.body!!.bytes().toResponseBody(null)
response = response.newBuilder().body(newBody).removeHeader("Content-Type").build()
}
return response
}
override fun defaultCredentials(): TravisToken? = TravisToken.external()
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): TravisToken {
if (!isTravisInstalled()) {
throw UsageException("Requires travis command line installed")
}
// TODO support pro as well
val token = travisToken(false)
return TravisToken(token)
}
private suspend fun isTravisInstalled(): Boolean = exec("which", "travis").success
private suspend fun travisToken(pro: Boolean): String {
val result = exec(listOf("travis", "token", "-E", "--no-interactive", if (pro) "--pro" else "--org")) {
readOutput(true)
redirectError(stdErrLogging)
}
if (!result.success) {
throw UsageException("Use 'travis login --org' or 'travis login --pro'")
}
return result.outputString.trim()
}
override suspend fun validate(
client: OkHttpClient,
credentials: TravisToken
): ValidatedCredentials {
val user = client.query<User>(
"https://api.travis-ci.org/user",
TokenValue(credentials)
)
return ValidatedCredentials(user.name)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource(name())
val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache)
completer.withVariable("user.id") {
listOf(client.query<User>("https://api.travis-ci.org/user", tokenSet).id)
}
completer.withVariable("repository.id") {
client.query<RepositoryList>(
"https://api.travis-ci.org/repos",
tokenSet
).repositories.map { it.slug.replace("/", "%2F") }
}
return completer
}
override fun hosts(credentialsStore: CredentialsStore): Set<String> = setOf("api.travis-ci.com", "api.travis-ci.org")
}
| apache-2.0 | 9459e259f19f0bab66435d6b7653c67c | 32.4375 | 119 | 0.732009 | 4.314516 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/completion/DirCompletionVariableCache.kt | 1 | 1152 | package com.baulsupp.okurl.completion
import java.io.File
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger
class DirCompletionVariableCache(val dir: File = File(System.getProperty("java.io.tmpdir"))) : CompletionVariableCache {
override fun get(service: String, key: String): List<String>? {
val f = File(dir, "$service-$key.txt")
// cache for 1 minutes
if (f.isFile && f.lastModified() > System.currentTimeMillis() - 60000) {
try {
return f.readLines().filterNot { it.isBlank() }
} catch (e: IOException) {
logger.log(Level.WARNING, "failed to read variables", e)
}
}
return null
}
override fun set(service: String, key: String, values: List<String>) {
val f = File(dir, "$service-$key.txt")
try {
f.writeText(values.joinToString(separator = "\n", postfix = "\n"))
} catch (e: IOException) {
logger.log(Level.WARNING, "failed to store variables", e)
}
}
companion object {
private val logger = Logger.getLogger(DirCompletionVariableCache::class.java.name)
val TEMP = DirCompletionVariableCache()
}
}
| apache-2.0 | 5db02625cf66965968e125c1f155f096 | 28.538462 | 120 | 0.667535 | 3.81457 | false | false | false | false |
robinverduijn/gradle | .teamcity/Gradle_Check/configurations/PerformanceTestCoordinator.kt | 1 | 2260 | package configurations
import common.Os
import common.applyPerformanceTestSettings
import common.buildToolGradleParameters
import common.checkCleanM2
import common.distributedPerformanceTestParameters
import common.gradleWrapper
import common.performanceTestCommandLine
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildStep
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildStep.ExecutionMode
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildSteps
import model.CIBuildModel
import model.PerformanceTestType
import model.Stage
class PerformanceTestCoordinator(model: CIBuildModel, type: PerformanceTestType, stage: Stage) : BaseGradleBuildType(model, stage = stage, init = {
uuid = type.asId(model)
id = AbsoluteId(uuid)
name = "Performance ${type.name.capitalize()} Coordinator - Linux"
applyPerformanceTestSettings(timeout = type.timeout)
if (type in listOf(PerformanceTestType.test, PerformanceTestType.experiment)) {
features {
publishBuildStatusToGithub(model)
}
}
params {
param("performance.baselines", type.defaultBaselines)
}
fun BuildSteps.runner(runnerName: String, runnerTasks: String, extraParameters: String = "", runnerExecutionMode: BuildStep.ExecutionMode = ExecutionMode.DEFAULT) {
gradleWrapper {
name = runnerName
tasks = ""
executionMode = runnerExecutionMode
gradleParams = (performanceTestCommandLine(task = runnerTasks, baselines = "%performance.baselines%", extraParameters = type.extraParameters) +
buildToolGradleParameters(isContinue = false) +
distributedPerformanceTestParameters(IndividualPerformanceScenarioWorkers(model).id.toString()) +
listOf(buildScanTag("PerformanceTest")) +
model.parentBuildCache.gradleParameters(Os.linux) +
extraParameters
).joinToString(separator = " ")
}
}
steps {
runner("GRADLE_RUNNER", "clean distributed${type.taskId}s")
checkCleanM2()
tagBuild(model, true)
}
applyDefaultDependencies(model, this, true)
})
| apache-2.0 | f972a8dd8232e9f80fdb6d083816bdc5 | 38.649123 | 168 | 0.716814 | 4.945295 | false | true | false | false |
fantasy1022/FancyTrendView | app/src/main/java/com/fantasy1022/fancytrendapp/common/UiUtils.kt | 1 | 1400 | /*
* Copyright 2017 Fantasy Fang
*
* 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.fantasy1022.fancytrendapp.common
import android.support.transition.ChangeBounds
import android.support.transition.Fade
import android.support.transition.TransitionManager
import android.support.transition.TransitionSet
import android.view.ViewGroup
/**
* Created by fantasy1022 on 2017/2/22.
*/
object UiUtils {
fun animateForViewGroupTransition(viewGroup: ViewGroup) {
val changeBounds = ChangeBounds()
val fadeOut = Fade(Fade.OUT)
val fadeIn = Fade(Fade.IN)
val transition = TransitionSet()
transition.ordering = TransitionSet.ORDERING_TOGETHER
transition.addTransition(fadeOut)
.addTransition(changeBounds)
.addTransition(fadeIn)
TransitionManager.beginDelayedTransition(viewGroup)
}
}
| apache-2.0 | 93c272b53e3430176ee152309592bf3e | 29.434783 | 75 | 0.732857 | 4.487179 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/hits/Shade.kt | 1 | 599 | package net.dinkla.raytracer.hits
import net.dinkla.raytracer.materials.IMaterial
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.math.Ray
class Shade : Hit() {
// for specular highlights, set by Tracer
var ray: Ray
// Recursion depth, set by tracer
var depth: Int = 0
val hitPoint: Point3D
get() = ray.linear(t)
val localHitPoint: Point3D
get() = ray.linear(t)
val material: IMaterial?
get() = `object`!!.material
init {
this.depth = 0
this.ray = Ray.DEFAULT
this.`object` = null
}
}
| apache-2.0 | 41bd4940a98f650758b5f96a4c3680fa | 18.966667 | 47 | 0.629382 | 3.697531 | false | false | false | false |
elpassion/android-commons | shared-preferences-moshi-converter-adapter/src/androidTest/java/com/elpassion/sharedpreferences/moshiadapter/SharedPreferencesTestCase.kt | 1 | 2952 | package com.elpassion.sharedpreferences.moshiadapter
import android.preference.PreferenceManager
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import com.elpassion.android.commons.sharedpreferences.createSharedPrefs
import com.squareup.moshi.Types
import org.junit.After
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SharedPreferencesTestCase {
@Test
fun shouldSaveStringToRepository() {
// tag::sharedpreferences-create-moshi-converter-adapter[]
val jsonAdapter = moshiConverterAdapter<String>()
// end::sharedpreferences-create-moshi-converter-adapter[]
val repository = createSharedPrefs(sharedPreferences, jsonAdapter)
val valueSaved = "someValue"
repository.write("key", valueSaved)
val valueRead = repository.read("key")
Assert.assertEquals(valueSaved, valueRead)
}
data class SimpleStructure(val value: Int)
@Test
fun shouldSaveObjectToRepository() {
val repository = createSharedPrefs<SimpleStructure>(sharedPreferences, moshiConverterAdapter())
val valueSaved = SimpleStructure(1)
repository.write("key", valueSaved)
val valueRead = repository.read("key")
Assert.assertEquals(valueSaved, valueRead)
}
@Test
fun shouldSaveListOfObjectsToRepository() {
val valueSaved = listOf(SimpleStructure(1))
val repository = createSharedPrefs<List<SimpleStructure>>(sharedPreferences, moshiConverterAdapter(type = Types.newParameterizedType(List::class.java, SimpleStructure::class.java)))
repository.write("key", valueSaved)
val valueRead = repository.read("key")
Assert.assertEquals(valueSaved, valueRead)
}
@Test
fun shouldBePossibleToSaveNull() {
val repository = createSharedPrefs<SimpleStructure>(sharedPreferences, moshiConverterAdapter())
repository.write("key", null)
Assert.assertEquals(null, repository.read("key"))
}
@Test
fun containsShouldReturnFalseWhenSharedPreferencesIsEmpty() {
val repository = createSharedPrefs<SimpleStructure>(sharedPreferences, moshiConverterAdapter())
Assert.assertFalse(repository.contains("key"))
}
@Test
fun containsShouldReturnTrueWhenSharedPreferencesContainsGivenKey() {
val repository = createSharedPrefs<SimpleStructure>(sharedPreferences, moshiConverterAdapter())
repository.write("key", SimpleStructure(1))
Assert.assertTrue(repository.contains("key"))
}
@After
fun clearSharedPrefs() {
sharedPreferences()
.edit()
.clear()
.apply()
}
private val sharedPreferences = { PreferenceManager.getDefaultSharedPreferences(getContext()) }
private fun getContext() = InstrumentationRegistry.getInstrumentation().targetContext
} | apache-2.0 | 132fc06e20d4d752af92d77e4ff0ac63 | 34.154762 | 189 | 0.722222 | 5.054795 | false | true | false | false |
AerisG222/maw_photos_android | MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/categorylist/CategoryListRecyclerAdapter.kt | 1 | 2662 | package us.mikeandwan.photos.ui.controls.categorylist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import us.mikeandwan.photos.databinding.ViewHolderCategoryListItemBinding
import us.mikeandwan.photos.domain.models.PhotoCategory
class CategoryListRecyclerAdapter(private val clickListener: ClickListener)
: ListAdapter<CategoryWithYearVisibility, CategoryListRecyclerAdapter.ViewHolder>(DiffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ViewHolderCategoryListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val categoryWithYearVisibility = getItem(position)
holder.bind(categoryWithYearVisibility, clickListener)
}
companion object DiffCallback : DiffUtil.ItemCallback<CategoryWithYearVisibility>() {
override fun areItemsTheSame(oldItem: CategoryWithYearVisibility, newItem: CategoryWithYearVisibility): Boolean {
// odd, per docs, would have expected below check here, and then the areContentsTheSame to identify same records
// however, when debugging the other method was not called which resulted in the recycler to reset the scroll position
// to the top after loading more search results (new items added to list). interestingly, this does not happen with the
// imagegrid recycler (it does call the areContentsTheSame and does not cause a scroll update)
// return oldItem === newItem
return oldItem.category.id == newItem.category.id
}
override fun areContentsTheSame(oldItem: CategoryWithYearVisibility, newItem: CategoryWithYearVisibility): Boolean {
return oldItem.category.id == newItem.category.id
}
}
class ViewHolder(private var binding: ViewHolderCategoryListItemBinding)
: RecyclerView.ViewHolder(binding.root) {
fun bind(categoryWithYearVisibility: CategoryWithYearVisibility, clickListener: ClickListener) {
binding.viewModel = categoryWithYearVisibility
binding.root.setOnClickListener { clickListener.onClick(categoryWithYearVisibility.category) }
binding.executePendingBindings()
}
}
class ClickListener(val clickListener: (category: PhotoCategory) -> Unit) {
fun onClick(category: PhotoCategory) = clickListener(category)
}
}
| mit | 533580002b1269567cfc8f84f638e1d6 | 49.226415 | 132 | 0.753569 | 5.569038 | false | false | false | false |
opeykin/vkspy | backend/src/main/kotlin/org/vkspy/HttpWrapper.kt | 1 | 3621 | package org.vkspy
import org.apache.commons.io.IOUtils
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
import java.io.IOException
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
/**
* Eases using [HttpClient] for performing requests to vk.com
* @author Alexey Grigorev
*/
class HttpClientWrapper(private val httpClient: HttpClient) {
public constructor() : this(wrapClient(DefaultHttpClient())) {
}
/**
* Executes GET request and returns response in string
* @param uri for the request
* *
* @return string response
* *
*/
public fun executeGet(uri: String): String {
return executeRequest(HttpGet(uri))
}
private fun executeRequest(request: HttpUriRequest): String {
try {
val response = httpClient.execute(request)
val entity = response.entity
return IOUtils.toString(entity.content, "UTF-8")
} catch (e: IOException) {
throw RuntimeException(e)
}
}
companion object {
/**
* Wraps [HttpClient] so it can be used for https requests without
* special certificates and it can work in concurrent environment
* @param base object to be wrapped
* *
* @return wrapped [HttpClient]
*/
private fun wrapClient(base: HttpClient): HttpClient {
// http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html
// wrapping the client to successfully perform https queries without any
// certificates
try {
val ctx = SSLContext.getInstance("TLS")
ctx.init(null, arrayOf<TrustManager>(dontCareTrustManager), null)
val ssf = SSLSocketFactory(ctx)
val baseCcm = base.connectionManager
val sr = baseCcm.schemeRegistry
sr.register(Scheme("https", 443, ssf))
// http://stackoverflow.com/questions/4612573/exception-using-httprequest-execute-invalid-use-of-singleclientconnmanager-c
// http://foo.jasonhudgins.com/2010/03/http-connections-revisited.html
// avoiding
// "invalid use of SingleClientConnManager: connection still allocated."
// exception
val safeCcm = ThreadSafeClientConnManager(sr)
return DefaultHttpClient(safeCcm, base.params)
} catch (ex: Exception) {
throw RuntimeException(ex)
}
}
/**
* Accepts all given certificates
*/
private val dontCareTrustManager = object : X509TrustManager {
private var empty = emptyArray<X509Certificate>()
override fun getAcceptedIssuers(): Array<X509Certificate> {
return empty
}
@Throws(CertificateException::class)
override fun checkServerTrusted(ar: Array<X509Certificate>, st: String) {
}
@Throws(CertificateException::class)
override fun checkClientTrusted(ar: Array<X509Certificate>, st: String) {
}
}
}
}
| gpl-2.0 | 9296be49874b7cfaa25e6150902ac5e6 | 32.220183 | 138 | 0.637393 | 4.666237 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdBlockQuoteImpl.kt | 1 | 2813 | // 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.psi.element
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.vladsch.flexmark.util.sequence.LineAppendable
import com.vladsch.md.nav.actions.handlers.util.PsiEditContext
import com.vladsch.md.nav.psi.util.MdPsiBundle
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.md.nav.util.format.CharLinePrefixMatcher
import com.vladsch.md.nav.util.format.LinePrefixMatcher
import icons.MdIcons
import javax.swing.Icon
class MdBlockQuoteImpl(node: ASTNode) : MdIndentingCompositeImpl(node), MdBlockQuote, MdStructureViewPresentableElement, MdStructureViewPresentableItem, MdBreadcrumbElement {
companion object {
@JvmField
val INDENT_PREFIX = "> "
private val INDENT_PREFIX_MATCHER = CharLinePrefixMatcher('>')
}
override fun isTextStart(node: ASTNode): Boolean {
return node !== node.firstChildNode
}
override fun getPrefixMatcher(editContext: PsiEditContext): LinePrefixMatcher {
return INDENT_PREFIX_MATCHER
}
override fun removeLinePrefix(lines: LineAppendable, indentColumns: IntArray, isFirstChild: Boolean, editContext: PsiEditContext) {
removeLinePrefix(lines, indentColumns, false, editContext, INDENT_PREFIX_MATCHER, 0)
}
override fun getIcon(flags: Int): Icon? {
return MdIcons.Element.BLOCK_QUOTE
}
override fun getPresentableText(): String? {
return MdPsiBundle.message("block-quote")
}
override fun getLocationString(): String? {
return null
}
override fun getStructureViewPresentation(): ItemPresentation {
return MdPsiImplUtil.getPresentation(this)
}
fun getBlockQuoteNesting(): Int {
var nesting = 1
var parent = parent
while (parent is MdBlockQuote) {
nesting++
parent = parent.parent
}
return nesting
}
override fun getBreadcrumbInfo(): String {
// val message = PsiBundle.message("block-quote")
// val nesting = getBlockQuoteNesting()
// return if (nesting > 1) "$message ×$nesting" else message
val settings = MdApplicationSettings.instance.documentSettings
if (settings.showBreadcrumbText) {
return ">"
}
return MdPsiBundle.message("block-quote")
}
override fun getBreadcrumbTooltip(): String? {
return null
}
override fun getBreadcrumbTextElement(): PsiElement? {
return null
}
}
| apache-2.0 | 84e4b360cfbab394ccf61e629ae4aedc | 32.879518 | 177 | 0.703058 | 4.640264 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/extensions/Context.kt | 1 | 3241 | package com.booboot.vndbandroid.extensions
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.res.ColorStateList
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.model.vndbandroid.Preferences
inline fun <reified A : Activity> Context.startActivity(configIntent: Intent.() -> Unit = {}) {
startActivity(Intent(this, A::class.java).apply(configIntent))
}
fun Context.getBitmap(@DrawableRes drawableRes: Int): Bitmap? {
return VectorDrawableCompat.create(resources, drawableRes, theme)?.let {
val bitmap = Bitmap.createBitmap(it.intrinsicWidth, it.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
it.setBounds(0, 0, canvas.width, canvas.height)
it.draw(canvas)
bitmap
}
}
fun Context.openURL(url: String) {
if (Preferences.useCustomTabs) {
val builder = CustomTabsIntent.Builder()
builder.setToolbarColor(getThemeColor(R.attr.colorPrimary))
getBitmap(R.drawable.ic_arrow_back_24dp)?.let {
builder.setCloseButtonIcon(it)
}
builder.setStartAnimations(this, R.anim.slide_in, R.anim.slide_out)
builder.setExitAnimations(this, R.anim.slide_back_in, R.anim.slide_back_out)
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(this, Uri.parse(url))
} else {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
}
}
fun Context.getThemeColor(resid: Int): Int {
val colorAttribute = TypedValue()
theme.resolveAttribute(resid, colorAttribute, true)
return colorAttribute.data
}
fun Context.getThemeColorState(@AttrRes resid: Int): ColorStateList? {
val data = getThemeColor(resid)
val arr = obtainStyledAttributes(data, intArrayOf(resid))
val color = arr.getColorStateList(0)
arr.recycle()
return color
}
@ColorInt
fun Context.getThemeColorStateEnabled(@AttrRes resid: Int): Int {
return getThemeColorState(resid)?.getColorForState(IntArray(android.R.attr.state_selected), -1) ?: -1
}
fun Context.dayNightTheme(): String {
val themeName = TypedValue()
theme.resolveAttribute(R.attr.themeName, themeName, true)
return themeName.string.toString()
}
fun Context.statusBarHeight() = resources.statusBarHeight()
fun Resources.statusBarHeight(): Int {
val resourceId = getIdentifier("status_bar_height", "dimen", "android")
return if (resourceId > 0) {
getDimensionPixelSize(resourceId)
} else 0
}
fun Context?.scanForActivity(): AppCompatActivity? = when {
this == null -> null
this is AppCompatActivity -> this
this is ContextWrapper -> this.baseContext?.scanForActivity()
else -> null
} | gpl-3.0 | 851d9f1ae03637efe705e7de610f1fca | 34.23913 | 105 | 0.742363 | 4.242147 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationsAdapter.kt | 3 | 5380 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.conversations
import android.content.Context
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.moez.QKSMS.R
import com.moez.QKSMS.common.Navigator
import com.moez.QKSMS.common.base.QkRealmAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.DateFormatter
import com.moez.QKSMS.common.util.extensions.resolveThemeColor
import com.moez.QKSMS.common.util.extensions.setTint
import com.moez.QKSMS.model.Conversation
import com.moez.QKSMS.util.PhoneNumberUtils
import kotlinx.android.synthetic.main.conversation_list_item.*
import kotlinx.android.synthetic.main.conversation_list_item.view.*
import javax.inject.Inject
class ConversationsAdapter @Inject constructor(
private val colors: Colors,
private val context: Context,
private val dateFormatter: DateFormatter,
private val navigator: Navigator,
private val phoneNumberUtils: PhoneNumberUtils
) : QkRealmAdapter<Conversation>() {
init {
// This is how we access the threadId for the swipe actions
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.conversation_list_item, parent, false)
if (viewType == 1) {
val textColorPrimary = parent.context.resolveThemeColor(android.R.attr.textColorPrimary)
view.title.setTypeface(view.title.typeface, Typeface.BOLD)
view.snippet.setTypeface(view.snippet.typeface, Typeface.BOLD)
view.snippet.setTextColor(textColorPrimary)
view.snippet.maxLines = 5
view.unread.isVisible = true
view.date.setTypeface(view.date.typeface, Typeface.BOLD)
view.date.setTextColor(textColorPrimary)
}
return QkViewHolder(view).apply {
view.setOnClickListener {
val conversation = getItem(adapterPosition) ?: return@setOnClickListener
when (toggleSelection(conversation.id, false)) {
true -> view.isActivated = isSelected(conversation.id)
false -> navigator.showConversation(conversation.id)
}
}
view.setOnLongClickListener {
val conversation = getItem(adapterPosition) ?: return@setOnLongClickListener true
toggleSelection(conversation.id)
view.isActivated = isSelected(conversation.id)
true
}
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val conversation = getItem(position) ?: return
// If the last message wasn't incoming, then the colour doesn't really matter anyway
val lastMessage = conversation.lastMessage
val recipient = when {
conversation.recipients.size == 1 || lastMessage == null -> conversation.recipients.firstOrNull()
else -> conversation.recipients.find { recipient ->
phoneNumberUtils.compare(recipient.address, lastMessage.address)
}
}
val theme = colors.theme(recipient).theme
holder.containerView.isActivated = isSelected(conversation.id)
holder.avatars.recipients = conversation.recipients
holder.title.collapseEnabled = conversation.recipients.size > 1
holder.title.text = buildSpannedString {
append(conversation.getTitle())
if (conversation.draft.isNotEmpty()) {
color(theme) { append(" " + context.getString(R.string.main_draft)) }
}
}
holder.date.text = conversation.date.takeIf { it > 0 }?.let(dateFormatter::getConversationTimestamp)
holder.snippet.text = when {
conversation.draft.isNotEmpty() -> conversation.draft
conversation.me -> context.getString(R.string.main_sender_you, conversation.snippet)
else -> conversation.snippet
}
holder.pinned.isVisible = conversation.pinned
holder.unread.setTint(theme)
}
override fun getItemId(position: Int): Long {
return getItem(position)?.id ?: -1
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position)?.unread == false) 0 else 1
}
}
| gpl-3.0 | 2fde9b4643496ac2d86e7d43f1299bec | 39.451128 | 109 | 0.692007 | 4.702797 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/views/TaskDetailView.kt | 1 | 1597 | package com.airbnb.mvrx.todomvrx.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.RelativeLayout
import android.widget.TextView
import com.airbnb.epoxy.CallbackProp
import com.airbnb.epoxy.ModelProp
import com.airbnb.epoxy.ModelView
import com.airbnb.mvrx.todomvrx.data.Task
import com.airbnb.mvrx.todomvrx.todoapp.R
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_MATCH_HEIGHT)
class TaskDetailView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val titleView by lazy { findViewById<TextView>(R.id.task_title) }
private val descriptionView by lazy { findViewById<TextView>(R.id.task_description) }
private val checkbox by lazy { findViewById<CheckBox>(R.id.complete) }
private val noDataView by lazy { findViewById<View>(R.id.no_data_view) }
init {
inflate(context, R.layout.task_detail, this)
}
@ModelProp
fun setTask(task: Task?) {
titleView.text = task?.title
descriptionView.text = task?.description
checkbox.isChecked = task?.complete ?: false
checkbox.visibility = if (task == null) View.GONE else View.VISIBLE
noDataView.visibility = if (task == null) View.VISIBLE else View.GONE
}
@CallbackProp
fun onCheckedChanged(listener: CompoundButton.OnCheckedChangeListener?) {
checkbox.setOnCheckedChangeListener(listener)
}
}
| apache-2.0 | a5ed6490347b349e7f2f9ab3ca4bab22 | 34.488889 | 89 | 0.743895 | 4.180628 | false | false | false | false |
rock3r/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnusedPrivateMember.kt | 1 | 10733 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.LazyRegex
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isAbstract
import io.gitlab.arturbosch.detekt.rules.isExternal
import io.gitlab.arturbosch.detekt.rules.isMainFunction
import io.gitlab.arturbosch.detekt.rules.isOpen
import io.gitlab.arturbosch.detekt.rules.isOperator
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtOperationReferenceExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.types.expressions.OperatorConventions
/**
* Reports unused private properties, function parameters and functions.
* If these private elements are unused they should be removed. Otherwise this dead code
* can lead to confusion and potential bugs.
*
* @configuration allowedNames - unused private member names matching this regex are ignored
* (default: `'(_|ignored|expected|serialVersionUID)'`)
*/
class UnusedPrivateMember(config: Config = Config.empty) : Rule(config) {
companion object {
const val ALLOWED_NAMES_PATTERN = "allowedNames"
}
override val defaultRuleIdAliases: Set<String> = setOf("UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused")
override val issue: Issue = Issue("UnusedPrivateMember",
Severity.Maintainability,
"Private member is unused.",
Debt.FIVE_MINS)
private val allowedNames by LazyRegex(ALLOWED_NAMES_PATTERN, "(_|ignored|expected|serialVersionUID)")
override fun visit(root: KtFile) {
super.visit(root)
root.acceptUnusedMemberVisitor(UnusedFunctionVisitor(allowedNames, bindingContext))
root.acceptUnusedMemberVisitor(UnusedParameterVisitor(allowedNames))
root.acceptUnusedMemberVisitor(UnusedPropertyVisitor(allowedNames))
}
private fun KtFile.acceptUnusedMemberVisitor(visitor: UnusedMemberVisitor) {
accept(visitor)
visitor.getUnusedReports(issue).forEach { report(it) }
}
}
private abstract class UnusedMemberVisitor(protected val allowedNames: Regex) : DetektVisitor() {
abstract fun getUnusedReports(issue: Issue): List<CodeSmell>
}
private class UnusedFunctionVisitor(
allowedNames: Regex,
private val bindingContext: BindingContext
) : UnusedMemberVisitor(allowedNames) {
private val functionDeclarations = mutableMapOf<String, MutableList<KtFunction>>()
private val functionReferences = mutableMapOf<String, MutableList<KtReferenceExpression>>()
override fun getUnusedReports(issue: Issue): List<CodeSmell> {
return functionDeclarations.flatMap { (name, functions) ->
val isOperator = functions.any { it.isOperator() }
val references = functionReferences[name].orEmpty()
val unusedFunctions = when {
(functions.size > 1 || isOperator) && bindingContext != BindingContext.EMPTY -> {
val referencesViaOperator = if (isOperator) {
val operatorToken = OperatorConventions.getOperationSymbolForName(Name.identifier(name))
val operatorValue = (operatorToken as? KtSingleValueToken)?.value
operatorValue?.let { functionReferences[it] }.orEmpty()
} else {
emptyList()
}
val referenceDescriptors = (references + referencesViaOperator).mapNotNull {
it.getResolvedCall(bindingContext)?.resultingDescriptor
}
functions.filter {
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] !in referenceDescriptors
}
}
references.isEmpty() -> functions
else -> emptyList()
}
unusedFunctions.map {
CodeSmell(issue, Entity.from(it), "Private function $name is unused.")
}
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!isDeclaredInsideAnInterface(function) && function.isPrivate()) {
collectFunction(function)
}
super.visitNamedFunction(function)
}
private fun isDeclaredInsideAnInterface(function: KtNamedFunction) =
function.getStrictParentOfType<KtClass>()?.isInterface() == true
private fun collectFunction(function: KtNamedFunction) {
val name = function.nameAsSafeName.identifier
if (!allowedNames.matches(name)) {
functionDeclarations.getOrPut(name) { mutableListOf() }.add(function)
}
}
/*
* We need to collect all private function declarations and references to these functions
* for the whole file as Kotlin allows to access private and internal object declarations
* from everywhere in the file.
*/
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val name = when (expression) {
is KtOperationReferenceExpression -> expression.getReferencedName()
is KtNameReferenceExpression -> expression.getReferencedName()
else -> null
} ?: return
functionReferences.getOrPut(name) { mutableListOf() }.add(expression)
}
}
private class UnusedParameterVisitor(allowedNames: Regex) : UnusedMemberVisitor(allowedNames) {
private var unusedParameters: MutableSet<KtParameter> = mutableSetOf()
override fun getUnusedReports(issue: Issue): List<CodeSmell> {
return unusedParameters.map {
CodeSmell(issue, Entity.from(it), "Function parameter ${it.nameAsSafeName.identifier} is unused.")
}
}
override fun visitClass(klass: KtClass) {
if (klass.isInterface()) return
super.visitClassOrObject(klass)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!function.isRelevant()) {
return
}
collectParameters(function)
super.visitNamedFunction(function)
}
private fun collectParameters(function: KtNamedFunction) {
val parameters = mutableMapOf<String, KtParameter>()
function.valueParameterList?.parameters?.forEach { parameter ->
val name = parameter.nameAsSafeName.identifier
if (!allowedNames.matches(name)) {
parameters[name] = parameter
}
}
function.accept(object : DetektVisitor() {
override fun visitProperty(property: KtProperty) {
if (property.isLocal) {
val name = property.nameAsSafeName.identifier
parameters.remove(name)
}
super.visitProperty(property)
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
parameters.remove(expression.text)
super.visitReferenceExpression(expression)
}
})
unusedParameters.addAll(parameters.values)
}
private fun KtNamedFunction.isRelevant() = !isAllowedToHaveUnusedParameters()
private fun KtNamedFunction.isAllowedToHaveUnusedParameters() =
isAbstract() || isOpen() || isOverride() || isOperator() || isMainFunction() || isExternal()
}
private class UnusedPropertyVisitor(allowedNames: Regex) : UnusedMemberVisitor(allowedNames) {
private val properties = mutableSetOf<KtNamedDeclaration>()
private val nameAccesses = mutableSetOf<String>()
override fun getUnusedReports(issue: Issue): List<CodeSmell> {
return properties
.filter { it.nameAsSafeName.identifier !in nameAccesses }
.map { CodeSmell(issue, Entity.from(it),
"Private property ${it.nameAsSafeName.identifier} is unused.") }
}
override fun visitParameter(parameter: KtParameter) {
super.visitParameter(parameter)
if (parameter.isLoopParameter) {
val destructuringDeclaration = parameter.destructuringDeclaration
if (destructuringDeclaration != null) {
for (variable in destructuringDeclaration.entries) {
maybeAddUnusedProperty(variable)
}
} else {
maybeAddUnusedProperty(parameter)
}
}
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
super.visitPrimaryConstructor(constructor)
constructor.valueParameters
.filter { it.isPrivate() || !it.hasValOrVar() }
.forEach { maybeAddUnusedProperty(it) }
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
super.visitSecondaryConstructor(constructor)
constructor.valueParameters.forEach { maybeAddUnusedProperty(it) }
}
private fun maybeAddUnusedProperty(it: KtNamedDeclaration) {
if (!allowedNames.matches(it.nameAsSafeName.identifier)) {
properties.add(it)
}
}
override fun visitProperty(property: KtProperty) {
if (property.isPrivate() && property.isMemberOrTopLevel() || property.isLocal) {
maybeAddUnusedProperty(property)
}
super.visitProperty(property)
}
private fun KtProperty.isMemberOrTopLevel() = isMember || isTopLevel
override fun visitReferenceExpression(expression: KtReferenceExpression) {
nameAccesses.add(expression.text)
super.visitReferenceExpression(expression)
}
}
| apache-2.0 | 797a66ec49c3d8fed4445fae73a6098b | 39.501887 | 112 | 0.690487 | 5.190039 | false | false | false | false |
tipsy/javalin | javalin/src/test/java/io/javalin/TestCors.kt | 1 | 4978 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin
import io.javalin.core.util.Header.ACCESS_CONTROL_ALLOW_CREDENTIALS
import io.javalin.core.util.Header.ACCESS_CONTROL_ALLOW_HEADERS
import io.javalin.core.util.Header.ACCESS_CONTROL_ALLOW_METHODS
import io.javalin.core.util.Header.ACCESS_CONTROL_ALLOW_ORIGIN
import io.javalin.core.util.Header.ACCESS_CONTROL_REQUEST_HEADERS
import io.javalin.core.util.Header.ACCESS_CONTROL_REQUEST_METHOD
import io.javalin.core.util.Header.ORIGIN
import io.javalin.core.util.Header.REFERER
import io.javalin.testing.TestUtil
import kong.unirest.Unirest
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.jupiter.api.Test
class TestCors {
@Test
fun `enableCorsForOrigin throws for empty varargs`() {
assertThatExceptionOfType(IllegalArgumentException::class.java)
.isThrownBy { Javalin.create { it.enableCorsForOrigin() } }
.withMessageStartingWith("Origins cannot be empty.")
}
@Test
fun `enableCorsForOrigin enables cors for specific origins`() {
val javalin = Javalin.create { it.enableCorsForOrigin("origin-1", "referer-1") }
TestUtil.test(javalin) { app, http ->
app.get("/") { it.result("Hello") }
assertThat(Unirest.get(http.origin).asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]).isEmpty()
assertThat(Unirest.get(http.origin).header(ORIGIN, "origin-1").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]!![0]).isEqualTo("origin-1")
assertThat(Unirest.get(http.origin).header(REFERER, "referer-1").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]!![0]).isEqualTo("referer-1")
}
}
@Test
fun `rejectCorsForInvalidOrigin reject where origin doesn't match`() {
val javalin = Javalin.create { it.enableCorsForOrigin("origin-1.com") }
TestUtil.test(javalin) { app, http ->
app.get("/") { it.result("Hello") }
assertThat(Unirest.get(http.origin).header(ORIGIN, "origin-2.com").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]).isEmpty()
assertThat(Unirest.get(http.origin).header(ORIGIN, "origin-1.com.au").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]).isEmpty()
}
}
@Test
fun `enableCorsForAllOrigins enables cors for all origins`() {
val javalin = Javalin.create { it.enableCorsForAllOrigins() }
TestUtil.test(javalin) { app, http ->
app.get("/") { it.result("Hello") }
assertThat(Unirest.get(http.origin).header("Origin", "some-origin").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]!![0]).isEqualTo("some-origin")
assertThat(Unirest.get(http.origin).header("Origin", "some-origin").asString().headers[ACCESS_CONTROL_ALLOW_CREDENTIALS]!![0]).isEqualTo("true") // cookies allowed
assertThat(Unirest.get(http.origin).header("Referer", "some-referer").asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]!![0]).isEqualTo("some-referer")
assertThat(Unirest.get(http.origin).asString().headers[ACCESS_CONTROL_ALLOW_ORIGIN]).isEmpty()
}
}
@Test
fun `enableCorsForAllOrigins enables cors for all origins with AccessManager`() {
val accessManagedCorsApp = Javalin.create {
it.enableCorsForAllOrigins()
it.accessManager { _, ctx, _ ->
ctx.status(401).result("Unauthorized")
}
}
TestUtil.test(accessManagedCorsApp) { app, http ->
app.get("/", { it.result("Hello") }, TestAccessManager.MyRoles.ROLE_ONE)
assertThat(http.get("/").body).isEqualTo("Unauthorized")
val response = Unirest.options(http.origin)
.header(ACCESS_CONTROL_REQUEST_HEADERS, "123")
.header(ACCESS_CONTROL_REQUEST_METHOD, "TEST")
.asString()
assertThat(response.headers[ACCESS_CONTROL_ALLOW_HEADERS]!![0]).isEqualTo("123")
assertThat(response.headers[ACCESS_CONTROL_ALLOW_METHODS]!![0]).isEqualTo("TEST")
assertThat(response.body).isBlank()
}
}
@Test
fun `enableCorsForAllOrigins allows options endpoint mapping`() {
val javalin = Javalin.create { it.enableCorsForAllOrigins() }
TestUtil.test(javalin) { app, http ->
app.options("/") { it.result("Hello") }
val response = Unirest.options(http.origin)
.header(ACCESS_CONTROL_REQUEST_HEADERS, "123")
.header(ACCESS_CONTROL_REQUEST_METHOD, "TEST")
.asString()
assertThat(response.headers[ACCESS_CONTROL_ALLOW_HEADERS]!![0]).isEqualTo("123")
assertThat(response.headers[ACCESS_CONTROL_ALLOW_METHODS]!![0]).isEqualTo("TEST")
assertThat(response.body).isEqualTo("Hello")
}
}
}
| apache-2.0 | 3211fb23661f2ad642abcca18983b9e7 | 48.277228 | 175 | 0.663854 | 4.059543 | false | true | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/model/NotificationModel.kt | 1 | 595 | package im.fdx.v2ex.model
import android.os.Parcelable
import im.fdx.v2ex.ui.main.Topic
import im.fdx.v2ex.ui.member.Member
import kotlinx.parcelize.Parcelize
/**
* Created by fdx on 2017/3/24.
*/
@Parcelize
class NotificationModel(var time: String? = "",
var replyPosition: String? = "",
var type: String? = "",
var topic: Topic? = Topic(),
var member: Member? = Member(),
var content: String? = "",
var id: String? = "") : Parcelable, VModel()
| apache-2.0 | 966f041de8cc56537bf7b9e23329ba5a | 30.315789 | 68 | 0.527731 | 4.075342 | false | false | false | false |
tipsy/javalin | javalin-openapi/src/main/java/io/javalin/plugin/openapi/annotations/AnnotationApiMapping.kt | 1 | 7294 | package io.javalin.plugin.openapi.annotations
import io.javalin.plugin.openapi.dsl.DocumentedContent
import io.javalin.plugin.openapi.dsl.DocumentedParameter
import io.javalin.plugin.openapi.dsl.DocumentedResponse
import io.javalin.plugin.openapi.dsl.OpenApiDocumentation
import io.javalin.plugin.openapi.dsl.anyOf
import io.javalin.plugin.openapi.dsl.createUpdater
import io.javalin.plugin.openapi.dsl.oneOf
import io.swagger.v3.oas.models.Operation
import io.swagger.v3.oas.models.parameters.RequestBody
import io.swagger.v3.oas.models.security.SecurityRequirement
import kotlin.reflect.KClass
fun OpenApi.asOpenApiDocumentation(): OpenApiDocumentation {
val documentation = OpenApiDocumentation()
val annotation = this
documentation.isIgnored = annotation.ignore
documentation.operation { it.applyAnnotation(annotation) }
annotation.cookies.forEach { documentation.applyParamAnnotation("cookie", it) }
annotation.headers.forEach { documentation.applyParamAnnotation("header", it) }
annotation.pathParams.forEach { documentation.applyParamAnnotation("path", it) }
annotation.queryParams.forEach { documentation.applyParamAnnotation("query", it) }
annotation.formParams.forEach { documentation.formParam(it.name, it.type.java, it.required) }
documentation.applyRequestBodyAnnotation(annotation.requestBody)
documentation.applyComposedRequestBodyAnnotation(annotation.composedRequestBody)
annotation.fileUploads.forEach { fileUpload ->
if (fileUpload.isArray) {
documentation.uploadedFiles(name = fileUpload.name) { it.applyAnnotation(fileUpload) }
} else {
documentation.uploadedFile(name = fileUpload.name) { it.applyAnnotation(fileUpload) }
}
}
documentation.applyResponseAnnotations(annotation.responses)
return documentation
}
private fun resolveNullValueFromContentType(fromType: KClass<*>, contentType: String): KClass<out Any> {
return if (fromType == NULL_CLASS::class) {
if (contentType.startsWith("text/")) {
// Default for text/html, etc is string
String::class
} else {
// Default for everything else is unit
Unit::class
}
} else {
fromType
}
}
private fun Operation.applyAnnotation(annotation: OpenApi) {
if (annotation.description.isNotNullString()) {
this.description = annotation.description
}
if (annotation.summary.isNotNullString()) {
this.summary = annotation.summary
}
if (annotation.operationId.isNotNullString()) {
this.operationId = annotation.operationId
}
if (annotation.deprecated) {
this.deprecated = annotation.deprecated
}
if (annotation.security.isNotEmpty()) {
this.applySecurity(annotation.security)
}
annotation.tags.forEach { tag -> this.addTagsItem(tag) }
}
private fun RequestBody.applyAnnotation(annotation: OpenApiRequestBody) {
if (annotation.required) {
this.required = annotation.required
}
if (annotation.description.isNotNullString()) {
this.description = annotation.description
}
}
private fun RequestBody.applyAnnotation(annotation: OpenApiComposedRequestBody) {
if (annotation.required) {
this.required = annotation.required
}
if (annotation.description.isNotNullString()) {
this.description = annotation.description
}
}
private fun RequestBody.applyAnnotation(annotation: OpenApiFileUpload) {
if (annotation.required) {
this.required = annotation.required
}
if (annotation.description.isNotNullString()) {
this.description = annotation.description
}
}
private fun OpenApiContent.asDocumentedContent(): DocumentedContent {
val content = this
val from = resolveNullValueFromContentType(content.from, content.type)
return DocumentedContent(
from = from.java,
isArray = content.isArray,
contentType = content.type
)
}
private fun OpenApiDocumentation.applyRequestBodyAnnotation(requestBody: OpenApiRequestBody) {
if (requestBody.content.isNotEmpty()) {
this.body(requestBody.content.map { it.asDocumentedContent() }, createUpdater { it.applyAnnotation(requestBody) })
}
}
private fun OpenApiDocumentation.applyComposedRequestBodyAnnotation(requestBody: OpenApiComposedRequestBody) {
val composition = when {
requestBody.anyOf.isNotEmpty() -> anyOf(*requestBody.anyOf.toList().map { it.asDocumentedContent() }.toTypedArray())
requestBody.oneOf.isNotEmpty() -> oneOf(*requestBody.oneOf.toList().map { it.asDocumentedContent() }.toTypedArray())
else -> null
}
if (composition != null) {
this.body(composition, requestBody.contentType, createUpdater { it.applyAnnotation(requestBody) })
}
}
private fun OpenApiDocumentation.applyResponseAnnotations(responses: Array<OpenApiResponse>) {
val documentation = this
responses.groupBy { it.status }.forEach { (status, list) ->
documentation.result(
documentedResponse = DocumentedResponse(
status = status,
content = list.flatMap { it.content.toList() }.map { it.asDocumentedContent() }
),
applyUpdates = { responseDocumentation ->
val description = list.map { it.description }.filter { it.isNotNullString() }.joinToString(separator = "; ")
if (description.isNotBlank()) {
responseDocumentation.description = description
}
}
)
}
}
private fun OpenApiDocumentation.applyParamAnnotation(`in`: String, param: OpenApiParam) {
val documentation = this
documentation.param(
documentedParameter = createDocumentedParam(`in`, param),
applyUpdates = { paramDocumentation ->
if (param.description.isNotNullString()) {
paramDocumentation.description = param.description
}
if (param.required) {
paramDocumentation.required = param.required
}
if (param.deprecated) {
paramDocumentation.deprecated = param.deprecated
}
if (param.allowEmptyValue) {
paramDocumentation.allowEmptyValue = param.allowEmptyValue
}
},
isRepeatable = param.isRepeatable
)
}
private fun Operation.applySecurity(securityArray: Array<OpenApiSecurity>) {
if (securityArray.isEmpty()) {
return
}
val operation = this
var securityRequirement = SecurityRequirement()
securityArray.forEach {
securityRequirement = securityRequirement.addList(it.name, it.scopes.toList())
}
operation.addSecurityItem(securityRequirement)
}
private fun createDocumentedParam(`in`: String, param: OpenApiParam) = DocumentedParameter(
`in` = `in`,
name = param.name,
type = param.type.java
)
private fun String.isNullString() = this == NULL_STRING
private fun String.isNotNullString() = !this.isNullString()
private fun String.correctNullValue(): String? = if (this.isNullString()) null else this
| apache-2.0 | 2f2106ffeacacac8a45d16f487417df9 | 36.792746 | 128 | 0.683576 | 4.757991 | false | false | false | false |
kichikuou/xsystem35-sdl2 | android/app/src/main/java/io/github/kichikuou/xsystem35/LauncherActivity.kt | 1 | 7916 | /* Copyright (C) 2019 <[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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package io.github.kichikuou.xsystem35
import android.app.*
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import java.io.*
private const val CONTENT_TYPE_ZIP = "application/zip"
private const val INSTALL_REQUEST = 1
private const val SAVEDATA_EXPORT_REQUEST = 2
private const val SAVEDATA_IMPORT_REQUEST = 3
class LauncherActivity : Activity(), LauncherObserver {
private lateinit var launcher: Launcher
private var progressDialog: ProgressDialogFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.launcher)
launcher = Launcher.getInstance(filesDir)
launcher.observer = this
if (launcher.isInstalling) {
showProgressDialog()
}
onGameListChange()
val listView = findViewById<ListView>(R.id.list)
listView.setOnItemClickListener { _, _, position, _ ->
onListItemClick(position)
}
listView.setOnItemLongClickListener { _, _, position, _ ->
onItemLongClick(position)
}
}
override fun onDestroy() {
launcher.observer = null
super.onDestroy()
}
private fun onListItemClick(position: Int) {
if (position < launcher.games.size) {
startGame(launcher.games[position].path, null)
} else {
val i = Intent(Intent.ACTION_GET_CONTENT)
i.type = CONTENT_TYPE_ZIP
startActivityForResult(Intent.createChooser(i, getString(R.string.choose_a_file)), INSTALL_REQUEST)
}
}
private fun onItemLongClick(position: Int): Boolean {
if (position < launcher.games.size) {
AlertDialog.Builder(this).setTitle(R.string.uninstall_dialog_title)
.setMessage(getString(R.string.uninstall_dialog_message, launcher.games[position].title))
.setPositiveButton(R.string.ok) {_, _ -> uninstall(position)}
.setNegativeButton(R.string.cancel) {_, _ -> }
.show()
}
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.launcher_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.export_savedata -> {
val i = Intent(Intent.ACTION_CREATE_DOCUMENT)
i.type = CONTENT_TYPE_ZIP
i.putExtra(Intent.EXTRA_TITLE, "savedata.zip")
startActivityForResult(i, SAVEDATA_EXPORT_REQUEST)
true
}
R.id.import_savedata -> {
val i = Intent(Intent.ACTION_GET_CONTENT)
i.type = CONTENT_TYPE_ZIP
startActivityForResult(Intent.createChooser(i, getString(R.string.choose_a_file)),
SAVEDATA_IMPORT_REQUEST)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != RESULT_OK)
return
val uri = data?.data ?: return
when (requestCode) {
INSTALL_REQUEST -> {
val input = contentResolver.openInputStream(uri) ?: return
showProgressDialog()
launcher.install(input, getArchiveName(uri))
}
SAVEDATA_EXPORT_REQUEST -> try {
launcher.exportSaveData(contentResolver.openOutputStream(uri)!!)
Toast.makeText(this, R.string.save_data_export_success, Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
Log.e("launcher", "Failed to export savedata", e)
errorDialog(R.string.save_data_export_error)
}
SAVEDATA_IMPORT_REQUEST -> {
val input = contentResolver.openInputStream(uri) ?: return
val errMsgId = launcher.importSaveData(input)
if (errMsgId == null) {
Toast.makeText(this, R.string.save_data_import_success, Toast.LENGTH_SHORT).show()
} else {
errorDialog(errMsgId)
}
}
}
}
override fun onGameListChange() {
val items = launcher.titles.toMutableList()
items.add(getString(R.string.install_from_zip))
val listView = findViewById<ListView>(R.id.list)
listView.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
}
override fun onInstallProgress(path: String) {
progressDialog?.setProgress(getString(R.string.install_progress, path))
}
override fun onInstallSuccess(path: File, archiveName: String?) {
dismissProgressDialog()
startGame(path, archiveName)
}
override fun onInstallFailure(msgId: Int) {
dismissProgressDialog()
errorDialog(msgId)
}
private fun startGame(path: File, archiveName: String?) {
val i = Intent()
i.setClass(applicationContext, GameActivity::class.java)
i.putExtra(GameActivity.EXTRA_GAME_ROOT, path.path)
i.putExtra(GameActivity.EXTRA_ARCHIVE_NAME, archiveName)
startActivity(i)
}
private fun uninstall(id: Int) {
launcher.uninstall(id)
}
private fun showProgressDialog() {
progressDialog = ProgressDialogFragment()
progressDialog!!.show(fragmentManager, "progress_dialog")
}
private fun dismissProgressDialog() {
progressDialog?.dismiss()
progressDialog = null
}
private fun errorDialog(msgId: Int) {
AlertDialog.Builder(this).setTitle(R.string.error_dialog_title)
.setMessage(msgId)
.setPositiveButton(R.string.ok) {_, _ -> }
.show()
}
private fun getArchiveName(uri: Uri): String? {
val cursor = contentResolver.query(uri, null, null, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
val column = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (column >= 0) {
val fname = it.getString(column)
return if (fname.endsWith(".zip", true)) fname.dropLast(4) else fname
}
}
}
return null
}
}
@Suppress("DEPRECATION") // for ProgressDialog
class ProgressDialogFragment : DialogFragment() {
private lateinit var dialog: ProgressDialog
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
dialog = ProgressDialog(activity)
return dialog.apply {
setTitle(R.string.install_dialog_title)
setCancelable(true)
}
}
fun setProgress(msg: String) {
dialog.setMessage(msg)
}
}
| gpl-2.0 | 44426ef98d503d9b6c5f8de1e288f6cb | 34.819005 | 111 | 0.620768 | 4.613054 | false | false | false | false |
kikermo/Things-Audio-Renderer | core/src/main/java/org/kikermo/thingsaudio/core/model/Track.kt | 1 | 254 | package org.kikermo.thingsaudio.core.model
data class Track(
val uuid: String,
val title: String? = null,
var album: String? = null,
var artist: String? = null,
var length: Int = 0,
var url: String,
var art: String? = null
)
| gpl-3.0 | aea9ff0aa13a1f0f1546a98ba89334b8 | 22.090909 | 42 | 0.629921 | 3.298701 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/address/HousenumberParser.kt | 1 | 5394 | package de.westnordost.streetcomplete.quests.address
import de.westnordost.streetcomplete.data.elementfilter.StringWithCursor
/** parses 99999/a, 9/a, 99/9, 99a, 99 a, 9 / a, "95-98", "5,5a,6", "5d-5f, 7", "5-1" etc. into an appropriate data
* structure or return null if it cannot be parsed */
fun parseHouseNumber(string: String): HouseNumbers? {
return HouseNumbers(string.split(",").map { part ->
val range = part.split("-")
when (range.size) {
1 -> SingleHouseNumbersPart(parseHouseNumberParts(range[0]) ?: return null)
2 -> {
val start = parseHouseNumberParts(range[0]) ?: return null
val end = parseHouseNumberParts(range[1]) ?: return null
if (start < end) {
HouseNumbersPartsRange(start, end)
}
// reverse ranges are interpreted like sub-housenumbers, i.e. 4-2 is about the same as 4/2
else {
SingleHouseNumbersPart(parseHouseNumberParts(part) ?: return null)
}
}
else -> return null
}
})
}
private fun parseHouseNumberParts(string: String): StructuredHouseNumber? {
val c = StringWithCursor(string)
val houseNumber = c.nextMatchesAndAdvance("\\p{N}{1,5}".toRegex())?.value?.toIntOrNull() ?: return null
if (c.isAtEnd()) return SimpleHouseNumber(houseNumber)
val separatorWithNumber = c.nextMatchesAndAdvance("(\\s?[/-]\\s?)(\\p{N})".toRegex())
if (separatorWithNumber != null) {
if (!c.isAtEnd()) return null
return HouseNumberWithNumber(
houseNumber,
separatorWithNumber.groupValues[1],
separatorWithNumber.groupValues[2].toInt()
)
}
val separatorWithLetter = c.nextMatchesAndAdvance("(\\s?/?\\s?)(\\p{L})".toRegex())
if (separatorWithLetter != null) {
if (!c.isAtEnd()) return null
return HouseNumberWithLetter(
houseNumber,
separatorWithLetter.groupValues[1],
separatorWithLetter.groupValues[2]
)
}
return null
}
data class HouseNumbers(val list: List<HouseNumbersPart>) {
override fun toString() = list.joinToString(",")
}
/** -------------------------------------- HouseNumbersPart ------------------------------------- */
sealed class HouseNumbersPart: Comparable<HouseNumbersPart> {
override fun compareTo(other: HouseNumbersPart): Int = when(this) {
is SingleHouseNumbersPart -> when (other) {
// e.g. 12c < 15
is SingleHouseNumbersPart -> sign(
single.compareTo(other.single)
)
// e.g. 10 < 12-14, but 10 ≮ 8-12 (and also not bigger than)
is HouseNumbersPartsRange -> sign(
single.compareTo(other.start),
single.compareTo(other.end)
)
}
is HouseNumbersPartsRange -> when (other) {
// e.g. 12-14 < 16a, but 12-14 ≮ 13 (and also not bigger than)
is SingleHouseNumbersPart -> sign(
start.compareTo(other.single),
end.compareTo(other.single)
)
// e.g. 8-14 < 16-18 but not if the ranges intersect
is HouseNumbersPartsRange -> sign(
start.compareTo(other.start),
start.compareTo(other.end),
end.compareTo(other.start),
end.compareTo(other.end)
)
}
}
}
private fun sign(vararg numbers: Int): Int = when {
numbers.all { it > 0 } -> 1
numbers.all { it < 0} -> -1
else -> 0
}
/** e.g. 5a-12, 100-20/1*/
data class HouseNumbersPartsRange(
val start: StructuredHouseNumber,
val end: StructuredHouseNumber
): HouseNumbersPart() {
override fun toString() = "$start-$end"
}
data class SingleHouseNumbersPart(val single: StructuredHouseNumber) : HouseNumbersPart() {
override fun toString() = "$single"
}
/** ----------------------------------- StructuredHouseNumber ---------------------------------- */
sealed class StructuredHouseNumber: Comparable<StructuredHouseNumber> {
abstract val number: Int
override fun compareTo(other: StructuredHouseNumber): Int {
val diffNumber = number - other.number
if (diffNumber != 0) return diffNumber
when {
this is HouseNumberWithLetter && other is HouseNumberWithLetter -> {
if (letter < other.letter) return -1
else if (letter > other.letter) return +1
}
this is HouseNumberWithNumber && other is HouseNumberWithNumber -> {
val diffNumber2 = number2 - other.number2
if (diffNumber2 != 0) return diffNumber2
}
}
return 0
}
}
/** e.g. 12 */
data class SimpleHouseNumber(override val number: Int) : StructuredHouseNumber() {
override fun toString() = number.toString()
}
/** e.g. 12c */
data class HouseNumberWithLetter(
override val number: Int,
val separator: String,
val letter: String
) : StructuredHouseNumber() {
override fun toString() = "$number$separator$letter"
}
/** e.g. 12/3 */
data class HouseNumberWithNumber(
override val number: Int,
val separator: String,
val number2: Int
) : StructuredHouseNumber() {
override fun toString() = "$number$separator$number2"
}
| gpl-3.0 | 01f28eff86dcb2209492301471bc86bf | 34.695364 | 115 | 0.585343 | 4.254144 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/CollectionNameSorter.kt | 1 | 979 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.extensions.asRating
import com.boardgamegeek.extensions.firstChar
class CollectionNameSorter(context: Context) : CollectionSorter(context) {
@StringRes
public override val typeResId = R.string.collection_sort_type_collection_name
@StringRes
override val descriptionResId = R.string.collection_sort_collection_name
override fun sort(items: Iterable<CollectionItemEntity>): List<CollectionItemEntity> {
return items.sortedBy { it.sortName }
}
override fun getHeaderText(item: CollectionItemEntity) = item.sortName.firstChar()
override fun getRating(item: CollectionItemEntity): Double = item.averageRating
override fun getRatingText(item: CollectionItemEntity) = getRating(item).asRating(context, R.string.unrated_abbr)
}
| gpl-3.0 | ecb4a05c0156e164153f0e7d9848a726 | 36.653846 | 117 | 0.797753 | 4.553488 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/utils/extensions/FragmentExt.kt | 1 | 826 | package org.fossasia.openevent.general.utils.extensions
import android.os.Build
import androidx.fragment.app.Fragment
import androidx.transition.TransitionInflater
const val SUPPORTED_TRANSITION_VERSION = Build.VERSION_CODES.O
fun Fragment.setStartPostponedEnterTransition() {
if (Build.VERSION.SDK_INT >= SUPPORTED_TRANSITION_VERSION) {
this.startPostponedEnterTransition()
}
}
fun Fragment.setSharedElementEnterTransition(transition: Int = android.R.transition.move) {
if (Build.VERSION.SDK_INT >= SUPPORTED_TRANSITION_VERSION) {
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(transition)
}
}
fun Fragment.setPostponeSharedElementTransition() {
if (Build.VERSION.SDK_INT >= SUPPORTED_TRANSITION_VERSION) {
postponeEnterTransition()
}
}
| apache-2.0 | 91ec2978efe1c9eaf6c63bfe354211eb | 32.04 | 101 | 0.773608 | 4.44086 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/inventory/container/layout/RootPlayerContainerLayout.kt | 1 | 3761 | /*
* 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.inventory.container.layout
import org.lanternpowered.api.item.inventory.container.layout.ContainerSlot
import org.lanternpowered.api.item.inventory.container.layout.CraftingContainerLayout
import org.lanternpowered.api.item.inventory.container.layout.GridContainerLayout
import org.lanternpowered.api.item.inventory.container.layout.TopPlayerContainerLayout
import org.lanternpowered.api.text.textOf
import org.lanternpowered.server.inventory.client.ClientContainer
import org.lanternpowered.server.network.packet.Packet
class RootPlayerContainerLayout : LanternTopBottomContainerLayout<TopPlayerContainerLayout>(
title = TITLE, slotFlags = ALL_INVENTORY_FLAGS
) {
companion object {
private val TITLE = textOf("Player")
private val TOP_INVENTORY_FLAGS = intArrayOf(
Flags.DISABLE_SHIFT_INSERTION + Flags.REVERSE_SHIFT_INSERTION + ClientContainer.FLAG_IGNORE_DOUBLE_CLICK, // Crafting output slot
Flags.DISABLE_SHIFT_INSERTION, // Crafting input slot 1
Flags.DISABLE_SHIFT_INSERTION, // Crafting input slot 2
Flags.DISABLE_SHIFT_INSERTION, // Crafting input slot 3
Flags.DISABLE_SHIFT_INSERTION, // Crafting input slot 4
Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.silentSlotIndex(40), // Equipment slot 1
Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.silentSlotIndex(39), // Equipment slot 2
Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.silentSlotIndex(38), // Equipment slot 3
Flags.POSSIBLY_DISABLED_SHIFT_INSERTION + Flags.silentSlotIndex(37), // Equipment slot 4
Flags.DISABLE_SHIFT_INSERTION + Flags.silentSlotIndex(41) // Offhand slot
)
val OFFHAND_INDEX = TOP_INVENTORY_FLAGS.size - 1
const val ARMOR_SIZE = 4
val ARMOR_START_INDEX = OFFHAND_INDEX - ARMOR_SIZE
private val ALL_INVENTORY_FLAGS = TOP_INVENTORY_FLAGS + MAIN_INVENTORY_FLAGS
}
// The vanilla is the offhand slot the last index, after the main inventory,
// but we modify this to move the slot before the main inventory
override fun serverSlotIndexToClient(index: Int): Int {
if (index == OFFHAND_INDEX)
return ALL_INVENTORY_FLAGS.lastIndex
if (index > OFFHAND_INDEX)
return index - 1
return index
}
override fun clientSlotIndexToServer(index: Int): Int {
if (index == ALL_INVENTORY_FLAGS.lastIndex)
return OFFHAND_INDEX
if (index >= OFFHAND_INDEX)
return index + 1
return index
}
override fun createOpenPackets(data: ContainerData): List<Packet> = throw UnsupportedOperationException()
override val top: TopPlayerContainerLayout = SubTopPlayerContainerLayout(0, TOP_INVENTORY_FLAGS.size, this)
}
private class SubTopPlayerContainerLayout(
offset: Int, size: Int, val root: RootPlayerContainerLayout
) : SubContainerLayout(offset, size, root), TopPlayerContainerLayout {
override val armor: GridContainerLayout =
SubGridContainerLayout(RootPlayerContainerLayout.ARMOR_START_INDEX, 1, RootPlayerContainerLayout.ARMOR_SIZE, this.root)
override val crafting: CraftingContainerLayout = SubCraftingContainerLayout(0, 2, 2, this.root)
override val offhand: ContainerSlot = this[RootPlayerContainerLayout.OFFHAND_INDEX]
}
| mit | 1aa15d0f69e64b2c87b77a5bef5dbb35 | 43.77381 | 145 | 0.717362 | 4.445626 | false | false | false | false |
colmcoughlan/alchemy | app/src/main/java/com/colmcoughlan/colm/alchemy/service/HttpCharityService.kt | 1 | 2042 | package com.colmcoughlan.colm.alchemy.service
import android.content.Context
import android.util.Log
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.colmcoughlan.colm.alchemy.R
import com.colmcoughlan.colm.alchemy.StaticState
import com.colmcoughlan.colm.alchemy.model.Callback
import com.colmcoughlan.colm.alchemy.model.CharitiesDto
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
class HttpCharityService(context: Context): CharityService {
private val queue = Volley.newRequestQueue(context)
private val url = context.resources.getString(R.string.server_url)
private val objectMapper = jacksonObjectMapper()
override fun getCharities(callback: Callback) {
if (!StaticState.shouldRefreshCharities()){
callback.onComplete()
return
}
val request = object: StringRequest(Method.GET, url,
{charitiesString ->
run {
val charitiesDto = objectMapper.readValue<CharitiesDto>(charitiesString)
val charities = charitiesDto.charities.map { (k, v) ->
v.copy(
name = k,
donationOptions = objectMapper.readValue(v.donation_options),
frequencies = objectMapper.readValue(v.freq)
)
}
Log.i("http",charities.toString() )
StaticState.charities = charities
callback.onComplete()
}
},
{e -> Log.e("http", "error fetching charities", e) })
{
override fun getHeaders(): MutableMap<String, String>{
return mutableMapOf(Pair("client-id", "alchemy"))
}
}
queue.add(request)
}
} | mit | c052d2d7b70201a90b58531dcba6088e | 37.307692 | 93 | 0.592556 | 4.683486 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/PresentExperienceRoute.kt | 1 | 2977 | package io.rover.sdk.experiences
import android.content.Context
import android.content.Intent
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.platform.asAndroidUri
import io.rover.sdk.core.platform.parseAsQueryParameters
import io.rover.sdk.core.routing.Route
import io.rover.sdk.experiences.ui.containers.RoverActivity
import java.net.URI
class PresentExperienceRoute(
private val urlSchemes: List<String>,
private val associatedDomains: List<String>,
private val presentExperienceIntents: PresentExperienceIntents
) : Route {
override fun resolveUri(uri: URI?): Intent? {
// Experiences can be opened either by a deep link or a universal link.
return when {
(uri?.scheme == "https" || uri?.scheme == "http") && associatedDomains.contains(uri.host) -> {
// universal link!
val queryParameters = uri.query?.parseAsQueryParameters()
val screenID = queryParameters?.let {it["screenID"] }
presentExperienceIntents.displayExperienceIntentFromCampaignLink(uri, screenID)
}
urlSchemes.contains(uri?.scheme) && uri?.authority == "presentExperience" -> {
val queryParameters = uri.query.parseAsQueryParameters()
val possibleCampaignId = queryParameters["campaignID"]
// For now, you need to support deep links with both `experienceID` and `id` to enable backwards compatibility
// For Rover 3.0 devices, the Rover server will send deep links within push notifications using `experienceID` parameter. For backwards compatibility, `id` parameter is also supported.
val experienceId = queryParameters["experienceID"] ?: queryParameters["id"]
val screenID = queryParameters["screenID"]
if (experienceId == null) {
log.w("A presentExperience deep link lacked either a `campaignID` or `id` parameter.")
return null
}
presentExperienceIntents.displayExperienceIntentByExperienceId(experienceId, possibleCampaignId, screenID)
}
else -> null // no match.
}
}
}
/**
* Override this class to configure Rover to open Experiences with a different Activity other than
* the bundled [RoverActivity].
*/
open class PresentExperienceIntents(
private val applicationContext: Context
) {
fun displayExperienceIntentByExperienceId(experienceId: String, possibleCampaignId: String?, screenID: String? = null): Intent {
return RoverActivity.makeIntent(applicationContext, experienceId = experienceId, campaignId = possibleCampaignId, initialScreenId = screenID)
}
fun displayExperienceIntentFromCampaignLink(universalLink: URI, screenID: String? = null): Intent {
return RoverActivity.makeIntent(applicationContext, experienceUrl = universalLink.asAndroidUri(), initialScreenId = screenID)
}
}
| apache-2.0 | 8ceda55b59e9acc474a4570c74d7b298 | 47.016129 | 200 | 0.693315 | 4.755591 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/latex/logtab/LatexLogMagicRegex.kt | 1 | 2604 | package nl.hannahsten.texifyidea.run.latex.logtab
/**
* Regex (text) every error handler and message processor can use.
*/
object LatexLogMagicRegex {
// Line length (including newline at the end)
const val LINE_WIDTH = 80
// Match filename:linenumber: as this probably denotes an error, but not if it appears in a stacktrace
// and starts with ... and also not if this starts with a ( as then we assume the ( is not part of the file
const val FILE_LINE_REGEX: String =
"""(?!\s*\.\.\.)(?<file>[^\(\)]+\.\w+):(?<line>\d+):""" // error
val REPORTED_ON_LINE_REGEX =
"""( Reported| Found)? on input line (?<line>\d+).""".toRegex()
const val LINE_REGEX: String =
"""on input line (?<line>\d+).""" // meestal warning
const val LATEX_ERROR_REGEX: String = "!" // error
const val PDFTEX_ERROR_REGEX: String = "!pdfTeX error:"
const val LATEX_WARNING_REGEX: String = "LaTeX( Font)? Warning:" // warning
const val PACKAGE_REGEX: String =
"""(?<package>[\d\w-\.]+)""" // package error/warning?
const val REFERENCE_REGEX: String =
"""(?<label>(`|').+')""" // reference warning
const val PACKAGE_WARNING_CONTINUATION = "\\(\\w+\\) {${"Package warning:".length}}"
const val DUPLICATE_WHITESPACE =
"""\s{2,}"""
val lineNumber =
"""^l.\d+ """.toRegex()
/*
* Errors
*/
/** A variation on [FILE_LINE_REGEX] by lualatex (?) */
val directLuaError =
"""^\((?!\s*\.\.\.)(.+\.\w+)\)(\[.+])?:(?<line>\d+): (?<message>.*)""".toRegex()
val fixMeError =
"""FiXme (Fatal )?Error: '(?<message>.+)' on input line (?<line>\d+).""".toRegex()
/*
* Warnings
*/
val fixMeWarning =
"""FiXme Warning: '(?<message>.+)' on input line (?<line>\d+).""".toRegex()
val pdfTeXWarning =
"""pdfTeX warning(.+)?: (?<message>.+)""".toRegex()
val TEX_MISC_WARNINGS = listOf(
"LaTeX Warning: ",
"LaTeX Font Warning: ",
"AVAIL list clobbered at",
"Citation",
"Double-AVAIL list clobbered at",
"Doubly free location at",
"Bad flag at",
"Runaway definition",
"Runaway argument",
"Runaway text",
"Missing character: There is no",
"No auxiliary output files.",
"No file ",
"No pages of output.",
"Underfull \\hbox",
"Overfull \\hbox",
"Loose \\hbox",
"Tight \\hbox",
"Underfull \\vbox",
"Overfull \\vbox",
"Loose \\vbox",
"Tight \\vbox",
"(\\end occurred",
)
} | mit | fc2db1ef96252a2c9b8ab736f6b580ea | 33.276316 | 111 | 0.540323 | 3.768452 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/feed/FeedItem.kt | 1 | 4726 | package com.pr0gramm.app.feed
import android.os.Parcel
import com.pr0gramm.app.Instant
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.parcel.*
/**
* This is an item in pr0gramm feed item to be displayed. It is backed
* by the data of an [Api.Feed.Item].
*/
data class FeedItem(
val created: Instant,
val thumbnail: String,
val image: String,
val fullsize: String,
val user: String,
val userId: Long,
val id: Long,
val promotedId: Long,
val width: Int,
val height: Int,
val up: Int,
val down: Int,
val mark: Int,
val flags: Int,
val audio: Boolean,
val deleted: Boolean,
val placeholder: Boolean,
) : DefaultParcelable {
constructor(item: Api.Feed.Item) : this(
id = item.id,
promotedId = item.promoted,
userId = item.userId,
thumbnail = item.thumb,
image = item.image,
fullsize = item.fullsize,
user = item.user,
up = item.up,
down = item.down,
mark = item.mark,
created = item.created,
flags = item.flags,
width = item.width,
height = item.height,
audio = item.audio,
deleted = item.deleted,
placeholder = false,
)
/**
* Returns the content type of this Item, falling back to [ContentType.SFW]
* if no type is available.
*/
val contentType: ContentType
get() = ContentType.valueOf(flags) ?: ContentType.SFW
val isVideo: Boolean
get() = isVideoUri(image)
val isImage: Boolean
get() = isImageUri(image)
val isPinned: Boolean
get() = promotedId > 1_000_000_000
/**
* Gets the id of this feed item depending on the type of the feed..
* @param type The type of feed.
*/
fun id(type: FeedType): Long {
return (if (type === FeedType.PROMOTED) promotedId else id)
}
override fun toString(): String = "FeedItem(id=$id)"
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id.toInt())
dest.writeInt(promotedId.toInt())
dest.writeInt(userId.toInt())
// deduplicate values for thumb & fullsize if equal to 'image'
dest.writeString(image)
dest.writeString(thumbnail.takeIf { it != image })
dest.writeString(fullsize.takeIf { it != image })
dest.writeString(user)
dest.writeInt(up)
dest.writeInt(down)
dest.write(created)
dest.writeInt(width)
dest.writeInt(height)
var bits = 0
bits = bits.or(if (audio) 0b0001 else 0)
bits = bits.or(if (deleted) 0b0010 else 0)
bits = bits.or(if (placeholder) 0b0100 else 0)
bits = bits.or((mark and 0xff) shl 8)
bits = bits.or((flags and 0xff) shl 16)
dest.writeInt(bits)
}
companion object CREATOR : ConstructorCreator<FeedItem>(javaClassOf(), { source ->
val id = source.readInt().toLong()
val promotedId = source.readInt().toLong()
val userId = source.readInt().toLong()
// deduplicate values for thumb & fullsize if equal to image
val image = source.readStringNotNull()
val thumbnail = source.readString() ?: image
val fullsize = source.readString() ?: image
val user = source.readStringNotNull()
val up = source.readInt()
val down = source.readInt()
val created = source.read(Instant)
val width = source.readInt()
val height = source.readInt()
val bits = source.readInt()
val audio = (bits and 0b0001) != 0
val deleted = (bits and 0b0010) != 0
val placeholder = (bits and 0b0100) != 0
val mark = (bits ushr 8) and 0xff
val flags = (bits ushr 16) and 0xff
FeedItem(
id = id,
promotedId = promotedId,
userId = userId,
image = image,
thumbnail = thumbnail,
fullsize = fullsize,
user = user,
up = up,
down = down,
created = created,
width = width,
height = height,
mark = mark,
flags = flags,
audio = audio,
deleted = deleted,
placeholder = placeholder,
)
})
}
fun isVideoUri(image: String): Boolean {
return image.endsWith(".webm") || image.endsWith(".mp4")
}
fun isImageUri(image: String): Boolean {
return image.endsWith(".jpg") || image.endsWith(".png")
}
| mit | 68b307f13ef8db45083be302beb6757f | 27.993865 | 86 | 0.555226 | 4.219643 | false | false | false | false |
FHannes/intellij-community | plugins/stats-collector/test/com/intellij/stats/completion/CompletionEventsLoggingTest.kt | 11 | 4557 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.stats.events.completion.Action.*
import com.intellij.stats.events.completion.ExplicitSelectEvent
import org.assertj.core.api.Assertions.assertThat
class CompletionEventsLoggingTest : CompletionLoggingTestBase() {
fun `test item selected on just typing`() {
myFixture.type('.')
myFixture.completeBasic()
val itemsOnStart = lookup.items
myFixture.type("ru")
trackedEvents.assertOrder(
COMPLETION_STARTED,
TYPE
)
myFixture.type("n)")
trackedEvents.assertOrder(
COMPLETION_STARTED,
TYPE,
TYPE,
TYPE,
EXPLICIT_SELECT //should be TYPED_SELECT investigate
)
checkLoggedAllElements(itemsOnStart)
checkSelectedCorrectId(itemsOnStart, "run")
}
private fun checkLoggedAllElements(itemsOnStart: MutableList<LookupElement>) {
assertThat(completionStartedEvent.newCompletionListItems).hasSize(itemsOnStart.size)
assertThat(completionStartedEvent.completionListIds).hasSize(itemsOnStart.size)
}
private fun checkSelectedCorrectId(itemsOnStart: MutableList<LookupElement>, selectedString: String) {
val selectedIndex = itemsOnStart.indexOfFirst { it.lookupString == selectedString }
val selectedId = completionStartedEvent.completionListIds[selectedIndex]
val select = trackedEvents.last() as ExplicitSelectEvent
assertThat(select.selectedId).isEqualTo(selectedId)
}
fun `test wrong typing`() {
myFixture.type('.')
myFixture.completeBasic()
myFixture.type('r')
myFixture.type('u')
myFixture.type('x')
lookup.hide() //figure out why needed here
trackedEvents.assertOrder(
COMPLETION_STARTED,
TYPE,
TYPE,
COMPLETION_CANCELED
)
}
fun `test down up buttons`() {
myFixture.type('.')
myFixture.completeBasic()
val elementsOnStart = lookup.items
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)
myFixture.type('\n')
trackedEvents.assertOrder(
COMPLETION_STARTED,
DOWN,
DOWN,
DOWN,
UP,
UP,
UP,
EXPLICIT_SELECT
)
checkLoggedAllElements(elementsOnStart)
checkSelectedCorrectId(elementsOnStart, elementsOnStart.first().lookupString)
}
fun `test backspace`() {
myFixture.type('.')
myFixture.completeBasic()
val elementsOnStart = lookup.items
myFixture.type("ru")
myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE)
myFixture.type('u')
myFixture.type('\n')
trackedEvents.assertOrder(
COMPLETION_STARTED,
TYPE,
TYPE,
BACKSPACE,
TYPE,
EXPLICIT_SELECT
)
checkSelectedCorrectId(elementsOnStart, "run")
checkLoggedAllElements(elementsOnStart)
}
fun `test if typed prefix is correct completion variant, pressing dot will select it`() {
myFixture.completeBasic()
val elementsOnStart = lookup.items
myFixture.type('.')
trackedEvents.assertOrder(
COMPLETION_STARTED,
EXPLICIT_SELECT
)
checkLoggedAllElements(elementsOnStart)
}
} | apache-2.0 | 4822eab0c29dde1665bf05c9bfb570c6 | 29.386667 | 106 | 0.666886 | 4.884244 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/movecopy/MoveFilesTask.kt | 1 | 6210 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.asynchronous.asynctasks.movecopy
import android.content.Context
import android.content.Intent
import android.widget.Toast
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.asynchronous.asynctasks.Task
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil
import com.amaze.filemanager.asynchronous.services.CopyService
import com.amaze.filemanager.database.CryptHandler
import com.amaze.filemanager.database.models.explorer.EncryptedEntry
import com.amaze.filemanager.fileoperations.filesystem.OpenMode
import com.amaze.filemanager.filesystem.HybridFile
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.filesystem.files.CryptUtil
import com.amaze.filemanager.filesystem.files.FileUtils
import com.amaze.filemanager.ui.activities.MainActivity
import org.slf4j.Logger
import org.slf4j.LoggerFactory
data class MoveFilesReturn(
val movedCorrectly: Boolean,
val invalidOperation: Boolean,
val destinationSize: Long,
val totalSize: Long
)
class MoveFilesTask(
val files: ArrayList<ArrayList<HybridFileParcelable>>,
val isRootExplorer: Boolean,
val currentPath: String,
context: Context,
val mode: OpenMode,
val paths: ArrayList<String>
) : Task<MoveFilesReturn, MoveFiles> {
private val log: Logger = LoggerFactory.getLogger(MoveFilesTask::class.java)
private val task: MoveFiles = MoveFiles(files, isRootExplorer, context, mode, paths)
private val applicationContext: Context = context.applicationContext
override fun getTask(): MoveFiles = task
override fun onError(error: Throwable) {
log.error("Unexpected error on file move: ", error)
}
override fun onFinish(value: MoveFilesReturn) {
val (movedCorrectly, invalidOperation, destinationSize, totalBytes) = value
if (movedCorrectly) {
onMovedCorrectly(invalidOperation)
} else {
onMovedFail(destinationSize, totalBytes)
}
}
private fun onMovedCorrectly(invalidOperation: Boolean) {
if (currentPath == paths[0]) {
// mainFrag.updateList();
val intent = Intent(MainActivity.KEY_INTENT_LOAD_LIST)
intent.putExtra(MainActivity.KEY_INTENT_LOAD_LIST_FILE, paths[0])
applicationContext.sendBroadcast(intent)
}
if (invalidOperation) {
Toast.makeText(
applicationContext,
R.string.some_files_failed_invalid_operation,
Toast.LENGTH_LONG
)
.show()
}
for (i in paths.indices) {
val targetFiles: MutableList<HybridFile> = ArrayList()
val sourcesFiles: MutableList<HybridFileParcelable> = ArrayList()
for (f in files[i]) {
val file = HybridFile(
OpenMode.FILE,
paths[i] + "/" + f.getName(applicationContext)
)
targetFiles.add(file)
}
for (hybridFileParcelables in files) {
sourcesFiles.addAll(hybridFileParcelables)
}
FileUtils.scanFile(applicationContext, sourcesFiles.toTypedArray())
FileUtils.scanFile(applicationContext, targetFiles.toTypedArray())
}
// updating encrypted db entry if any encrypted file was moved
AppConfig.getInstance()
.runInBackground {
for (i in paths.indices) {
for (file in files[i]) {
if (file.getName(applicationContext).endsWith(CryptUtil.CRYPT_EXTENSION)) {
val oldEntry = CryptHandler.findEntry(file.path)
if (oldEntry != null) {
val newEntry = EncryptedEntry()
newEntry.id = oldEntry.id
newEntry.password = oldEntry.password
newEntry.path = paths[i] + "/" + file.getName(applicationContext)
CryptHandler.updateEntry(oldEntry, newEntry)
}
}
}
}
}
}
private fun onMovedFail(destinationSize: Long, totalBytes: Long) {
if (totalBytes > 0 && destinationSize < totalBytes) {
// destination don't have enough space; return
Toast.makeText(
applicationContext,
applicationContext.resources.getString(R.string.in_safe),
Toast.LENGTH_LONG
)
.show()
return
}
for (i in paths.indices) {
val intent = Intent(applicationContext, CopyService::class.java)
intent.putExtra(CopyService.TAG_COPY_SOURCES, files[i])
intent.putExtra(CopyService.TAG_COPY_TARGET, paths[i])
intent.putExtra(CopyService.TAG_COPY_MOVE, true)
intent.putExtra(CopyService.TAG_COPY_OPEN_MODE, mode.ordinal)
intent.putExtra(CopyService.TAG_IS_ROOT_EXPLORER, isRootExplorer)
ServiceWatcherUtil.runService(applicationContext, intent)
}
}
}
| gpl-3.0 | 438b6f30bc892240b997074103d4efc3 | 39.324675 | 107 | 0.646055 | 4.758621 | false | false | false | false |
ansman/okhttp | okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt | 6 | 13752 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls.internal.der
import java.math.BigInteger
import java.net.ProtocolException
import okio.ByteString
/**
* ASN.1 adapters adapted from the specifications in [RFC 5280][rfc_5280].
*
* [rfc_5280]: https://tools.ietf.org/html/rfc5280
*/
@Suppress("UNCHECKED_CAST") // This needs to cast decoded collections.
internal object CertificateAdapters {
/**
* ```
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime
* }
* ```
*
* RFC 5280, section 4.1.2.5:
*
* > CAs conforming to this profile MUST always encode certificate validity dates through the year
* > 2049 as UTCTime; certificate validity dates in 2050 or later MUST be encoded as
* > GeneralizedTime.
*/
internal val time: DerAdapter<Long> = object : DerAdapter<Long> {
override fun matches(header: DerHeader): Boolean {
return Adapters.UTC_TIME.matches(header) || Adapters.GENERALIZED_TIME.matches(header)
}
override fun fromDer(reader: DerReader): Long {
val peekHeader = reader.peekHeader()
?: throw ProtocolException("expected time but was exhausted at $reader")
return when {
peekHeader.tagClass == Adapters.UTC_TIME.tagClass &&
peekHeader.tag == Adapters.UTC_TIME.tag -> {
Adapters.UTC_TIME.fromDer(reader)
}
peekHeader.tagClass == Adapters.GENERALIZED_TIME.tagClass &&
peekHeader.tag == Adapters.GENERALIZED_TIME.tag -> {
Adapters.GENERALIZED_TIME.fromDer(reader)
}
else -> throw ProtocolException("expected time but was $peekHeader at $reader")
}
}
override fun toDer(writer: DerWriter, value: Long) {
// [1950-01-01T00:00:00..2050-01-01T00:00:00Z)
if (value in -631_152_000_000L until 2_524_608_000_000L) {
Adapters.UTC_TIME.toDer(writer, value)
} else {
Adapters.GENERALIZED_TIME.toDer(writer, value)
}
}
}
/**
* ```
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time
* }
* ```
*/
private val validity: BasicDerAdapter<Validity> = Adapters.sequence(
"Validity",
time,
time,
decompose = {
listOf(
it.notBefore,
it.notAfter
)
},
construct = {
Validity(
notBefore = it[0] as Long,
notAfter = it[1] as Long
)
}
)
/** The type of the parameters depends on the algorithm that precedes it. */
private val algorithmParameters: DerAdapter<Any?> = Adapters.usingTypeHint { typeHint ->
when (typeHint) {
// This type is pretty strange. The spec says that for certain algorithms we must encode null
// when it is present, and for others we must omit it!
// https://tools.ietf.org/html/rfc4055#section-2.1
ObjectIdentifiers.sha256WithRSAEncryption -> Adapters.NULL
ObjectIdentifiers.rsaEncryption -> Adapters.NULL
ObjectIdentifiers.ecPublicKey -> Adapters.OBJECT_IDENTIFIER
else -> null
}
}
/**
* ```
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
* ```
*/
internal val algorithmIdentifier: BasicDerAdapter<AlgorithmIdentifier> = Adapters.sequence(
"AlgorithmIdentifier",
Adapters.OBJECT_IDENTIFIER.asTypeHint(),
algorithmParameters,
decompose = {
listOf(
it.algorithm,
it.parameters
)
},
construct = {
AlgorithmIdentifier(
algorithm = it[0] as String,
parameters = it[1]
)
}
)
/**
* ```
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL
* }
* ```
*/
private val basicConstraints: BasicDerAdapter<BasicConstraints> = Adapters.sequence(
"BasicConstraints",
Adapters.BOOLEAN.optional(defaultValue = false),
Adapters.INTEGER_AS_LONG.optional(),
decompose = {
listOf(
it.ca,
it.maxIntermediateCas
)
},
construct = {
BasicConstraints(
ca = it[0] as Boolean,
maxIntermediateCas = it[1] as Long?
)
}
)
/**
* Note that only a subset of available choices are implemented.
*
* ```
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER
* }
* ```
*
* The first property of the pair is the adapter that was used, the second property is the value.
*/
internal val generalNameDnsName = Adapters.IA5_STRING.withTag(tag = 2L)
internal val generalNameIpAddress = Adapters.OCTET_STRING.withTag(tag = 7L)
internal val generalName: DerAdapter<Pair<DerAdapter<*>, Any?>> = Adapters.choice(
generalNameDnsName,
generalNameIpAddress,
Adapters.ANY_VALUE
)
/**
* ```
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
* ```
*/
private val subjectAlternativeName: BasicDerAdapter<List<Pair<DerAdapter<*>, Any?>>> =
generalName.asSequenceOf()
/**
* This uses the preceding extension ID to select which adapter to use for the extension value
* that follows.
*/
private val extensionValue: BasicDerAdapter<Any?> = Adapters.usingTypeHint { typeHint ->
when (typeHint) {
ObjectIdentifiers.subjectAlternativeName -> subjectAlternativeName
ObjectIdentifiers.basicConstraints -> basicConstraints
else -> null
}
}.withExplicitBox(
tagClass = Adapters.OCTET_STRING.tagClass,
tag = Adapters.OCTET_STRING.tag,
forceConstructed = false
)
/**
* ```
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* -- contains the DER encoding of an ASN.1 value
* -- corresponding to the extension type identified
* -- by extnID
* }
* ```
*/
internal val extension: BasicDerAdapter<Extension> = Adapters.sequence(
"Extension",
Adapters.OBJECT_IDENTIFIER.asTypeHint(),
Adapters.BOOLEAN.optional(defaultValue = false),
extensionValue,
decompose = {
listOf(
it.id,
it.critical,
it.value
)
},
construct = {
Extension(
id = it[0] as String,
critical = it[1] as Boolean,
value = it[2]
)
}
)
/**
* ```
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue
* }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY -- DEFINED BY AttributeType
* ```
*/
private val attributeTypeAndValue: BasicDerAdapter<AttributeTypeAndValue> = Adapters.sequence(
"AttributeTypeAndValue",
Adapters.OBJECT_IDENTIFIER,
Adapters.any(
String::class to Adapters.UTF8_STRING,
Nothing::class to Adapters.PRINTABLE_STRING,
AnyValue::class to Adapters.ANY_VALUE
),
decompose = {
listOf(
it.type,
it.value
)
},
construct = {
AttributeTypeAndValue(
type = it[0] as String,
value = it[1]
)
}
)
/**
* ```
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
* ```
*/
internal val rdnSequence: BasicDerAdapter<List<List<AttributeTypeAndValue>>> =
attributeTypeAndValue.asSetOf().asSequenceOf()
/**
* ```
* Name ::= CHOICE {
* -- only one possibility for now --
* rdnSequence RDNSequence
* }
* ```
*/
internal val name: DerAdapter<Pair<DerAdapter<*>, Any?>> = Adapters.choice(
rdnSequence
)
/**
* ```
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
* ```
*/
internal val subjectPublicKeyInfo: BasicDerAdapter<SubjectPublicKeyInfo> = Adapters.sequence(
"SubjectPublicKeyInfo",
algorithmIdentifier,
Adapters.BIT_STRING,
decompose = {
listOf(
it.algorithm,
it.subjectPublicKey
)
},
construct = {
SubjectPublicKeyInfo(
algorithm = it[0] as AlgorithmIdentifier,
subjectPublicKey = it[1] as BitString
)
}
)
/**
* ```
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version MUST be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, -- If present, version MUST be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL -- If present, version MUST be v3
* }
* ```
*/
internal val tbsCertificate: BasicDerAdapter<TbsCertificate> = Adapters.sequence(
"TBSCertificate",
Adapters.INTEGER_AS_LONG.withExplicitBox(tag = 0L).optional(defaultValue = 0), // v1 == 0
Adapters.INTEGER_AS_BIG_INTEGER,
algorithmIdentifier,
name,
validity,
name,
subjectPublicKeyInfo,
Adapters.BIT_STRING.withTag(tag = 1L).optional(),
Adapters.BIT_STRING.withTag(tag = 2L).optional(),
extension.asSequenceOf().withExplicitBox(tag = 3).optional(defaultValue = listOf()),
decompose = {
listOf(
it.version,
it.serialNumber,
it.signature,
rdnSequence to it.issuer,
it.validity,
rdnSequence to it.subject,
it.subjectPublicKeyInfo,
it.issuerUniqueID,
it.subjectUniqueID,
it.extensions
)
},
construct = {
TbsCertificate(
version = it[0] as Long,
serialNumber = it[1] as BigInteger,
signature = it[2] as AlgorithmIdentifier,
issuer = (it[3] as Pair<*, *>).second as List<List<AttributeTypeAndValue>>,
validity = it[4] as Validity,
subject = (it[5] as Pair<*, *>).second as List<List<AttributeTypeAndValue>>,
subjectPublicKeyInfo = it[6] as SubjectPublicKeyInfo,
issuerUniqueID = it[7] as BitString?,
subjectUniqueID = it[8] as BitString?,
extensions = it[9] as List<Extension>
)
}
)
/**
* ```
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
* }
* ```
*/
internal val certificate: BasicDerAdapter<Certificate> = Adapters.sequence(
"Certificate",
tbsCertificate,
algorithmIdentifier,
Adapters.BIT_STRING,
decompose = {
listOf(
it.tbsCertificate,
it.signatureAlgorithm,
it.signatureValue
)
},
construct = {
Certificate(
tbsCertificate = it[0] as TbsCertificate,
signatureAlgorithm = it[1] as AlgorithmIdentifier,
signatureValue = it[2] as BitString
)
}
)
/**
* ```
* Version ::= INTEGER { v1(0), v2(1) } (v1, ..., v2)
*
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
*
* PrivateKey ::= OCTET STRING
*
* OneAsymmetricKey ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] Attributes OPTIONAL,
* ...,
* [[2: publicKey [1] PublicKey OPTIONAL ]],
* ...
* }
*
* PrivateKeyInfo ::= OneAsymmetricKey
* ```
*/
internal val privateKeyInfo: BasicDerAdapter<PrivateKeyInfo> = Adapters.sequence(
"PrivateKeyInfo",
Adapters.INTEGER_AS_LONG,
algorithmIdentifier,
Adapters.OCTET_STRING,
decompose = {
listOf(
it.version,
it.algorithmIdentifier,
it.privateKey
)
},
construct = {
PrivateKeyInfo(
version = it[0] as Long,
algorithmIdentifier = it[1] as AlgorithmIdentifier,
privateKey = it[2] as ByteString
)
}
)
}
| apache-2.0 | e27826ae9995766d46b437f17276bcd0 | 28.701944 | 103 | 0.585297 | 4.25495 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/views/TitleWithLogo.kt | 1 | 1128 | package com.bravelocation.yeltzlandnew.views
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.bravelocation.yeltzlandnew.R
@Composable
fun TitleWithLogo(title: String? = null) {
Row(horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Image(
painterResource(R.drawable.htfc_logo_large),
contentDescription = "Yeltz Logo",
modifier = Modifier
.size(40.dp)
)
title?.let {
Text(text = it, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 8.dp))
}
}
} | mit | 7d0764f08ae67419f4c53b0b5eae76bd | 35.419355 | 123 | 0.75 | 4.389105 | false | false | false | false |
songzhw/AndroidArchitecture | deprecated/HSM_Demo/app/src/main/java/ca/six/archi/demo/hsm/MainActivity.kt | 1 | 1806 | package ca.six.archi.demo.hsm
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var parents: Array<IState> = arrayOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
object UserState {
var state = LoggedOut
}
interface IState {
val parents: ArrayList<IState>
get() = arrayListOf()
}
object LoggedOut : IState
object LoggedIn : IState
// = = = = = = = = = = =
object RegularUser: IState
object VipUser: IState
object AbnormalUser : IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn)
}
object InsecureUser : IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, AbnormalUser)
}
object LockedUser : IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, AbnormalUser)
}
// = = = = = = = = = = =
object DepositUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn)
}
object InvestUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn)
}
object DepositRegularUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, DepositUser, RegularUser)
}
object DepositVipUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, DepositUser, VipUser)
}
object InvestRegularUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, InvestUser, RegularUser)
}
object InvestVipUser: IState {
override val parents: ArrayList<IState>
get() = arrayListOf(LoggedIn, InvestUser, VipUser)
} | apache-2.0 | 77c60b013ed44f217dd12e4f5fce2fbd | 22.166667 | 63 | 0.69103 | 3.943231 | false | false | false | false |
MarKco/Catchit | catchit/src/main/java/com/ilsecondodasinistra/catchit/Bus.kt | 1 | 3121 | package com.ilsecondodasinistra.catchit
import java.io.Serializable
import java.text.SimpleDateFormat
import java.util.Date
import android.graphics.Color
import android.os.Parcel
import android.os.Parcelable
class Bus(var departure: Date?, lineNumber: String, var departureStop: String?, var arrivalStop: String?, var arrival: Date?) : Serializable {
var line: String = ""
var color: Int = 0
var textColor: Int = 0
var toBePutLast: Boolean = false
private val dateFormatter = SimpleDateFormat("H:mm")
private val dateFormatterForComparison = SimpleDateFormat("kk:mm")
init {
this.line = lineNumber
this.textColor = Color.BLACK
this.toBePutLast = false
resetColors()
}
fun resetColors() {
// if(this.lineNumber.equals("12"))
// {
// //Rosso più scuro
// this.busColor = Color.argb(40, 178, 34, 34);
// }
//
// if(this.lineNumber.equals("12/"))
// {
// //Rosso
// this.busColor = Color.argb(30, 255, 20, 147);
// }
//
// if(this.lineNumber.equals("12L"))
// {
// //Rosso meno intenso
// this.busColor = Color.argb(40, 255, 69, 0);
// }
//
// if(this.lineNumber.equals("SCORZE'"))
// {
// //Azzurrino
// this.busColor = Color.argb(50, 185, 211, 238);
// }
//
// if(this.lineNumber.equals("NOALE"))
// {
// //Giallino
// this.busColor = Color.argb(30, 255, 255, 0);
// }
if (this.line == "T1") {
//Azzurrino
this.color = Color.argb(100, 204, 255, 255)
}
if (this.line == "N1") {
//azzurrino
this.color = Color.parseColor("#33518aff")
}
if (this.line == "N2") {
//Giallino
this.color = Color.argb(30, 30, 255, 255)
}
this.textColor = Color.BLACK
}
fun setTextColor(a: Int, r: Int, g: Int, b: Int) {
this.textColor = Color.argb(a, r, g, b)
}
fun setColor(color: String) {
this.color = Color.parseColor(color)
}
fun setColor(a: Int, r: Int, g: Int, b: Int) {
this.color = Color.argb(a, r, g, b)
}
fun resetTextColor() {
this.textColor = Color.BLACK
}
val departureString: String
get() = dateFormatter.format(this.departure)
val arrivalString: String
get() = dateFormatter.format(this.arrival)
val departureStringForComparison: String
get() = dateFormatterForComparison.format(this.departure)
fun getLineNumber(): String {
return line
}
fun setLineNumber(lineNumber: String) {
this.line = lineNumber
}
override fun toString(): String {
return "Line: " + this.line +
" Time: " + this.departure
// " going? " + this.leaving +
// " workdays? " + this.workDays +
// " saturdays? " + this.saturdays +
// " sundays? " + this.sundays;
}
}
| gpl-3.0 | ca4c1bf4e0ee975b9b284739ed20f9db | 25.440678 | 142 | 0.533013 | 3.537415 | false | false | false | false |
StephaneBg/ScoreItProject | ui/src/main/java/com/sbgapps/scoreit/ui/utils/CoroutinesUtils.kt | 1 | 3064 | /*
* Copyright 2018 Stéphane Baiget
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sbgapps.scoreit.ui.utils
import kotlinx.coroutines.experimental.CancellationException
import kotlinx.coroutines.experimental.CoroutineScope
interface CoroutinesUtils {
companion object {
suspend fun CoroutineScope.tryCatch(
tryBlock: suspend CoroutineScope.() -> Unit,
catchBlock: suspend CoroutineScope.(Throwable) -> Unit,
handleCancellationExceptionManually: Boolean = false) {
try {
tryBlock()
} catch (e: Throwable) {
if (e !is CancellationException || handleCancellationExceptionManually) {
catchBlock(e)
} else {
throw e
}
}
}
suspend fun CoroutineScope.tryCatchFinally(
tryBlock: suspend CoroutineScope.() -> Unit,
catchBlock: suspend CoroutineScope.(Throwable) -> Unit,
finallyBlock: suspend CoroutineScope.() -> Unit,
handleCancellationExceptionManually: Boolean = false) {
var caughtThrowable: Throwable? = null
try {
tryBlock()
} catch (e: Throwable) {
if (e !is CancellationException || handleCancellationExceptionManually) {
catchBlock(e)
} else {
caughtThrowable = e
}
} finally {
if (caughtThrowable is CancellationException && !handleCancellationExceptionManually) {
throw caughtThrowable
} else {
finallyBlock()
}
}
}
suspend fun CoroutineScope.tryFinally(
tryBlock: suspend CoroutineScope.() -> Unit,
finallyBlock: suspend CoroutineScope.() -> Unit,
suppressCancellationException: Boolean = false) {
var caughtThrowable: Throwable? = null
try {
tryBlock()
} catch (e: CancellationException) {
if (!suppressCancellationException) {
caughtThrowable = e
}
} finally {
if (caughtThrowable is CancellationException && !suppressCancellationException) {
throw caughtThrowable
} else {
finallyBlock()
}
}
}
}
} | apache-2.0 | 0b4c4bc1b4331727e665efe67dcf45b7 | 34.218391 | 103 | 0.562194 | 6.005882 | false | false | false | false |
olonho/carkot | server/src/main/java/algorithm/geometry/Vector.kt | 1 | 778 | package algorithm.geometry
class Vector constructor(var x: Double, var y: Double) {
constructor(x1: Double, y1: Double, x2: Double, y2: Double) : this(x2 - x1, y2 - y1)
constructor(begin: Point, end: Point) : this(begin.x, begin.y, end.x, end.y)
fun scalarProduct(vector: Vector): Double {
return this.x * vector.x + this.y * vector.y
}
fun length(): Double {
return Math.sqrt(x * x + y * y)
}
fun angleTo(other: Vector): Angle {
val sp = scalarProduct(other)
val cos = sp / length() / other.length()
return Angle(Math.acos(cos))
}
fun inverse() {
x *= -1
y *= -1
}
fun normalize() {
val div = Math.sqrt(x * x + y * y)
x /= div
y /= div
}
}
| mit | 44639f5f85aee8135fafb0db96aae636 | 21.882353 | 88 | 0.53856 | 3.2827 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/weibo/ContentHolder.kt | 1 | 1122 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.weibo
import android.view.View
/**
* @author Drakeet Xu
*/
open class ContentHolder(val itemView: View) {
lateinit var parent: WeiboFrameBinder.FrameHolder
val absoluteAdapterPosition: Int
get() = parent.absoluteAdapterPosition
val layoutPosition: Int
get() = parent.layoutPosition
val oldPosition: Int
get() = parent.oldPosition
var isRecyclable: Boolean
get() = parent.isRecyclable
set(recyclable) = parent.setIsRecyclable(recyclable)
}
| apache-2.0 | dc06b313e98f86a96765f3663bf0a316 | 27.05 | 75 | 0.737968 | 4.155556 | false | false | false | false |
lunivore/montecarluni | src/scenarios/kotlin/com/lunivore/montecarluni/steps/ClipboardSteps.kt | 1 | 1271 | package com.lunivore.montecarluni.steps
import com.lunivore.montecarluni.glue.Scenario
import com.lunivore.montecarluni.glue.World
import com.lunivore.stirry.Stirry.Companion.findInRoot
import com.lunivore.stirry.Stirry.Companion.getClipboard
import com.lunivore.stirry.fireAndStir
import javafx.scene.control.Button
import org.junit.Assert.assertEquals
class ClipboardSteps(val world : World) : Scenario(world) {
init {
When("^I copy it to the clipboard$", {
findInRoot<Button> {
it.id == "clipboardButton"
}.value.fireAndStir()
})
When("^I copy rows (\\d+) onwards to the clipboard$", {fromRow : Int ->
SelectionSteps(world).select(fromRow)
findInRoot<Button> {
it.id == "clipboardButton"
}.value.fireAndStir()
})
Then("^pasting it elsewhere should result in$", {expectedDistributionAsOneLine : String ->
val text = getClipboard(javafx.scene.input.DataFormat.PLAIN_TEXT)
val expectedDistribution = expectedDistributionAsOneLine.split(',')
.map { it.trim()}
.joinToString(separator = "\n")
assertEquals(expectedDistribution, text)
});
}
}
| apache-2.0 | c6918570e9c0af71d361380cb1694dc7 | 33.351351 | 98 | 0.637293 | 4.265101 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/steuer/UStIdNr.kt | 1 | 4665 | /*
* Copyright (c) 2017-2019 by Oliver Boehm
*
* 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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 24.03.2017 by oboehm ([email protected])
*/
package de.jfachwert.steuer
import de.jfachwert.PruefzifferVerfahren
import de.jfachwert.Text
import de.jfachwert.pruefung.LengthValidator
import de.jfachwert.pruefung.Mod11Verfahren
import de.jfachwert.pruefung.NoopVerfahren
import de.jfachwert.pruefung.exception.InvalidValueException
import org.apache.commons.lang3.StringUtils
import java.util.*
import java.util.function.Function
/**
* Die Umsatzsteuer-Identifikationsnummer (USt-IdNr) ist eine eindeutige
* Kennzeichnung eines Unternehmens innerhalb der Europaeischen Union im
* umsatzsteuerlichen Sinne.
*
* @author oboehm
* @since 0.1.0
*/
open class UStIdNr
/**
* Dieser Konstruktor ist hauptsaechlich fuer abgeleitete Klassen gedacht,
* damit diese das [PruefzifferVerfahren] ueberschreiben koennen.
* Man kann es auch verwenden, um das PruefzifferVerfahren abzuschalten,
* indem man das [de.jfachwert.pruefung.NoopVerfahren] verwendet.
*
* @param nr die Umsatzsteuer-IdNr.
* @param pzVerfahren das verwendete PruefzifferVerfahren
*/
constructor(nr: String, pzVerfahren: PruefzifferVerfahren<String> = selectPruefzifferVerfahrenFor(nr)) : Text(verify(nr, pzVerfahren)) {
/**
* Liefert das Land, zu dem die IBAN gehoert.
*
* @return z.B. "DE" (als Locale)
*/
val land: Locale
get() = Locale(toLaenderkuerzel(this.code))
/**
* Erzeugt eine Umsatzsteuer-IdNr. Die uebergebene Nummer besteht aus
* einer 2-stelligen Laenderkennung, gefolgt von maximal 12
* alphanumerischen Zeichen.
*
* @param nr, z.B. "DE999999999"
*/
constructor(nr: String): this(nr, selectPruefzifferVerfahrenFor(nr))
companion object {
private val PRUEFZIFFER_VERFAHREN = HashMap<String, PruefzifferVerfahren<String>>()
private val WEAK_CACHE = WeakHashMap<String, UStIdNr>()
init {
PRUEFZIFFER_VERFAHREN["DE"] = Mod11Verfahren(8)
}
/**
* Erzeugt eine Umsatzsteuer-IdNr. Die uebergebene Nummer besteht aus
* einer 2-stelligen Laenderkennung, gefolgt von maximal 12
* alphanumerischen Zeichen.
*
* @param nr, z.B. "DE999999999"
* @return UstIdNr
*/
@JvmStatic
fun of(nr: String): UStIdNr {
return WEAK_CACHE.computeIfAbsent(nr, Function(::UStIdNr))
}
private fun selectPruefzifferVerfahrenFor(nr: String): PruefzifferVerfahren<String> {
val laenderkuerzel = toLaenderkuerzel(nr)
var verfahren: PruefzifferVerfahren<String>? = PRUEFZIFFER_VERFAHREN[laenderkuerzel]
if (verfahren == null) {
verfahren = NoopVerfahren()
}
return verfahren
}
/**
* Eine Umsatzsteuer-Id beginnt mit der Laenderkennung (2 Zeichen), gefolgt
* von maximal 12 alphanumerischen Zeichen. Bei dieser wird, je nach Land, die
* Pruefziffer validiert (falls bekannt).
*
* Die kuerzeste Umsatzsteuer kann in GB mit 5 alphanumerischen Zeichen
* auftreten.
*
* @param nr die Umsatzsteuer-Id, z.B. "DE136695970"
* @return die validierte Id zur Weiterverarbeitung
* @since 0.2.0
*/
fun validate(nr: String): String {
return selectPruefzifferVerfahrenFor(nr).validate(nr)
}
private fun verify(nr: String, verfahren: PruefzifferVerfahren<String>): String {
val unformatted = StringUtils.remove(nr, ' ')
LengthValidator.verify(unformatted, 7, 14)
verfahren.verify(unformatted.substring(2))
return unformatted
}
private fun toLaenderkuerzel(nr: String): String {
val kuerzel = nr.substring(0, 2).toUpperCase()
return if (StringUtils.isAlpha(kuerzel)) {
kuerzel
} else {
throw InvalidValueException(nr, "country")
}
}
}
}
| apache-2.0 | 43452630a7f78b49986fb914f919d504 | 34.340909 | 140 | 0.658307 | 3.650235 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/base/verses/VersesUiModel.kt | 1 | 520 | package yuku.alkitab.base.verses
data class VersesUiModel(
val textSizeMult: Float,
val verseSelectionMode: VersesController.VerseSelectionMode,
val isVerseNumberShown: Boolean,
val dictionaryModeAris: Set<Int>
) {
companion object {
@JvmField
val EMPTY = VersesUiModel(
textSizeMult = 1f,
verseSelectionMode = VersesController.VerseSelectionMode.multiple,
isVerseNumberShown = false,
dictionaryModeAris = emptySet()
)
}
}
| apache-2.0 | db0eadc7976adc3e12b65fef72995e47 | 27.888889 | 78 | 0.667308 | 4.561404 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/fx/JoinGameController.kt | 1 | 2929 | package org.pixelndice.table.pixelclient.fx
import com.google.common.eventbus.Subscribe
import javafx.application.Platform
import javafx.scene.control.TextField
import org.pixelndice.table.pixelclient.ApplicationBus
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.Button
import javafx.scene.image.ImageView
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.scene.text.Text
import org.pixelndice.table.pixelclient.PixelResourceBundle
import org.pixelndice.table.pixelclient.ds.ImageCache
import org.pixelndice.table.pixelclient.ds.RPGGameSystem
class JoinGameController {
private var handler = BusHandler()
@FXML
private lateinit var gameTagTextField: TextField
@FXML
private lateinit var refreshGameList: Button
private val refreshIcon = ImageView(ImageCache.getImage("/icons/open-iconic-master/png/reload-3x.png"))
@FXML
private lateinit var campaignListVBox: VBox
@FXML
fun initialize() {
ApplicationBus.register(handler)
refreshGameList.graphic = refreshIcon
ApplicationBus.post(ApplicationBus.CheckGame())
}
@FXML
private fun hostgameButtonOnAction(@Suppress("UNUSED_PARAMETER") event: ActionEvent) {
ApplicationBus.post(ApplicationBus.LoadHostGameView())
}
@FXML
private fun playGameTagButton(@Suppress("UNUSED_PARAMETER") event: ActionEvent) {
ApplicationBus.post(ApplicationBus.QueryGame(gameTagTextField.text))
}
@FXML
private fun refreshCampaignList(@Suppress("UNUSED_PARAMETER") event: ActionEvent){
ApplicationBus.post(ApplicationBus.CheckGame())
}
// bus handler
private inner class BusHandler{
@Suppress("unused")
@Subscribe
fun handleGameList(event: ApplicationBus.GameList){
Platform.runLater {
campaignListVBox.children.clear()
event.list.forEach {
val hbox = HBox(7.0)
hbox.padding = Insets(7.0, 7.0, 7.0, 7.0)
hbox.alignment = Pos.CENTER_LEFT
val campaignNameText = Text("${it.campaign} - ${RPGGameSystem.fromProtobuf(it.rpgGameSystem)} - ${it.gm.name}")
val playIcon = ImageView(ImageCache.getImage("/icons/open-iconic-master/png/play-circle-3x.png"))
val playButton = Button(PixelResourceBundle.getString("key.play"), playIcon)
playButton.setOnAction { _ ->
ApplicationBus.post(ApplicationBus.ConnectToLobbyServer(it.hostname, it.port))
}
hbox.children.addAll(playButton, campaignNameText)
campaignListVBox.children.add(hbox)
campaignListVBox.isFillWidth = true
}
}
}
}
}
| bsd-2-clause | 845141bd8dba25e0c051a9ed93fe25f9 | 29.195876 | 131 | 0.673609 | 4.562305 | false | false | false | false |
Ribesg/anko | dsl/testData/robolectric/SimpleTest.kt | 1 | 1540 | package test
import android.app.*
import android.content.Context
import android.widget.*
import android.os.Bundle
import org.jetbrains.anko.*
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.*
import org.junit.Test
import org.junit.Assert.*
public open class TestActivity() : Activity() {
public var ctxProperty: Context? = null
public var actProperty: Activity? = null
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
ctxProperty = ctx
actProperty = act
verticalLayout {
val text = textView("Some text") {
id = 1
}
button {
id = 2
onClick { text.text = "New text" }
}
}
}
}
@RunWith(RobolectricTestRunner::class)
public class RobolectricTest() {
@Test
public fun test() {
val activity = Robolectric.buildActivity(TestActivity::class.java).create().get()
val textView = activity.findViewById(1) as TextView
val button = activity.findViewById(2) as Button
assertNotNull(activity.ctxProperty)
assertNotNull(activity.actProperty)
assertEquals(activity.ctxProperty, activity)
assertEquals(activity.actProperty, activity)
assertEquals("Some text", textView.getText().toString())
button.performClick()
assertEquals("New text", textView.getText().toString())
println("[COMPLETE]")
}
} | apache-2.0 | 82e583caeb7ba20317680a897be11ecd | 25.568966 | 89 | 0.648701 | 4.767802 | false | true | false | false |
rmnn/compiler | src/main/kotlin/ru/dageev/compiler/parser/visitor/CompilationUnitVisitor.kt | 1 | 3859 | package ru.dageev.compiler.parser.visitor
import org.antlr.v4.runtime.misc.NotNull
import ru.dageev.compiler.domain.ClassesContext
import ru.dageev.compiler.domain.CompilationUnit
import ru.dageev.compiler.domain.declaration.ClassDeclaration
import ru.dageev.compiler.domain.declaration.MethodDeclaration
import ru.dageev.compiler.domain.node.statement.Block
import ru.dageev.compiler.domain.scope.MethodSignature
import ru.dageev.compiler.domain.scope.Scope
import ru.dageev.compiler.domain.type.ClassType
import ru.dageev.compiler.grammar.ElaginBaseVisitor
import ru.dageev.compiler.grammar.ElaginParser
import ru.dageev.compiler.parser.helper.getDefaultConstructor
import ru.dageev.compiler.parser.helper.getMainMethodSignature
import ru.dageev.compiler.parser.provider.TypeProvider
/**
* Created by dageev
* on 15-May-16.
*/
class CompilationUnitVisitor : ElaginBaseVisitor<CompilationUnit>() {
override fun visitCompilationUnit(@NotNull ctx: ElaginParser.CompilationUnitContext): CompilationUnit {
val classesContext = ClassesContext()
val typeProvider = createTypeProvider(ctx.classDeclaration())
val classVisitor = ClassVisitor(typeProvider, classesContext)
val classDeclarationContext = ctx.classDeclaration()
val classes = classDeclarationContext.map { classDeclaration ->
val classDecl = classDeclaration.accept(classVisitor)
classesContext.addClass(classDecl)
classDecl
}.toMutableList()
val classDeclaration = processMethodWithoutClass(typeProvider, classesContext, ctx)
return CompilationUnit(classes, classDeclaration)
}
fun processMethodWithoutClass(typeProvider: TypeProvider, classesContext: ClassesContext, ctx: ElaginParser.CompilationUnitContext): ClassDeclaration {
val scope = Scope("ElaginProgram", null)
val methods = getMethods(classesContext, ctx, scope, typeProvider)
val classDeclaration = ClassDeclaration("ElaginProgram", emptyList(), methods, listOf(getDefaultConstructor(scope)))
return checkAndPatchForMainMethodMainClass(scope, classesContext, classDeclaration)
}
private fun getMethods(classesContext: ClassesContext, ctx: ElaginParser.CompilationUnitContext, scope: Scope, typeProvider: TypeProvider): List<MethodDeclaration> {
return if (ctx.methodDeclaration() != null) {
ctx.methodDeclaration().map { method -> method.accept(MethodSignatureVisitor(scope, typeProvider, classesContext)) }.forEach {
scope.addSignature(it)
}
ctx.methodDeclaration().map { method -> method.accept(MethodVisitor(scope, typeProvider, classesContext)) }
} else {
emptyList()
}
}
private fun checkAndPatchForMainMethodMainClass(scope: Scope, classesContext: ClassesContext, classDeclaration: ClassDeclaration): ClassDeclaration {
val mainMethodSignature = getMainMethodSignature()
val mainMethodExists = classesContext.toScope(classDeclaration).signatureExists(mainMethodSignature)
return if (!mainMethodExists) {
addStubMainMethod(mainMethodSignature, scope, classDeclaration)
} else {
classDeclaration
}
}
private fun addStubMainMethod(mainMethodSignature: MethodSignature, scope: Scope, classDecl: ClassDeclaration): ClassDeclaration {
val methods = classDecl.methods + MethodDeclaration(mainMethodSignature, Block(scope, emptyList()))
return ClassDeclaration(classDecl.name, classDecl.fields, methods, classDecl.constructors, classDecl.parentClassDeclaration)
}
private fun createTypeProvider(classDeclarationContext: List<ElaginParser.ClassDeclarationContext>): TypeProvider {
return TypeProvider(classDeclarationContext.map { ClassType(it.identifier().text) })
}
}
| apache-2.0 | 1327069fdaee0381d0df96add97bd8ef | 47.848101 | 169 | 0.757968 | 5.097754 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/FaceAndColorDetectImageView.kt | 1 | 3875 | package org.wikipedia.views
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.util.AttributeSet
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import androidx.palette.graphics.Palette
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import org.wikipedia.settings.Prefs
import org.wikipedia.util.CenterCropWithFaceTransformation
import org.wikipedia.util.WhiteBackgroundTransformation
import java.util.*
class FaceAndColorDetectImageView constructor(context: Context, attrs: AttributeSet? = null) : AppCompatImageView(context, attrs) {
interface OnImageLoadListener {
fun onImageLoaded(palette: Palette, bmpWidth: Int, bmpHeight: Int)
fun onImageFailed()
}
private fun shouldDetectFace(uri: Uri): Boolean {
// TODO: not perfect; should ideally detect based on MIME type.
val path = uri.path.orEmpty().lowercase(Locale.ROOT)
return path.endsWith(".jpg") || path.endsWith(".jpeg")
}
fun loadImage(uri: Uri?, roundedCorners: Boolean = false, cropped: Boolean = true, emptyPlaceholder: Boolean = false, listener: OnImageLoadListener? = null) {
val placeholder = ViewUtil.getPlaceholderDrawable(context)
if (!Prefs.isImageDownloadEnabled || uri == null) {
setImageDrawable(placeholder)
return
}
var builder = Glide.with(this)
.load(uri)
.placeholder(if (emptyPlaceholder) null else placeholder)
.error(placeholder)
.downsample(DownsampleStrategy.CENTER_INSIDE)
if (listener != null) {
builder = builder.listener(object : RequestListener<Drawable?> {
override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Drawable?>, isFirstResource: Boolean): Boolean {
listener.onImageFailed()
return false
}
override fun onResourceReady(resource: Drawable?, model: Any, target: Target<Drawable?>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
if (resource is BitmapDrawable && resource.bitmap != null) {
listener.onImageLoaded(Palette.from(resource.bitmap).generate(), resource.bitmap.width, resource.bitmap.height)
} else {
listener.onImageFailed()
}
return false
}
})
}
builder = if (cropped) {
if (shouldDetectFace(uri)) {
builder.transform(if (roundedCorners) FACE_DETECT_TRANSFORM_AND_ROUNDED_CORNERS else FACE_DETECT_TRANSFORM)
} else {
builder.transform(if (roundedCorners) ViewUtil.CENTER_CROP_LARGE_ROUNDED_CORNERS else CENTER_CROP_WHITE_BACKGROUND)
}
} else {
builder.transform(WhiteBackgroundTransformation())
}
builder.into(this)
}
fun loadImage(@DrawableRes id: Int) {
setImageResource(id)
}
companion object {
private val FACE_DETECT_TRANSFORM = CenterCropWithFaceTransformation()
private val FACE_DETECT_TRANSFORM_AND_ROUNDED_CORNERS = MultiTransformation(FACE_DETECT_TRANSFORM, ViewUtil.ROUNDED_CORNERS)
private val CENTER_CROP_WHITE_BACKGROUND = MultiTransformation(CenterCrop(), WhiteBackgroundTransformation())
}
}
| apache-2.0 | 56133eda65afb1341d3c3ef3ff6b8b24 | 44.05814 | 165 | 0.680516 | 4.84375 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/dataclient/watch/Watch.kt | 1 | 423 | package org.wikipedia.dataclient.watch
import kotlinx.serialization.Serializable
import org.wikipedia.dataclient.mwapi.MwResponse
@Serializable
class Watch(val title: String?,
val ns: Int = 0,
val pageid: Int = 0,
val expiry: String? = null,
val watched: Boolean = false,
val unwatched: Boolean = false,
val missing: Boolean = false) : MwResponse()
| apache-2.0 | caf36cb5259de8cf1d007146ce9058eb | 31.538462 | 56 | 0.638298 | 4.360825 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/PostalCodeConfig.kt | 1 | 3555 | package com.stripe.android.ui.core.elements
import androidx.annotation.StringRes
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.VisualTransformation
import com.stripe.android.ui.core.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlin.math.max
internal class PostalCodeConfig(
@StringRes override val label: Int,
override val capitalization: KeyboardCapitalization = KeyboardCapitalization.Words,
override val keyboard: KeyboardType = KeyboardType.Text,
override val trailingIcon: MutableStateFlow<TextFieldIcon?> = MutableStateFlow(null),
private val country: String
) : TextFieldConfig {
private val format = CountryPostalFormat.forCountry(country)
override val debugLabel: String = "postal_code_text"
override val visualTransformation: VisualTransformation =
PostalCodeVisualTransformation(format)
override val loading: MutableStateFlow<Boolean> = MutableStateFlow(false)
override fun determineState(input: String): TextFieldState = object : TextFieldState {
override fun shouldShowError(hasFocus: Boolean) = getError() != null && !hasFocus
override fun isValid(): Boolean {
return when (format) {
is CountryPostalFormat.Other -> input.isNotBlank()
else -> {
input.length in format.minimumLength..format.maximumLength &&
input.matches(format.regexPattern)
}
}
}
override fun getError(): FieldError? {
return when {
input.isNotBlank() && !isValid() && country == "US" -> {
FieldError(R.string.address_zip_invalid)
}
input.isNotBlank() && !isValid() -> {
FieldError(R.string.address_zip_postal_invalid)
}
else -> null
}
}
override fun isFull(): Boolean = input.length >= format.maximumLength
override fun isBlank(): Boolean = input.isBlank()
}
override fun filter(userTyped: String): String =
if (
setOf(KeyboardType.Number, KeyboardType.NumberPassword).contains(keyboard)
) {
userTyped.filter { it.isDigit() }
} else {
userTyped
}.dropLast(max(0, userTyped.length - format.maximumLength))
override fun convertToRaw(displayName: String) = displayName
override fun convertFromRaw(rawValue: String) =
rawValue.replace(Regex("\\s+"), "")
sealed class CountryPostalFormat(
val minimumLength: Int,
val maximumLength: Int,
val regexPattern: Regex
) {
object CA : CountryPostalFormat(
minimumLength = 6,
maximumLength = 6,
regexPattern = Regex("[a-zA-Z]\\d[a-zA-Z][\\s-]?\\d[a-zA-Z]\\d")
)
object US : CountryPostalFormat(
minimumLength = 5,
maximumLength = 5,
regexPattern = Regex("\\d+")
)
object Other : CountryPostalFormat(
minimumLength = 1,
maximumLength = Int.MAX_VALUE,
regexPattern = Regex(".*")
)
companion object {
fun forCountry(country: String): CountryPostalFormat {
return when (country) {
"US" -> US
"CA" -> CA
else -> Other
}
}
}
}
}
| mit | a855404e4a5f134f3b308360bec79f06 | 33.852941 | 90 | 0.599437 | 4.869863 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/PostalCodeVisualTransformation.kt | 1 | 1451 | package com.stripe.android.ui.core.elements
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
internal class PostalCodeVisualTransformation(
val format: PostalCodeConfig.CountryPostalFormat
) : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return when (format) {
is PostalCodeConfig.CountryPostalFormat.CA -> postalForCanada(text)
else -> TransformedText(text, OffsetMapping.Identity)
}
}
private fun postalForCanada(text: AnnotatedString): TransformedText {
var out = ""
for (i in text.text.indices) {
out += text.text[i].uppercaseChar()
if (i == 2) out += " "
}
val postalCodeOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 2) return offset
if (offset <= 5) return offset + 1
return 7
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= 3) return offset
if (offset <= 6) return offset - 1
return 6
}
}
return TransformedText(AnnotatedString(out), postalCodeOffsetTranslator)
}
}
| mit | 2c4612b70b38055fb3f28178536bacb4 | 32.744186 | 80 | 0.632667 | 4.852843 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/camera/utils/ImageDimensions.kt | 2 | 427 | package abi44_0_0.expo.modules.camera.utils
data class ImageDimensions @JvmOverloads constructor(private val mWidth: Int, private val mHeight: Int, val rotation: Int = 0, val facing: Int = -1) {
private val isLandscape: Boolean
get() = rotation % 180 == 90
val width: Int
get() = if (isLandscape) {
mHeight
} else mWidth
val height: Int
get() = if (isLandscape) {
mWidth
} else mHeight
}
| bsd-3-clause | 6bcf285f8d03ca5f6366703537adedee | 29.5 | 150 | 0.662763 | 3.8125 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.