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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
envoyproxy/envoy-mobile | test/kotlin/io/envoyproxy/envoymobile/RetryPolicyMapperTest.kt | 2 | 4000 | package io.envoyproxy.envoymobile
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class RetryPolicyMapperTest {
@Test
fun `converting to headers with per retry timeout includes all headers`() {
val retryPolicy = RetryPolicy(
maxRetryCount = 3,
retryOn = listOf(
RetryRule.STATUS_5XX,
RetryRule.GATEWAY_ERROR,
RetryRule.CONNECT_FAILURE,
RetryRule.REFUSED_STREAM,
RetryRule.RETRIABLE_4XX,
RetryRule.RETRIABLE_HEADERS,
RetryRule.RESET
),
retryStatusCodes = listOf(400, 422, 500),
perRetryTimeoutMS = 15000,
totalUpstreamTimeoutMS = 60000
)
assertThat(retryPolicy.outboundHeaders()).isEqualTo(
mapOf(
"x-envoy-max-retries" to listOf("3"),
"x-envoy-retriable-status-codes" to listOf("400", "422", "500"),
"x-envoy-retry-on" to listOf(
"5xx", "gateway-error", "connect-failure", "refused-stream", "retriable-4xx",
"retriable-headers", "reset", "retriable-status-codes"
),
"x-envoy-upstream-rq-per-try-timeout-ms" to listOf("15000"),
"x-envoy-upstream-rq-timeout-ms" to listOf("60000")
)
)
}
@Test
fun `converting from header values delimited with comma yields individual enum values`() {
val retryPolicy = RetryPolicy(
maxRetryCount = 3,
retryOn = listOf(
RetryRule.STATUS_5XX,
RetryRule.GATEWAY_ERROR
),
retryStatusCodes = listOf(400, 422, 500),
perRetryTimeoutMS = 15000,
totalUpstreamTimeoutMS = 60000
)
val headers = RequestHeadersBuilder(
method = RequestMethod.POST, scheme = "https",
authority = "envoyproxy.io", path = "/mock"
)
.add("x-envoy-max-retries", "3")
.add("x-envoy-retriable-status-codes", "400,422,500")
.add("x-envoy-retry-on", "5xx,gateway-error")
.add("x-envoy-upstream-rq-per-try-timeout-ms", "15000")
.add("x-envoy-upstream-rq-timeout-ms", "60000")
.build()
val retryPolicyFromHeaders = RetryPolicy.from(headers)!!
assertThat(retryPolicy).isEqualTo(retryPolicyFromHeaders)
}
@Test
fun `converting to headers without retry timeout excludes per retry timeout header`() {
val retryPolicy = RetryPolicy(
maxRetryCount = 123,
retryOn = listOf(RetryRule.STATUS_5XX, RetryRule.GATEWAY_ERROR)
)
assertThat(retryPolicy.outboundHeaders())
.doesNotContainKey("x-envoy-upstream-rq-per-try-timeout-ms")
}
@Test
fun `converting to headers without upstream timeout includes zero for timeout header`() {
val retryPolicy = RetryPolicy(
maxRetryCount = 123,
retryOn = listOf(RetryRule.STATUS_5XX),
totalUpstreamTimeoutMS = null
)
assertThat(retryPolicy.outboundHeaders()).isEqualTo(
mapOf(
"x-envoy-max-retries" to listOf("123"),
"x-envoy-retry-on" to listOf("5xx"),
"x-envoy-upstream-rq-timeout-ms" to listOf("0")
)
)
}
@Test(expected = IllegalArgumentException::class)
fun `throws error when per-retry timeout is larger than total timeout`() {
RetryPolicy(
maxRetryCount = 3,
retryOn = listOf(RetryRule.STATUS_5XX),
perRetryTimeoutMS = 2,
totalUpstreamTimeoutMS = 1
)
}
@Test
fun `converting headers without retry status code does not set retriable status code headers`() {
val retryPolicy = RetryPolicy(
maxRetryCount = 123,
retryOn = listOf(
RetryRule.STATUS_5XX,
RetryRule.GATEWAY_ERROR,
RetryRule.CONNECT_FAILURE,
RetryRule.REFUSED_STREAM,
RetryRule.RETRIABLE_4XX,
RetryRule.RETRIABLE_HEADERS,
RetryRule.RESET
),
retryStatusCodes = emptyList(),
totalUpstreamTimeoutMS = null
)
val headers = retryPolicy.outboundHeaders()
assertThat(headers["x-envoy-retriable-status-codes"]).isNull()
assertThat(headers["x-envoy-retry-on"]).doesNotContain("retriable-status-codes")
}
}
| apache-2.0 | 071bf9a1bf8f3414101e480d4b9bb458 | 30.496063 | 99 | 0.6535 | 4.016064 | false | true | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/ToolWindowTabRenameActionBase.kt | 1 | 3881 | // 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.ide.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowContextMenuActionBase
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.openapi.wm.impl.content.BaseLabel
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBLabel
import com.intellij.ui.content.Content
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.SwingHelper
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Point
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.Box
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
private const val OUTLINE_PROPERTY = "JComponent.outline"
private const val ERROR_VALUE = "error"
open class ToolWindowTabRenameActionBase(val toolWindowId: String, val labelText: String) : ToolWindowContextMenuActionBase() {
override fun update(e: AnActionEvent, toolWindow: ToolWindow, selectedContent: Content?) {
val id = (toolWindow as ToolWindowImpl).id
e.presentation.isEnabledAndVisible = e.project != null && id == toolWindowId && selectedContent != null
}
override fun actionPerformed(e: AnActionEvent, toolWindow: ToolWindow, content: Content?) {
val baseLabel = e.getData(PlatformDataKeys.CONTEXT_COMPONENT) as? BaseLabel
val contextContent = baseLabel?.content ?: return
showContentRenamePopup(baseLabel, contextContent)
}
private fun showContentRenamePopup(baseLabel: BaseLabel, content: Content) {
val textField = JTextField(content.displayName)
textField.selectAll()
val label = JBLabel(labelText)
label.font = UIUtil.getLabelFont().deriveFont(Font.BOLD)
val panel = SwingHelper.newLeftAlignedVerticalPanel(label, Box.createVerticalStrut(JBUI.scale(2)), textField)
panel.addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
IdeFocusManager.findInstance().requestFocus(textField, false)
}
})
val balloon = JBPopupFactory.getInstance().createDialogBalloonBuilder(panel, null)
.setShowCallout(true)
.setCloseButtonEnabled(false)
.setAnimationCycle(0)
.setDisposable(content)
.setHideOnKeyOutside(true)
.setHideOnClickOutside(true)
.setRequestFocus(true)
.setBlockClicksThroughBalloon(true)
.createBalloon()
textField.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
if (e != null && e.keyCode == KeyEvent.VK_ENTER) {
if (!Disposer.isDisposed(content)) {
if (textField.text.isEmpty()) {
textField.putClientProperty(OUTLINE_PROPERTY, ERROR_VALUE)
textField.repaint()
return
}
content.displayName = textField.text
}
balloon.hide()
}
}
})
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
val outlineValue = textField.getClientProperty(OUTLINE_PROPERTY)
if (outlineValue == ERROR_VALUE) {
textField.putClientProperty(OUTLINE_PROPERTY, null)
textField.repaint()
}
}
})
balloon.show(RelativePoint(baseLabel, Point(baseLabel.width / 2, 0)), Balloon.Position.above)
}
} | apache-2.0 | d8732d9372c40d7713b44a2298ffa660 | 37.82 | 140 | 0.738469 | 4.425314 | false | false | false | false |
zdary/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyUnresolvedModuleAttributeCompletionContributor.kt | 1 | 9418 | package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Key
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.QualifiedName
import com.intellij.util.ProcessingContext
import com.intellij.util.Processor
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.imports.AddImportHelper
import com.jetbrains.python.inspections.unresolvedReference.PyPackageAliasesProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.resolve.QualifiedNameFinder
import com.jetbrains.python.psi.search.PySearchUtilBase
import com.jetbrains.python.psi.stubs.PyModuleNameIndex
import com.jetbrains.python.psi.stubs.PyQualifiedNameCompletionMatcher
import com.jetbrains.python.psi.stubs.PyQualifiedNameCompletionMatcher.QualifiedNameMatcher
import com.jetbrains.python.psi.types.PyModuleType
class PyUnresolvedModuleAttributeCompletionContributor : CompletionContributor() {
private companion object {
val UNRESOLVED_FIRST_COMPONENT = object : PatternCondition<PyReferenceExpression>("unresolved first component") {
override fun accepts(expression: PyReferenceExpression, context: ProcessingContext): Boolean {
val qualifier = context.get(REFERENCE_QUALIFIER)
val qualifiersFirstComponent = qualifier.firstComponent ?: return false
val scopeOwner = ScopeUtil.getScopeOwner(expression) ?: return false
return PyResolveUtil.resolveLocally(scopeOwner, qualifiersFirstComponent).isEmpty()
}
}
val QUALIFIED_REFERENCE_EXPRESSION = psiElement(PyTokenTypes.IDENTIFIER).withParent(
psiElement(PyReferenceExpression::class.java)
.andNot(psiElement().inside(PyImportStatementBase::class.java))
.with(object : PatternCondition<PyReferenceExpression>("plain qualified name") {
override fun accepts(expression: PyReferenceExpression, context: ProcessingContext): Boolean {
if (!expression.isQualified) return false
val qualifiedName = expression.asQualifiedName() ?: return false
context.put(REFERENCE_QUALIFIER, qualifiedName.removeLastComponent())
return true
}
})
.with(UNRESOLVED_FIRST_COMPONENT)
)
val REFERENCE_QUALIFIER: Key<QualifiedName> = Key.create("QUALIFIER")
private val functionInsertHandler: InsertHandler<LookupElement> = object : PyFunctionInsertHandler() {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val tailOffset = context.tailOffset - 1
super.handleInsert(context, item) // adds parentheses, modifies tail offset
context.commitDocument()
addImportForLookupElement(context, item, tailOffset)
}
}
private val importingInsertHandler: InsertHandler<LookupElement> = InsertHandler { context, item ->
addImportForLookupElement(context, item, context.tailOffset - 1)
}
private fun addImportForLookupElement(context: InsertionContext, item: LookupElement, tailOffset: Int) {
val manager = PsiDocumentManager.getInstance(context.project)
val document = manager.getDocument(context.file)
if (document != null) {
manager.commitDocument(document)
}
val ref = context.file.findReferenceAt(tailOffset)
WriteCommandAction.writeCommandAction(context.project, context.file).run<RuntimeException> {
val psiElement = item.psiElement
if (psiElement is PsiNamedElement && psiElement.containingFile != null) {
val name = QualifiedName.fromDottedString(item.lookupString).removeLastComponent().toString()
val commonAlias = PyPackageAliasesProvider.commonImportAliases[name]
val nameToImport = commonAlias ?: name
AddImportHelper.addImportStatement(context.file, nameToImport, if (commonAlias != null) name else null,
AddImportHelper.getImportPriority(context.file, psiElement.containingFile),
ref?.element as? PyElement)
}
}
}
private fun getInsertHandler(elementToInsert: PyElement, position: PsiElement): InsertHandler<LookupElement> {
return if (elementToInsert is PyFunction && position.parent?.parent !is PyDecorator) functionInsertHandler
else importingInsertHandler
}
}
init {
extend(CompletionType.BASIC, QUALIFIED_REFERENCE_EXPRESSION, object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val originalReferenceExpr = parameters.originalPosition?.parent as? PyReferenceExpression
// It cannot be checked in the pattern, because the default placeholder splits the reference, e.g. "foo.ba<caret>IntellijIdeaRulezzz z".
val isOtherReferenceQualifier = originalReferenceExpr?.parent is PyReferenceExpression
if (isOtherReferenceQualifier) return
val project = parameters.position.project
val attribute = result.prefixMatcher.prefix
val qualifier = context.get(REFERENCE_QUALIFIER)
val suggestedQualifiedNames = HashSet<String>()
ProgressManager.checkCanceled()
val qualifiedName = qualifier.append(attribute)
val packageNameForAlias = PyPackageAliasesProvider.commonImportAliases[qualifier.toString()]
val packageName = if (packageNameForAlias != null) QualifiedName.fromDottedString(packageNameForAlias) else qualifier
val resultMatchingCompleteReference = result.withPrefixMatcher(QualifiedNameMatcher(qualifiedName))
val availableModules = PyModuleNameIndex.findByQualifiedName(packageName, project,
PySearchUtilBase.defaultSuggestionScope(parameters.originalFile))
.asSequence()
if (packageNameForAlias == null) {
availableModules.filter { PyUtil.isPackage(it) }
.flatMap { PyModuleType.getSubModuleVariants(it.containingDirectory, it, null) }
.filterNot { it.lookupString.startsWith('_') }
.mapNotNull {
val qualifiedNameToSuggest = "$qualifier.${it.lookupString}"
if (suggestedQualifiedNames.add(qualifiedNameToSuggest)) {
object : LookupElementDecorator<LookupElement>(it) {
override fun getLookupString(): String = qualifiedNameToSuggest
override fun getAllLookupStrings(): MutableSet<String> = mutableSetOf(lookupString)
}
}
else null
}
.forEach { resultMatchingCompleteReference.addElement(it) }
}
availableModules.flatMap { it.iterateNames() }
.filter { it.containingFile != null }
.filterNot { it is PsiFileSystemItem }
.filterNot { it.name == null || it.name!!.startsWith('_') }
.filter { attribute.isEmpty() || resultMatchingCompleteReference.prefixMatcher.prefixMatches("$packageName.${it.name}") }
.mapNotNull {
val qualifiedNameToSuggest = "$qualifier.${it.name}"
if (suggestedQualifiedNames.add(qualifiedNameToSuggest)) {
LookupElementBuilder.create(it, qualifiedNameToSuggest)
.withIcon(it.getIcon(0))
.withInsertHandler(getInsertHandler(it, parameters.position))
.withTypeText(packageNameForAlias)
}
else null
}
.forEach { resultMatchingCompleteReference.addElement(it) }
if (attribute.isEmpty()) {
result.restartCompletionOnAnyPrefixChange()
return
}
val scope = PySearchUtilBase.defaultSuggestionScope(parameters.originalFile)
PyQualifiedNameCompletionMatcher.processMatchingExportedNames(
packageName.append(attribute), if (packageNameForAlias != null) qualifiedName else null, parameters.originalFile, scope,
Processor {
ProgressManager.checkCanceled()
if (suggestedQualifiedNames.add(it.qualifiedName.toString())) {
resultMatchingCompleteReference.addElement(LookupElementBuilder
.createWithSmartPointer(it.qualifiedNameWithUserTypedAlias.toString(),
it.element)
.withIcon(it.element.getIcon(0))
.withInsertHandler(getInsertHandler(it.element, parameters.position)))
}
return@Processor true
})
}
})
}
} | apache-2.0 | 9665e34160ccab7f2c9b195075cd5393 | 51.620112 | 144 | 0.701635 | 5.510825 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt | 1 | 7132 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.ide.util.TreeChooser
import com.intellij.ide.util.gotoByName.GotoSymbolModel2
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.ui.TextAccessor
import com.intellij.util.ProcessingContext
import com.intellij.util.TextFieldCompletionProvider
import com.intellij.util.textCompletion.TextFieldWithCompletion
import com.jetbrains.extensions.getQName
import com.jetbrains.extensions.python.toPsi
import com.jetbrains.extensions.ContextAnchor
import com.jetbrains.extensions.QNameResolveContext
import com.jetbrains.extensions.resolveToElement
import com.jetbrains.python.PyGotoSymbolContributor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyTreeChooserDialog
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.stubs.PyClassNameIndex
import com.jetbrains.python.psi.stubs.PyFunctionNameIndex
import com.jetbrains.python.psi.types.PyModuleType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
/**
* Python module is file or package with init.py.
* Only source based packages are supported.
* [PySymbolFieldWithBrowseButton] use this function to get list of root names
*/
fun isPythonModule(element: PsiElement): Boolean = element is PyFile || (element as? PsiDirectory)?.let {
it.findFile(PyNames.INIT_DOT_PY) != null
} ?: false
/**
* Text field to enter python symbols and browse button (from [PyGotoSymbolContributor]).
* Supports auto-completion for symbol fully qualified names inside of textbox
* @param filter lambda to filter symbols
* @param startFromDirectory symbols resolved against module, but may additionally be resolved against this folder if provided like in [QNameResolveContext.folderToStart]
*
*/
class PySymbolFieldWithBrowseButton(contextAnchor: ContextAnchor,
filter: ((PsiElement) -> Boolean)? = null,
startFromDirectory: (() -> VirtualFile)? = null) : TextAccessor, ComponentWithBrowseButton<TextFieldWithCompletion>(
TextFieldWithCompletion(contextAnchor.project, PyNameCompletionProvider(contextAnchor, filter, startFromDirectory), "", true, true, true),
null) {
init {
addActionListener {
val dialog = PySymbolChooserDialog(contextAnchor.project, contextAnchor.scope, filter)
dialog.showDialog()
val element = dialog.selected
if (element is PyQualifiedNameOwner) {
childComponent.setText(element.qualifiedName)
}
if (element is PyFile) {
childComponent.setText(element.getQName()?.toString())
}
}
}
override fun setText(text: String?) {
childComponent.setText(text)
}
override fun getText(): String = childComponent.text
}
private fun PyType.getVariants(element: PsiElement): Array<LookupElement> =
this.getCompletionVariants("", element, ProcessingContext()).filterIsInstance(LookupElement::class.java).toTypedArray()
private class PyNameCompletionProvider(private val contextAnchor: ContextAnchor,
private val filter: ((PsiElement) -> Boolean)?,
private val startFromDirectory: (() -> VirtualFile)? = null) : TextFieldCompletionProvider() {
override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) {
val lookups: Array<LookupElement>
var name: QualifiedName? = null
if ('.' !in text) {
lookups = contextAnchor.getRoots()
.map { rootFolder -> rootFolder.children.map { it.toPsi(contextAnchor.project) } }
.flatten()
.filterNotNull()
.filter { isPythonModule(it) }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
.distinctBy { it.lookupString }
.toTypedArray()
}
else {
val evalContext = TypeEvalContext.userInitiated(contextAnchor.project, null)
name = QualifiedName.fromDottedString(text)
val resolveContext = QNameResolveContext(contextAnchor, evalContext = evalContext, allowInaccurateResult = false,
folderToStart = startFromDirectory?.invoke())
var element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
if (element == null && name.componentCount > 1) {
name = name.removeLastComponent()
element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
}
if (element == null) {
return
}
lookups = when (element) {
is PyFile -> PyModuleType(element).getVariants(element)
is PsiDirectory -> {
val init = PyUtil.turnDirIntoInit(element) as? PyFile ?: return
PyModuleType(init).getVariants(element) +
element.children.filterIsInstance(PsiFileSystemItem::class.java)
// For package we need all symbols in initpy and all filesystem children of this folder except initpy itself
.filterNot { it.name == PyNames.INIT_DOT_PY }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
}
is PyTypedElement -> {
evalContext.getType(element)?.getVariants(element) ?: return
}
else -> return
}
}
result.addAllElements(lookups
.filter { it.psiElement != null }
.filter { filter?.invoke(it.psiElement!!) ?: true }
.map { if (name != null) LookupElementBuilder.create("$name.${it.lookupString}") else it })
}
}
private class PySymbolChooserDialog(project: Project, scope: GlobalSearchScope, private val filter: ((PsiElement) -> Boolean)?)
: PyTreeChooserDialog<PsiNamedElement>("Choose Symbol", PsiNamedElement::class.java,
project,
scope,
TreeChooser.Filter { filter?.invoke(it) ?: true }, null) {
override fun findElements(name: String, searchScope: GlobalSearchScope): Collection<PsiNamedElement> {
return PyClassNameIndex.find(name, project, searchScope) + PyFunctionNameIndex.find(name, project, searchScope)
}
override fun createChooseByNameModel() = GotoSymbolModel2(project, arrayOf(PyGotoSymbolContributor()))
}
| apache-2.0 | 599b0f87468b4f91f23d591cfa85bb16 | 45.921053 | 170 | 0.713545 | 4.922015 | false | false | false | false |
walkingice/MomoDict | app/src/main/java/org/zeroxlab/momodict/reader/Reader.kt | 1 | 3402 | package org.zeroxlab.momodict.reader
import androidx.room.Room
import android.content.Context
import org.zeroxlab.momodict.archive.FileSet
import org.zeroxlab.momodict.db.room.RoomStore
import org.zeroxlab.momodict.model.Book
import org.zeroxlab.momodict.model.Entry
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.util.ArrayList
/**
* A class to extract compressed file, to read and to save into Database.
*/
class Reader
/**
* Constructor
*
* @param mCacheDir A string as path of cache directory. Extracted files will be placed
* here.
* @param mFilePath A string as path of a compressed file which will be parsed.
*/
(private val mCacheDir: String, private val mFilePath: String) {
/**
* To read file and save into database.
*
* @param ctx Context instance
*/
fun parse(ctx: Context) {
// extract file
val cachedir = File(mCacheDir)
val outputDir = makeTempDir(cachedir)
var archive: FileSet? = null
try {
val fis = FileInputStream(File(mFilePath))
archive = readBzip2File(outputDir, fis)
// FIXME: should avoid main thread
val store = Room.databaseBuilder(
ctx.applicationContext,
RoomStore::class.java,
RoomStore.DB_NAME
)
.allowMainThreadQueries()
.build()
val ifoFile = File(archive!![FileSet.Type.IFO]!!)
val idxFile = File(archive[FileSet.Type.IDX]!!)
// To read ifo file
val `is` = FileInputStream(ifoFile)
val info = readIfo(`is`)
`is`.close()
if (!isSanity(info)) {
throw RuntimeException("Insanity .ifo file")
}
// To read idx file
if (idxFile == null || !idxFile.exists()) {
throw RuntimeException("Should give an existing idx file")
}
val idxIs = FileInputStream(idxFile)
val idx = parseIdx(idxIs)
idxIs.close()
// To save ifo to database
// TODO: remove !!
val dict = Book(info.bookName!!)
dict.author = info.author
dict.wordCount = info.wordCount
dict.date = info.date
store.addBook(dict)
// To save each words to database
if (idx.size() != 0) {
val dictPath = archive[FileSet.Type.DICT]
val isDict = dictPath!!.endsWith(".dz")
val ips = FileInputStream(dictPath)
val bis = BufferedInputStream(ips)
val dictIs = wrapInputStream(isDict, bis)
val words = parseDict(idx.entries, dictIs)
val entries = ArrayList<Entry>()
for (word in words) {
if (word.entry != null) {
val entry = Entry(word.entry!!.wordStr)
entry.source = info.bookName
entry.data = word.data
entries.add(entry)
}
}
store.addEntries(entries)
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (archive != null) {
archive.clean()
}
}
}
}
| mit | 75f694d98fad7ab99f035ceae64deb58 | 32.352941 | 87 | 0.542916 | 4.641201 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/rts/route/trip/RTSTripStopsViewModel.kt | 1 | 5312 | package org.mtransit.android.ui.rts.route.trip
import androidx.core.content.edit
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.liveData
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import org.mtransit.android.common.repository.LocalPreferenceRepository
import org.mtransit.android.commons.MTLog
import org.mtransit.android.commons.SqlUtils
import org.mtransit.android.commons.pref.liveData
import org.mtransit.android.commons.provider.GTFSProviderContract
import org.mtransit.android.commons.provider.POIProviderContract
import org.mtransit.android.data.POIManager
import org.mtransit.android.datasource.POIRepository
import org.mtransit.android.dev.DemoModeManager
import org.mtransit.android.ui.view.common.PairMediatorLiveData
import org.mtransit.android.ui.view.common.TripleMediatorLiveData
import org.mtransit.android.ui.view.common.getLiveDataDistinct
import javax.inject.Inject
@HiltViewModel
class RTSTripStopsViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val poiRepository: POIRepository,
private val lclPrefRepository: LocalPreferenceRepository,
private val demoModeManager: DemoModeManager,
) : ViewModel(), MTLog.Loggable {
companion object {
private val LOG_TAG = RTSTripStopsViewModel::class.java.simpleName
internal const val EXTRA_AGENCY_AUTHORITY = "extra_agency_authority"
internal const val EXTRA_ROUTE_ID = "extra_route_id"
internal const val EXTRA_TRIP_ID = "extra_trip_id"
internal const val EXTRA_SELECTED_STOP_ID = "extra_trip_stop_id"
internal const val EXTRA_SELECTED_STOP_ID_DEFAULT: Int = -1
internal const val EXTRA_CLOSEST_POI_SHOWN = "extra_closest_poi_shown"
internal const val EXTRA_CLOSEST_POI_SHOWN_DEFAULT: Boolean = false
}
override fun getLogTag(): String = tripId.value?.let { "${LOG_TAG}-$it" } ?: LOG_TAG
val agencyAuthority = savedStateHandle.getLiveDataDistinct<String?>(EXTRA_AGENCY_AUTHORITY)
private val _routeId = savedStateHandle.getLiveDataDistinct<Long?>(EXTRA_ROUTE_ID)
val tripId = savedStateHandle.getLiveDataDistinct<Long?>(EXTRA_TRIP_ID)
val selectedTripStopId = savedStateHandle.getLiveDataDistinct(EXTRA_SELECTED_STOP_ID, EXTRA_SELECTED_STOP_ID_DEFAULT)
.map { if (it < 0) null else it }
val closestPOIShown = savedStateHandle.getLiveDataDistinct(EXTRA_CLOSEST_POI_SHOWN, EXTRA_CLOSEST_POI_SHOWN_DEFAULT)
fun setSelectedOrClosestStopShown() {
savedStateHandle[EXTRA_SELECTED_STOP_ID] = EXTRA_SELECTED_STOP_ID_DEFAULT
savedStateHandle[EXTRA_CLOSEST_POI_SHOWN] = true
}
val poiList: LiveData<List<POIManager>?> = PairMediatorLiveData(agencyAuthority, tripId).switchMap { (agencyAuthority, tripId) ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emit(getPOIList(agencyAuthority, tripId))
}
}
private fun getPOIList(agencyAuthority: String?, tripId: Long?): List<POIManager>? {
if (agencyAuthority == null || tripId == null) {
return null
}
val poiFilter = POIProviderContract.Filter.getNewSqlSelectionFilter(
SqlUtils.getWhereEquals(
GTFSProviderContract.RouteTripStopColumns.T_TRIP_K_ID, tripId
)
).apply {
addExtra(
POIProviderContract.POI_FILTER_EXTRA_SORT_ORDER,
SqlUtils.getSortOrderAscending(GTFSProviderContract.RouteTripStopColumns.T_TRIP_STOPS_K_STOP_SEQUENCE)
)
}
return this.poiRepository.findPOIMs(
agencyAuthority,
poiFilter
)
}
val showingListInsteadOfMap: LiveData<Boolean> = TripleMediatorLiveData(agencyAuthority, _routeId, tripId).switchMap { (authority, routeId, tripId) ->
liveData {
if (authority == null || routeId == null || tripId == null) {
return@liveData // SKIP
}
if (demoModeManager.enabled) {
emit(false) // show map (demo mode ON)
return@liveData
}
emitSource(
lclPrefRepository.pref.liveData(
LocalPreferenceRepository.getPREFS_LCL_RTS_ROUTE_TRIP_ID_KEY(authority, routeId, tripId),
LocalPreferenceRepository.PREFS_LCL_RTS_TRIP_SHOWING_LIST_INSTEAD_OF_MAP_DEFAULT
)
)
}
}.distinctUntilChanged()
fun saveShowingListInsteadOfMap(showingListInsteadOfMap: Boolean) {
if (demoModeManager.enabled) {
return // SKIP (demo mode ON)
}
lclPrefRepository.pref.edit {
val authority = agencyAuthority.value ?: return
val routeId = _routeId.value ?: return
val tripId = tripId.value ?: return
putBoolean(
LocalPreferenceRepository.getPREFS_LCL_RTS_ROUTE_TRIP_ID_KEY(authority, routeId, tripId),
showingListInsteadOfMap
)
}
}
} | apache-2.0 | 8650973d6ab001f1f946740dd4a19c6e | 40.834646 | 154 | 0.70256 | 4.400994 | false | false | false | false |
leafclick/intellij-community | platform/platform-util-io/src/org/jetbrains/io/IdeaNettyLogger.kt | 1 | 2418 | // 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.io
import com.intellij.openapi.diagnostic.Logger
import io.netty.util.internal.logging.AbstractInternalLogger
internal class IdeaNettyLogger : AbstractInternalLogger("netty") {
private fun getLogger() = Logger.getInstance("netty")
override fun isInfoEnabled() = false
override fun info(msg: String?) {
}
override fun info(format: String?, arg: Any?) {
}
override fun info(format: String?, argA: Any?, argB: Any?) {
}
override fun info(format: String?, vararg arguments: Any?) {
}
override fun info(msg: String?, t: Throwable?) {
}
override fun isWarnEnabled() = true
override fun warn(msg: String?) {
getLogger().warn(msg)
}
override fun warn(format: String?, arg: Any?) {
getLogger().warn("$format $arg")
}
override fun warn(format: String?, vararg arguments: Any?) {
getLogger().warn("$format $arguments")
}
override fun warn(format: String?, argA: Any?, argB: Any?) {
getLogger().warn("$format $argA $argB")
}
override fun warn(msg: String?, t: Throwable?) {
getLogger().warn(msg, t)
}
override fun isErrorEnabled() = true
override fun error(msg: String?) {
getLogger().error(msg)
}
override fun error(format: String?, arg: Any?) {
getLogger().error("$format $arg")
}
override fun error(format: String?, argA: Any?, argB: Any?) {
getLogger().error("$format $argA $argB")
}
override fun error(format: String?, vararg arguments: Any?) {
getLogger().error("$format $arguments")
}
override fun error(msg: String?, t: Throwable?) {
getLogger().error(msg, t)
}
override fun isDebugEnabled() = false
override fun debug(msg: String?) {
}
override fun debug(format: String?, arg: Any?) {
}
override fun debug(format: String?, argA: Any?, argB: Any?) {
}
override fun debug(format: String?, vararg arguments: Any?) {
}
override fun debug(msg: String?, t: Throwable?) {
}
override fun isTraceEnabled() = false
override fun trace(msg: String?) {
}
override fun trace(format: String?, arg: Any?) {
}
override fun trace(format: String?, argA: Any?, argB: Any?) {
}
override fun trace(format: String?, vararg arguments: Any?) {
}
override fun trace(msg: String?, t: Throwable?) {
}
} | apache-2.0 | c7796e0ac9a9c564505d11ef230ced51 | 22.259615 | 140 | 0.657568 | 3.754658 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/closures/localReturnWithAutolabel.kt | 5 | 440 | fun box(): String {
val a = 1
val explicitlyReturned = run1 {
if (a > 0)
return@run1 "OK"
else "Fail 1"
}
if (explicitlyReturned != "OK") return explicitlyReturned
val implicitlyReturned = run1 {
if (a < 0)
return@run1 "Fail 2"
else "OK"
}
if (implicitlyReturned != "OK") return implicitlyReturned
return "OK"
}
fun <T> run1(f: () -> T): T { return f() } | apache-2.0 | 370150aae440fa5d27bd6e845aeafd63 | 22.210526 | 61 | 0.534091 | 3.52 | false | false | false | false |
LUSHDigital/android-lush-views | sample/src/main/java/com/lush/views/sample/TextSampleActivity.kt | 1 | 2283 | package com.lush.views.sample
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lush.views.sample.base.BaseSampleActivity
import kotlinx.android.synthetic.main.activity_text.*
/**
* <Class Description>
*
* @author Jamie Cruwys
*/
class TextSampleActivity : BaseSampleActivity() {
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_text)
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
container.adapter = mSectionsPagerAdapter
container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
}
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
if (position == 1) {
return WhiteTextFragment.newInstance()
}
return BlackTextFragment.newInstance()
}
override fun getCount(): Int {
return 2
}
}
class BlackTextFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_text_black, container, false)
}
companion object {
fun newInstance(): BlackTextFragment {
return BlackTextFragment()
}
}
}
class WhiteTextFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_text_white, container, false)
}
companion object {
fun newInstance(): WhiteTextFragment {
return WhiteTextFragment()
}
}
}
} | apache-2.0 | ca4145d288a80a5e2cc711eee358416f | 32.101449 | 120 | 0.688568 | 5.212329 | false | false | false | false |
PeterVollmer/feel-at-home-android-client | Feel@Home/Feel@Home/src/main/java/club/frickel/feelathome/SendActiveHandler.kt | 1 | 2593 | package club.frickel.feelathome
import android.content.Context
import android.os.AsyncTask
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Toast
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.util.*
/**
* Created by nino on 08.07.17.
*/
class SendActiveHandler(internal var active: Boolean, internal var deviceID: String, internal var context: Context) : AsyncTask<Void, Void, String>() {
override fun doInBackground(vararg params: Void): String {
var errorMessage: String = ""
if (deviceID != null) {
var urlString = PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.SERVER_URL, null)
if (urlString != null) {
urlString += "/devices/$deviceID/active"
}
val url: URL
try {
url = URL(urlString)
} catch (e: MalformedURLException) {
errorMessage = "Malformed URL: " + urlString!!
return errorMessage
}
val urlConnection: HttpURLConnection
try {
urlConnection = url.openConnection() as HttpURLConnection
urlConnection.doOutput = true
urlConnection.requestMethod = "PUT"
val mapper = ObjectMapper()
val activeObject = HashMap<String, Any>()
activeObject.put("Active", active)
mapper.writeValue(urlConnection.outputStream, activeObject)
val responce = urlConnection.responseCode
if (responce != 200) {
errorMessage = "Received ErrorCode: " + responce.toString()
Log.d(SEND_ERROR, "Received $responce Error while sending")
}
} catch (e: IOException) {
errorMessage = "Server doesn\\'t exist or isn\\'t availible!"
return errorMessage
}
} else {
errorMessage = "deviceID was null"
}
return errorMessage
}
override fun onPostExecute(errorMessage: String) {
if (!errorMessage.isEmpty()) {
Log.d("Send Error", "State Error" + errorMessage)
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
}
//showSendErrorDialog(active, deviceID, context, errorMessage);
}
companion object {
val SEND_ERROR = "Send Error"
}
}
| gpl-2.0 | 25d64412b5b4caf961aac834db0cebcd | 32.675325 | 151 | 0.604705 | 5.074364 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/dsl/builder/ButtonTest.kt | 1 | 1107 | // 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.dsl.builder
import com.intellij.ui.layout.*
import org.junit.Test
import kotlin.random.Random
import kotlin.test.assertEquals
class ButtonTest {
var property = true
@Test
fun testBindingInitialization() {
property = Random.Default.nextBoolean()
panel {
row {
val checkBox = checkBox("")
.bindSelected(::property)
assertEquals(checkBox.component.isSelected, property)
}
}
var localProperty = Random.Default.nextBoolean()
panel {
row {
val checkBox = checkBox("")
.bindSelected({ localProperty }, { localProperty = it })
assertEquals(checkBox.component.isSelected, localProperty)
}
}
panel {
row {
val checkBox = checkBox("")
.bindSelected(PropertyBinding({ localProperty }, { localProperty = it }))
assertEquals(checkBox.component.isSelected, localProperty)
}
}
}
} | apache-2.0 | c6eed87139123882ebdde6809193a4e7 | 26.02439 | 158 | 0.658537 | 4.57438 | false | true | false | false |
smmribeiro/intellij-community | platform/rd-platform-community/src/com/intellij/openapi/rd/SourceEx.kt | 9 | 1016 | // 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.openapi.rd
import com.jetbrains.rd.framework.base.RdReactiveBase
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.ISource
enum class RdEventSource {
Local,
Remote,
Initial
}
/**
* Advise for protocol entities to get information who initiates events
*/
fun <T> ISource<T>.advise(lifetime: Lifetime, handler: (T, RdEventSource) -> Unit) {
val rdSource = this as? RdReactiveBase
if (rdSource == null) throw UnsupportedOperationException("$this should inherit RdReactiveBase in order to use this advice function.")
var initialChange = true
advise(lifetime) {
val eventSource = when {
initialChange -> RdEventSource.Initial
rdSource.isLocalChange -> RdEventSource.Local
else -> RdEventSource.Remote
}
handler(it, eventSource)
}
initialChange = false
} | apache-2.0 | 6fbed567327b4c0431647bfb5e4b015b | 31.806452 | 158 | 0.747047 | 4.031746 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/asJava/ultraLightClasses/annotations.kt | 7 | 2241 | import kotlin.reflect.KClass
@Target(*[AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION])
annotation class Anno2()
@Target(allowedTargets = [AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION])
annotation class Anno3()
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
annotation class Anno4()
@Target(*arrayOf(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION))
annotation class Anno5()
@Target(allowedTargets = arrayOf(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION))
annotation class Anno6()
annotation class AnnoWithCompanion() {
companion object {
fun foo() {}
@JvmField
val x: Int = 42
}
}
annotation class Anno(val p: String = "", val x: Array<Anno> = arrayOf(Anno(p = "a"), Anno(p = "b")))
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,
AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
@Deprecated("This anno is deprecated, use === instead", ReplaceWith("this === other"))
annotation class Fancy
annotation class ReplaceWith(val expression: String)
annotation class AnnotatedAttribute(@get:Anno val x: String)
annotation class Deprecated(
val message: String,
val replaceWith: ReplaceWith = ReplaceWith(""))
annotation class Ann(val arg1: KClass<*>, val arg2: KClass<out Any>)
@Anno class F: Runnable {
@Anno("f") fun f(@Anno p: String) {}
@Anno("p") var prop = "x"
}
class Foo @Anno constructor(dependency: MyDependency) {
var x: String? = null
@Anno set
@Anno
fun String.f4() {}
}
@Ann(String::class, Int::class) class MyClass
class Example(@field:Ann val foo: String, // annotate Java field
@get:Ann val bar: String, // annotate Java getter
@param:Ann val quux: String) // annotate Java constructor parameter
class CtorAnnotations(@Anno val x: String, @param:Anno val y: String, val z: String) | apache-2.0 | 2424908faebae28cb530bdf519714c45 | 33.492308 | 147 | 0.740295 | 4.293103 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/leguicomp/PixelBorder.kt | 1 | 1731 | package com.cout970.modeler.gui.leguicomp
import com.cout970.modeler.core.config.colorOf
import org.joml.Vector2f
import org.joml.Vector4f
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.style.Border
import org.liquidengine.legui.system.context.Context
import org.liquidengine.legui.system.renderer.nvg.NvgBorderRenderer
import org.liquidengine.legui.system.renderer.nvg.util.NvgShapes
/**
* Created by cout970 on 2017/08/29.
*/
class PixelBorder : Border() {
var color: Vector4f = colorOf("FFF")
var enableTop = false
var enableBottom = false
var enableLeft = false
var enableRight = false
object PixelBorderRenderer : NvgBorderRenderer<PixelBorder>() {
override fun renderBorder(border: PixelBorder, comp: Component, context: Context, nanovg: Long) {
if (border.enableTop) {
NvgShapes.drawRect(nanovg, comp.absolutePosition, Vector2f(comp.size.x, 1f), border.color)
}
if (border.enableBottom) {
NvgShapes.drawRect(nanovg,
Vector2f(comp.absolutePosition.x, comp.absolutePosition.y + comp.size.y - 1),
Vector2f(comp.size.x, 1f),
border.color)
}
if (border.enableLeft) {
NvgShapes.drawRect(nanovg, comp.absolutePosition, Vector2f(1f, comp.size.y), border.color)
}
if (border.enableRight) {
NvgShapes.drawRect(nanovg,
Vector2f(comp.absolutePosition.x + comp.size.x - 1, comp.absolutePosition.y),
Vector2f(1f, comp.size.y),
border.color)
}
}
}
} | gpl-3.0 | 800a6e31fdf6d8a63452fe684763d86e | 35.083333 | 106 | 0.626805 | 3.934091 | false | false | false | false |
kivensolo/UiUsingListView | database/src/main/java/com/kingz/database/dao/SongDao.kt | 1 | 613 | package com.kingz.database.dao
import androidx.room.*
import com.kingz.database.entity.BaseEntity
import com.kingz.database.entity.SongEntity
@Dao
interface SongDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(data: BaseEntity)
@Delete
fun delete(data: BaseEntity)
@Query("SELECT * FROM SongEntity WHERE name==:songName ")
fun querySongBy(songName: String): SongEntity?
@Query("SELECT * FROM SongEntity WHERE name==:songName AND singer==:singer")
fun querySongBy(songName: String, singer: String?): SongEntity?
@Update
fun update(data: SongEntity)
} | gpl-2.0 | 38d356719f3bfcf31a89513743bade08 | 24.583333 | 80 | 0.730832 | 3.904459 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/extensions/Range.kt | 1 | 226 | package com.simplemobiletools.calendar.pro.extensions
import android.util.Range
fun Range<Int>.intersects(other: Range<Int>) = (upper >= other.lower && lower <= other.upper) || (other.upper >= lower && other.lower <= upper)
| gpl-3.0 | b01103e5f5e046913f1c40e3db3bad99 | 44.2 | 143 | 0.725664 | 3.645161 | false | false | false | false |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflowHandler.kt | 1 | 12605 | // 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.vcs.commit
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.DumbService.isDumb
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.openapi.vcs.changes.actions.DefaultCommitExecutorAction
import com.intellij.openapi.vcs.checkin.*
import com.intellij.openapi.vcs.checkin.CheckinHandler.ReturnResult
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.wm.ex.ProgressIndicatorEx
import com.intellij.util.containers.nullize
import com.intellij.util.progress.DelegatingProgressIndicatorEx
import com.intellij.vcs.commit.AbstractCommitWorkflow.Companion.getCommitExecutors
import kotlinx.coroutines.*
import java.lang.Runnable
import kotlin.properties.Delegates.observable
private val LOG = logger<NonModalCommitWorkflowHandler<*, *>>()
private val isBackgroundCommitChecksValue: RegistryValue get() = Registry.get("vcs.background.commit.checks")
fun isBackgroundCommitChecks(): Boolean = isBackgroundCommitChecksValue.asBoolean()
abstract class NonModalCommitWorkflowHandler<W : NonModalCommitWorkflow, U : NonModalCommitWorkflowUi> :
AbstractCommitWorkflowHandler<W, U>(),
DumbService.DumbModeListener {
abstract override val amendCommitHandler: NonModalAmendCommitHandler
private var areCommitOptionsCreated = false
private val uiDispatcher = AppUIExecutor.onUiThread().coroutineDispatchingContext()
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
if (exception !is ProcessCanceledException) LOG.error(exception)
}
private val coroutineScope =
CoroutineScope(CoroutineName("commit workflow") + uiDispatcher + SupervisorJob() + exceptionHandler)
private var isCommitChecksResultUpToDate: Boolean by observable(false) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
updateDefaultCommitActionName()
}
protected fun setupCommitHandlersTracking() {
isBackgroundCommitChecksValue.addListener(object : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) = commitHandlersChanged()
}, this)
CheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
VcsCheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
}
private fun commitHandlersChanged() {
if (workflow.isExecuting) return
commitOptions.saveState()
disposeCommitOptions()
initCommitHandlers()
}
override fun vcsesChanged() {
initCommitHandlers()
workflow.initCommitExecutors(getCommitExecutors(project, workflow.vcses) + RunCommitChecksExecutor)
updateDefaultCommitActionEnabled()
updateDefaultCommitActionName()
ui.setCustomCommitActions(createCommitExecutorActions())
}
protected fun setupDumbModeTracking() {
if (isDumb(project)) enteredDumbMode()
project.messageBus.connect(this).subscribe(DumbService.DUMB_MODE, this)
}
override fun enteredDumbMode() {
ui.commitProgressUi.isDumbMode = true
}
override fun exitDumbMode() {
ui.commitProgressUi.isDumbMode = false
}
override fun executionStarted() = updateDefaultCommitActionEnabled()
override fun executionEnded() = updateDefaultCommitActionEnabled()
override fun updateDefaultCommitActionName() {
val commitText = getCommitActionName()
val isAmend = amendCommitHandler.isAmendCommitMode
val isSkipCommitChecks = isSkipCommitChecks()
ui.defaultCommitActionName = when {
isAmend && isSkipCommitChecks -> message("action.amend.commit.anyway.text")
isAmend && !isSkipCommitChecks -> message("amend.action.name", commitText)
!isAmend && isSkipCommitChecks -> message("action.commit.anyway.text", commitText)
else -> commitText
}
}
fun updateDefaultCommitActionEnabled() {
ui.isDefaultCommitActionEnabled = isReady()
}
protected open fun isReady() = workflow.vcses.isNotEmpty() && !workflow.isExecuting && !amendCommitHandler.isLoading
override fun isExecutorEnabled(executor: CommitExecutor): Boolean = super.isExecutorEnabled(executor) && isReady()
private fun createCommitExecutorActions(): List<AnAction> {
val executors = workflow.commitExecutors.ifEmpty { return emptyList() }
val group = ActionManager.getInstance().getAction("Vcs.CommitExecutor.Actions") as ActionGroup
return group.getChildren(null).toList() + executors.filter { it.useDefaultAction() }.map { DefaultCommitExecutorAction(it) }
}
override fun checkCommit(executor: CommitExecutor?): Boolean =
ui.commitProgressUi.run {
val executorWithoutChangesAllowed = executor?.areChangesRequired() == false
isEmptyChanges = !amendCommitHandler.isAmendWithoutChangesAllowed() && !executorWithoutChangesAllowed && isCommitEmpty()
isEmptyMessage = getCommitMessage().isBlank()
!isEmptyChanges && !isEmptyMessage
}
/**
* Subscribe to VFS and documents changes to reset commit checks results
*/
protected fun setupCommitChecksResultTracking() {
fun areFilesAffectsCommitChecksResult(files: Collection<VirtualFile>): Boolean {
val vcsManager = ProjectLevelVcsManager.getInstance(project)
val filesFromVcs = files.filter { vcsManager.getVcsFor(it) != null }.nullize() ?: return false
val changeListManager = ChangeListManager.getInstance(project)
val fileIndex = ProjectRootManagerEx.getInstanceEx(project).fileIndex
return filesFromVcs.any {
fileIndex.isInContent(it) && changeListManager.getStatus(it) != FileStatus.IGNORED
}
}
// reset commit checks on VFS updates
project.messageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: MutableList<out VFileEvent>) {
if (!isCommitChecksResultUpToDate) {
return
}
val updatedFiles = events.mapNotNull { it.file }
if (areFilesAffectsCommitChecksResult(updatedFiles)) {
resetCommitChecksResult()
}
}
})
// reset commit checks on documents modification (e.g. user typed in the editor)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!isCommitChecksResultUpToDate) {
return
}
val file = FileDocumentManager.getInstance().getFile(event.document)
if (file != null && areFilesAffectsCommitChecksResult(listOf(file))) {
resetCommitChecksResult()
}
}
}, this)
}
private fun resetCommitChecksResult() {
isCommitChecksResultUpToDate = false
}
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: ReturnResult) {
super.beforeCommitChecksEnded(isDefaultCommit, result)
if (result == ReturnResult.COMMIT) {
ui.commitProgressUi.clearCommitCheckFailures()
}
}
fun isSkipCommitChecks(): Boolean = isBackgroundCommitChecks() && isCommitChecksResultUpToDate
override fun doExecuteDefault(executor: CommitExecutor?): Boolean {
if (!isBackgroundCommitChecks()) return super.doExecuteDefault(executor)
coroutineScope.launch {
workflow.executeDefault {
val isOnlyRunCommitChecks = commitContext.isOnlyRunCommitChecks
commitContext.isOnlyRunCommitChecks = false
if (isSkipCommitChecks() && !isOnlyRunCommitChecks) return@executeDefault ReturnResult.COMMIT
val indicator = IndeterminateIndicator(ui.commitProgressUi.startProgress())
indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() {
override fun cancel() = [email protected]()
})
try {
runAllHandlers(executor, indicator, isOnlyRunCommitChecks)
}
finally {
indicator.stop()
}
}
}
return true
}
private suspend fun runAllHandlers(
executor: CommitExecutor?,
indicator: ProgressIndicator,
isOnlyRunCommitChecks: Boolean
): ReturnResult {
workflow.runMetaHandlers(indicator)
FileDocumentManager.getInstance().saveAllDocuments()
val handlersResult = workflow.runHandlers(executor)
if (handlersResult != ReturnResult.COMMIT) return handlersResult
val checksResult = runCommitChecks(indicator)
if (checksResult != ReturnResult.COMMIT || isOnlyRunCommitChecks) isCommitChecksResultUpToDate = true
return if (isOnlyRunCommitChecks) ReturnResult.CANCEL else checksResult
}
private suspend fun runCommitChecks(indicator: ProgressIndicator): ReturnResult {
var result = ReturnResult.COMMIT
for (commitCheck in commitHandlers.filterNot { it is CheckinMetaHandler }.filterIsInstance<CommitCheck<*>>()) {
val problem = runCommitCheck(commitCheck, indicator)
if (problem != null) result = ReturnResult.CANCEL
}
return result
}
private suspend fun <P : CommitProblem> runCommitCheck(commitCheck: CommitCheck<P>, indicator: ProgressIndicator): P? {
val problem = workflow.runCommitCheck(commitCheck, indicator)
problem?.let { ui.commitProgressUi.addCommitCheckFailure(it.text) { commitCheck.showDetails(it) } }
return problem
}
override fun dispose() {
coroutineScope.cancel()
super.dispose()
}
fun showCommitOptions(isFromToolbar: Boolean, dataContext: DataContext) =
ui.showCommitOptions(ensureCommitOptions(), getCommitActionName(), isFromToolbar, dataContext)
override fun saveCommitOptionsOnCommit(): Boolean {
ensureCommitOptions()
// restore state in case settings were changed via configurable
commitOptions.allOptions
.filter { it is UnnamedConfigurable }
.forEach { it.restoreState() }
return super.saveCommitOptionsOnCommit()
}
protected fun ensureCommitOptions(): CommitOptions {
if (!areCommitOptionsCreated) {
areCommitOptionsCreated = true
workflow.initCommitOptions(createCommitOptions())
commitOptions.restoreState()
commitOptionsCreated()
}
return commitOptions
}
protected open fun commitOptionsCreated() = Unit
protected fun disposeCommitOptions() {
workflow.disposeCommitOptions()
areCommitOptionsCreated = false
}
protected open inner class CommitStateCleaner : CommitResultHandler {
override fun onSuccess(commitMessage: String) = resetState()
override fun onCancel() = Unit
override fun onFailure(errors: List<VcsException>) = resetState()
protected open fun resetState() {
disposeCommitOptions()
workflow.clearCommitContext()
initCommitHandlers()
resetCommitChecksResult()
updateDefaultCommitActionName()
}
}
}
private class IndeterminateIndicator(indicator: ProgressIndicatorEx) : DelegatingProgressIndicatorEx(indicator) {
override fun setIndeterminate(indeterminate: Boolean) = Unit
override fun setFraction(fraction: Double) = Unit
}
| apache-2.0 | b3e7c84ea19d221ef30c2546b99bb4b3 | 38.024768 | 158 | 0.766997 | 5.042 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/mock/MockViewValidator.kt | 3 | 2684 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime.mock
import kotlin.test.assertEquals
import kotlin.test.assertTrue
interface MockViewValidator {
val view: View
fun next(): Boolean
}
class MockViewListValidator(private val views: List<View>) :
MockViewValidator {
override lateinit var view: View
override fun next(): Boolean {
if (iterator.hasNext()) {
view = iterator.next()
return true
}
return false
}
private val iterator by lazy { views.iterator() }
fun validate(block: (MockViewValidator.() -> Unit)?) {
if (block != null) {
this.block()
val hasNext = next()
assertEquals(false, hasNext, "Expected children but none found")
} else {
assertEquals(0, views.size, "Not expecting children but some found")
}
}
}
fun MockViewValidator.view(name: String, block: (MockViewValidator.() -> Unit)? = null) {
val hasNext = next()
assertTrue(hasNext, "Expected a $name, but none found")
assertEquals(name, view.name)
MockViewListValidator(view.children).validate(block)
}
fun <T> MockViewValidator.Repeated(of: Iterable<T>, block: MockViewValidator.(value: T) -> Unit) {
for (value in of) {
block(value)
}
}
fun MockViewValidator.Linear() = view("linear", null)
fun MockViewValidator.Linear(block: MockViewValidator.() -> Unit) = view("linear", block)
fun MockViewValidator.box(block: MockViewValidator.() -> Unit) = view("box", block)
fun MockViewValidator.Text(value: String) {
view("text")
assertEquals(value, view.attributes["text"])
}
fun MockViewValidator.Edit(value: String) {
view("edit")
assertEquals(value, view.attributes["value"])
}
fun MockViewValidator.SelectBox(selected: Boolean, block: MockViewValidator.() -> Unit) {
if (selected) {
box {
block()
}
} else {
block()
}
}
fun MockViewValidator.skip(times: Int = 1) {
repeat(times) {
val hasNext = next()
assertEquals(true, hasNext)
}
} | apache-2.0 | 5882c11b3240c3e6c2ce277214fd019d | 28.184783 | 98 | 0.658718 | 4.017964 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/extensions/PlaceholderExtensions.android.kt | 3 | 3216 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.platform.extensions
import android.text.Spannable
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.android.InternalPlatformTextApi
import androidx.compose.ui.text.android.style.PlaceholderSpan
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.util.fastForEach
internal fun Spannable.setPlaceholders(
placeholders: List<AnnotatedString.Range<Placeholder>>,
density: Density
) {
placeholders.fastForEach {
val (placeholder, start, end) = it
setPlaceholder(placeholder, start, end, density)
}
}
@OptIn(InternalPlatformTextApi::class)
private fun Spannable.setPlaceholder(
placeholder: Placeholder,
start: Int,
end: Int,
density: Density
) {
setSpan(
with(placeholder) {
PlaceholderSpan(
width = width.value,
widthUnit = width.spanUnit,
height = height.value,
heightUnit = height.spanUnit,
pxPerSp = density.fontScale * density.density,
verticalAlign = placeholderVerticalAlign.spanVerticalAlign
)
},
start,
end
)
}
/** Helper function that converts [TextUnit.type] to the unit in [PlaceholderSpan]. */
@OptIn(InternalPlatformTextApi::class)
@Suppress("DEPRECATION")
private val TextUnit.spanUnit: Int
get() = when (type) {
TextUnitType.Sp -> PlaceholderSpan.UNIT_SP
TextUnitType.Em -> PlaceholderSpan.UNIT_EM
else -> PlaceholderSpan.UNIT_UNSPECIFIED
}
/**
* Helper function that converts [PlaceholderVerticalAlign] to the verticalAlign in
* [PlaceholderSpan].
*/
@OptIn(InternalPlatformTextApi::class)
private val PlaceholderVerticalAlign.spanVerticalAlign: Int
get() = when (this) {
PlaceholderVerticalAlign.AboveBaseline -> PlaceholderSpan.ALIGN_ABOVE_BASELINE
PlaceholderVerticalAlign.Top -> PlaceholderSpan.ALIGN_TOP
PlaceholderVerticalAlign.Bottom -> PlaceholderSpan.ALIGN_BOTTOM
PlaceholderVerticalAlign.Center -> PlaceholderSpan.ALIGN_CENTER
PlaceholderVerticalAlign.TextTop -> PlaceholderSpan.ALIGN_TEXT_TOP
PlaceholderVerticalAlign.TextBottom -> PlaceholderSpan.ALIGN_TEXT_BOTTOM
PlaceholderVerticalAlign.TextCenter -> PlaceholderSpan.ALIGN_TEXT_CENTER
else -> error("Invalid PlaceholderVerticalAlign")
}
| apache-2.0 | 3df5a19538b5d1ab4d4d428c65a19b34 | 35.545455 | 86 | 0.724502 | 4.701754 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/find/impl/TextSearchContributor.kt | 2 | 9925 | // 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.find.impl
import com.intellij.find.FindBundle
import com.intellij.find.FindManager
import com.intellij.find.FindModel
import com.intellij.find.FindSettings
import com.intellij.find.impl.TextSearchRightActionAction.*
import com.intellij.ide.actions.GotoActionBase
import com.intellij.ide.actions.SearchEverywhereBaseAction
import com.intellij.ide.actions.SearchEverywhereClassifier
import com.intellij.ide.actions.searcheverywhere.*
import com.intellij.ide.actions.searcheverywhere.AbstractGotoSEContributor.createContext
import com.intellij.ide.util.RunOnceUtil
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo
import com.intellij.ide.util.scopeChooser.ScopeDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.observable.properties.AtomicBooleanProperty
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.util.ProgressIndicatorBase
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.ex.ProgressIndicatorEx
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.reference.SoftReference
import com.intellij.usages.Usage
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageInfoAdapter
import com.intellij.usages.UsageViewPresentation
import com.intellij.util.CommonProcessors
import com.intellij.util.PlatformUtils
import com.intellij.util.Processor
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.JBIterable
import java.lang.ref.Reference
import java.lang.ref.WeakReference
import javax.swing.ListCellRenderer
class TextSearchContributor(val event: AnActionEvent) : WeightedSearchEverywhereContributor<UsageInfo2UsageAdapter>,
SearchFieldActionsContributor, DumbAware, ScopeSupporting, Disposable {
private val project = event.getRequiredData(CommonDataKeys.PROJECT)
private val model = FindManager.getInstance(project).findInProjectModel
private var everywhereScope = getEverywhereScope()
private var projectScope: GlobalSearchScope?
private var selectedScopeDescriptor: ScopeDescriptor
private var psiContext = getPsiContext()
private lateinit var onDispose: () -> Unit
init {
val scopes = createScopes()
projectScope = getProjectScope(scopes)
selectedScopeDescriptor = getInitialSelectedScope(scopes)
}
private fun getPsiContext() = GotoActionBase.getPsiContext(event)?.let {
SmartPointerManager.getInstance(project).createSmartPsiElementPointer(it)
}
private fun getEverywhereScope() =
SearchEverywhereClassifier.EP_Manager.getEverywhereScope(project) ?: GlobalSearchScope.everythingScope(project)
private fun getProjectScope(descriptors: List<ScopeDescriptor>): GlobalSearchScope? {
SearchEverywhereClassifier.EP_Manager.getProjectScope(project)?.let { return it }
GlobalSearchScope.projectScope(project).takeIf { it != everywhereScope }?.let { return it }
val secondScope = JBIterable.from(descriptors).filter { !it.scopeEquals(everywhereScope) && !it.scopeEquals(null) }.first()
return if (secondScope != null) secondScope.scope as GlobalSearchScope? else everywhereScope
}
override fun getSearchProviderId() = ID
override fun getGroupName() = FindBundle.message("search.everywhere.group.name")
override fun getSortWeight() = 1500
override fun showInFindResults() = enabled()
override fun isShownInSeparateTab() = true
override fun fetchWeightedElements(pattern: String,
indicator: ProgressIndicator,
consumer: Processor<in FoundItemDescriptor<UsageInfo2UsageAdapter>>) {
FindModel.initStringToFind(model, pattern)
val presentation = FindInProjectUtil.setupProcessPresentation(project, UsageViewPresentation())
val progressIndicator = indicator as? ProgressIndicatorEx ?: ProgressIndicatorBase()
val recentUsageRef = ThreadLocal<Reference<Usage>>()
FindInProjectUtil.findUsages(model, project, progressIndicator, presentation, emptySet()) {
val usage = UsageInfo2UsageAdapter.CONVERTER.`fun`(it) as UsageInfo2UsageAdapter
progressIndicator.checkCanceled()
val recent = SoftReference.dereference(recentUsageRef.get())
val merged = (recent as? UsageInfoAdapter)?.merge(usage)
if (merged == null || !merged) {
recentUsageRef.set(WeakReference(usage))
consumer.process(FoundItemDescriptor<UsageInfo2UsageAdapter>(usage, 0))
}
true
}
}
override fun getElementsRenderer(): ListCellRenderer<in UsageInfo2UsageAdapter> = TextSearchRenderer(GlobalSearchScope.allScope(project))
override fun processSelectedItem(selected: UsageInfo2UsageAdapter, modifiers: Int, searchText: String): Boolean {
if (!selected.canNavigate()) return false
selected.navigate(true)
return true
}
override fun getActions(onChanged: Runnable): List<AnAction> =
listOf(ScopeAction { onChanged.run() }, JComboboxAction(project) { onChanged.run() }.also { onDispose = it.saveMask })
override fun createRightActions(onChanged: Runnable): List<TextSearchRightActionAction> {
lateinit var regexp: AtomicBooleanProperty
val word = AtomicBooleanProperty(model.isWholeWordsOnly).apply { afterChange { model.isWholeWordsOnly = it; if (it) regexp.set(false) } }
val case = AtomicBooleanProperty(model.isCaseSensitive).apply { afterChange { model.isCaseSensitive = it } }
regexp = AtomicBooleanProperty(model.isRegularExpressions).apply { afterChange { model.isRegularExpressions = it; if (it) word.set(false) } }
return listOf(CaseSensitiveAction(case, onChanged), WordAction(word, onChanged), RegexpAction(regexp, onChanged))
}
override fun getDataForItem(element: UsageInfo2UsageAdapter, dataId: String): UsageInfo2UsageAdapter? = null
private fun getInitialSelectedScope(scopeDescriptors: List<ScopeDescriptor>): ScopeDescriptor {
val scope = SE_TEXT_SELECTED_SCOPE.get(project) ?: return ScopeDescriptor(projectScope)
return scopeDescriptors.find { scope == it.displayName && !it.scopeEquals(null) } ?: ScopeDescriptor(projectScope)
}
private fun setSelectedScope(scope: ScopeDescriptor) {
selectedScopeDescriptor = scope
SE_TEXT_SELECTED_SCOPE.set(project, if (scope.scopeEquals(everywhereScope) || scope.scopeEquals(projectScope)) null else scope.displayName)
FindSettings.getInstance().customScope = selectedScopeDescriptor.scope?.displayName
model.customScopeName = selectedScopeDescriptor.scope?.displayName
model.customScope = selectedScopeDescriptor.scope
model.isCustomScope = true
}
private fun createScopes() = mutableListOf<ScopeDescriptor>().also {
ScopeChooserCombo.processScopes(project, createContext(project, psiContext),
ScopeChooserCombo.OPT_LIBRARIES or ScopeChooserCombo.OPT_EMPTY_SCOPES,
CommonProcessors.CollectProcessor(it))
}
override fun getScope() = selectedScopeDescriptor
override fun getSupportedScopes() = createScopes()
override fun setScope(scope: ScopeDescriptor) {
setSelectedScope(scope)
}
private inner class ScopeAction(val onChanged: () -> Unit) : ScopeChooserAction() {
override fun onScopeSelected(descriptor: ScopeDescriptor) {
setSelectedScope(descriptor)
onChanged()
}
override fun getSelectedScope() = selectedScopeDescriptor
override fun isEverywhere() = selectedScopeDescriptor.scopeEquals(everywhereScope)
override fun processScopes(processor: Processor<in ScopeDescriptor>) = ContainerUtil.process(createScopes(), processor)
override fun onProjectScopeToggled() {
isEverywhere = !selectedScopeDescriptor.scopeEquals(everywhereScope)
}
override fun setEverywhere(everywhere: Boolean) {
setSelectedScope(ScopeDescriptor(if (everywhere) everywhereScope else projectScope))
onChanged()
}
override fun canToggleEverywhere() = if (everywhereScope == projectScope) false
else selectedScopeDescriptor.scopeEquals(everywhereScope) || selectedScopeDescriptor.scopeEquals(projectScope)
}
override fun dispose() {
if (this::onDispose.isInitialized) onDispose()
}
companion object {
private const val ID = "TextSearchContributor"
private const val ADVANCED_OPTION_ID = "se.text.search"
private val SE_TEXT_SELECTED_SCOPE = Key.create<String>("SE_TEXT_SELECTED_SCOPE")
private fun enabled() = AdvancedSettings.getBoolean(ADVANCED_OPTION_ID)
class Factory : SearchEverywhereContributorFactory<UsageInfo2UsageAdapter> {
override fun isAvailable() = enabled()
override fun createContributor(event: AnActionEvent) = TextSearchContributor(event)
}
class TextSearchAction : SearchEverywhereBaseAction(), DumbAware {
override fun update(event: AnActionEvent) {
super.update(event)
event.presentation.isEnabledAndVisible = enabled()
}
override fun actionPerformed(e: AnActionEvent) {
showInSearchEverywherePopup(ID, e, true, true)
}
}
class TextSearchActivity : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
RunOnceUtil.runOnceForApp(ADVANCED_OPTION_ID) {
AdvancedSettings.setBoolean(ADVANCED_OPTION_ID, PlatformUtils.isRider())
}
}
}
}
} | apache-2.0 | 272def1425b39fd0741bb6ea914a4146 | 43.914027 | 145 | 0.770076 | 4.952595 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinByConventionCallUsage.kt | 6 | 3810 | // 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.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.intentions.RemoveEmptyParenthesesFromLambdaCallIntention
import org.jetbrains.kotlin.idea.intentions.conventionNameCalls.ReplaceInvokeIntention
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.util.OperatorNameConventions
class KotlinByConventionCallUsage(
expression: KtExpression,
private val callee: KotlinCallableDefinitionUsage<*>
) : KotlinUsageInfo<KtExpression>(expression) {
private var resolvedCall: ResolvedCall<*>? = null
private var convertedCallExpression: KtCallExpression? = null
private fun foldExpression(expression: KtDotQualifiedExpression, changeInfo: KotlinChangeInfo) {
when (changeInfo.newName) {
OperatorNameConventions.INVOKE.asString() -> {
with(ReplaceInvokeIntention()) {
if (applicabilityRange(expression) != null) {
OperatorToFunctionIntention.replaceExplicitInvokeCallWithImplicit(expression)
?.getPossiblyQualifiedCallExpression()
?.valueArgumentList
?.let {
RemoveEmptyParenthesesFromLambdaCallIntention.applyToIfApplicable(it)
}
}
}
}
OperatorNameConventions.GET.asString() -> {
with(ReplaceGetOrSetInspection()) {
if (isApplicable(expression)) {
applyTo(expression)
}
}
}
}
}
override fun getElement(): KtExpression? {
return convertedCallExpression ?: super.getElement()
}
override fun preprocessUsage() {
val element = element ?: return
val convertedExpression = OperatorToFunctionIntention.convert(element).first
val callExpression = convertedExpression.getPossiblyQualifiedCallExpression() ?: return
resolvedCall = callExpression.resolveToCall()
convertedCallExpression = callExpression
}
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtExpression, allUsages: Array<out UsageInfo>): Boolean {
val resolvedCall = resolvedCall ?: return true
val callExpression = convertedCallExpression ?: return true
val callProcessor = KotlinFunctionCallUsage(callExpression, callee, resolvedCall)
val newExpression = callProcessor.processUsageAndGetResult(
changeInfo = changeInfo,
element = callExpression,
allUsages = allUsages,
skipRedundantArgumentList = true,
) as? KtExpression
val qualifiedCall = newExpression?.getQualifiedExpressionForSelectorOrThis() as? KtDotQualifiedExpression
if (qualifiedCall != null) {
foldExpression(qualifiedCall, changeInfo)
}
return true
}
} | apache-2.0 | a8da989694672b8d6bef4831fb45e314 | 45.47561 | 158 | 0.702887 | 6.185065 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/PositionalArgumentMapping.kt | 13 | 4041 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.resolve.api.*
class PositionalArgumentMapping<out P : CallParameter>(
private val parameters: List<P>,
override val arguments: Arguments,
private val context: PsiElement
) : ArgumentMapping<P> {
private val parameterToArgument: List<Pair<P, Argument?>>? by lazy {
mapByPosition(parameters, arguments, CallParameter::isOptional, false)
}
private val argumentToParameter: Map<Argument, P>? by lazy {
parameterToArgument?.mapNotNull { (parameter, argument) ->
argument?.let {
Pair(argument, parameter)
}
}?.toMap()
}
override fun targetParameter(argument: Argument): P? = argumentToParameter?.get(argument)
override fun expectedType(argument: Argument): PsiType? = targetParameter(argument)?.type
override val expectedTypes: Iterable<Pair<PsiType, Argument>>
get() {
return (parameterToArgument ?: return emptyList()).mapNotNull { (parameter, argument) ->
val expectedType = parameter.type
if (expectedType == null || argument == null) {
null
}
else {
Pair(expectedType, argument)
}
}
}
override fun applicability(): Applicability {
val map = argumentToParameter ?: return Applicability.inapplicable
return mapApplicability(map, context)
}
val distance: Long
get() {
val map = requireNotNull(argumentToParameter) {
"#distance should not be accessed on inapplicable mapping"
}
return positionalParametersDistance(map, context)
}
override fun highlightingApplicabilities(substitutor: PsiSubstitutor): ApplicabilityResult {
val map = argumentToParameter ?: return ApplicabilityResult.Inapplicable
return ApplicabilityResultImpl(highlightApplicabilities(map, substitutor, context))
}
}
// foo(a?, b, c?, d?, e)
// foo(1, 2) => 1:b, 2:e
// foo(1, 2, 3) => 1:a, 2:b, 3:e
// foo(1, 2, 3, 4) => 1:a, 2:b, 3:c, 4:e
// foo(1, 2, 3, 4, 5) => 1:a, 2:b, 3:c, 4:d, 5:e
private fun <Arg, Param> mapByPosition(parameters: List<Param>,
arguments: List<Arg>,
isOptional: (Param) -> Boolean,
@Suppress("SameParameterValue") partial: Boolean): List<Pair<Param, Arg?>>? {
val argumentsCount = arguments.size
val parameterCount = parameters.size
val optionalParametersCount = parameters.count(isOptional)
val requiredParametersCount = parameterCount - optionalParametersCount
if (!partial && argumentsCount !in requiredParametersCount..parameterCount) {
// too little or too many arguments
return null
}
val result = ArrayList<Pair<Param, Arg?>>(parameterCount)
val argumentIterator = arguments.iterator()
var optionalArgsLeft = argumentsCount - requiredParametersCount
for (parameter in parameters) {
val optional = isOptional(parameter)
val argument = if (argumentIterator.hasNext()) {
if (!optional) {
argumentIterator.next()
}
else if (optionalArgsLeft > 0) {
optionalArgsLeft--
argumentIterator.next()
}
else {
// No argument passed for this parameter.
// Don't call next() on argument iterator, so current argument will be used for next parameter.
null
}
}
else {
require(optionalArgsLeft == 0)
require(optional || partial) {
"argumentsCount < requiredParameters. This should happen only in partial mode"
}
null
}
result += Pair(parameter, argument)
}
require(!argumentIterator.hasNext() || partial) {
"argumentsCount > parametersCount. This should happen only in partial mode."
}
return result
}
| apache-2.0 | e35a394ef19ecb143dd984a4bd22ffd9 | 34.447368 | 140 | 0.665924 | 4.445545 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleStructureWizardStep.kt | 9 | 4386 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard.getNewProjectJdk
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.wizard.MavenizedStructureWizardStep
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.layout.*
import icons.GradleIcons
import org.jetbrains.plugins.gradle.util.GradleConstants
import javax.swing.Icon
class GradleStructureWizardStep(
private val builder: AbstractGradleModuleBuilder,
context: WizardContext
) : MavenizedStructureWizardStep<ProjectData>(context) {
override fun getHelpId() = "Gradle_Archetype_Dialog"
override fun getBuilderId(): String? = builder.builderId
override fun createView(data: ProjectData) = GradleDataView(data)
override fun findAllParents(): List<ProjectData> {
val project = context.project ?: return emptyList()
return ProjectDataManager.getInstance()
.getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
.mapNotNull { it.externalProjectStructure }
.map { it.data }
}
override fun ValidationInfoBuilder.validateGroupId(): ValidationInfo? = null
override fun ValidationInfoBuilder.validateVersion(): ValidationInfo? = null
override fun ValidationInfoBuilder.validateName(): ValidationInfo? {
return validateNameAndArtifactId() ?: superValidateName()
}
override fun ValidationInfoBuilder.validateArtifactId(): ValidationInfo? {
return validateNameAndArtifactId() ?: superValidateArtifactId()
}
private fun ValidationInfoBuilder.validateNameAndArtifactId(): ValidationInfo? {
if (artifactId == entityName) return null
return error(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.and.artifact.id.is.different.error",
if (context.isCreatingNewProject) 1 else 0))
}
override fun updateProjectData() {
context.projectBuilder = builder
builder.parentProject = parentData
builder.projectId = ProjectId(groupId, artifactId, version)
builder.isInheritGroupId = parentData?.group == groupId
builder.isInheritVersion = parentData?.version == version
builder.name = entityName
builder.contentEntryPath = location
builder.moduleFilePath = getModuleFilePath()
builder.isCreatingNewProject = context.isCreatingNewProject
builder.moduleJdk = builder.moduleJdk ?: getNewProjectJdk(context)
}
private fun getModuleFilePath(): String {
val moduleFileDirectory = getModuleFileDirectory()
val moduleFilePath = FileUtil.join(moduleFileDirectory, artifactId + ModuleFileType.DOT_DEFAULT_EXTENSION)
return FileUtil.toCanonicalPath(moduleFilePath)
}
private fun getModuleFileDirectory(): String {
val projectPath = context.project?.basePath ?: location
return when (context.projectStorageFormat) {
StorageScheme.DEFAULT -> location
StorageScheme.DIRECTORY_BASED -> FileUtil.join(projectPath, Project.DIRECTORY_STORE_FOLDER, "modules")
else -> projectPath
}
}
override fun _init() {
builder.name?.let { entityName = it }
builder.projectId?.let { projectId ->
projectId.groupId?.let { groupId = it }
projectId.artifactId?.let { artifactId = it }
projectId.version?.let { version = it }
}
}
class GradleDataView(override val data: ProjectData) : DataView<ProjectData>() {
override val location: String = data.linkedExternalProjectPath
override val icon: Icon = GradleIcons.GradleFile
override val presentationName: String = data.externalName
override val groupId: String = data.group ?: ""
override val version: String = data.version ?: ""
}
} | apache-2.0 | 5bbcbd88e57b7a4711a0cb6e1a787490 | 41.182692 | 140 | 0.777702 | 4.895089 | false | false | false | false |
GlobalTechnology/android-gto-support | gto-support-leakcanary2/src/main/java/org/ccci/gto/android/common/leakcanary/timber/TimberSharkLog.kt | 2 | 772 | package org.ccci.gto.android.common.leakcanary.timber
import shark.SharkLog
import timber.log.Timber
private const val TAG = "LeakCanary"
private const val MAX_MESSAGE_LENGTH = 4000
private val REGEX_NEW_LINE = "\n".toRegex()
object TimberSharkLog : SharkLog.Logger {
override fun d(message: String) {
if (message.length >= MAX_MESSAGE_LENGTH) {
message.split(REGEX_NEW_LINE).forEach { Timber.tag(TAG).d(it) }
} else {
Timber.tag(TAG).d(message)
}
}
override fun d(throwable: Throwable, message: String) {
if (message.length >= MAX_MESSAGE_LENGTH) {
d(message)
Timber.tag(TAG).d(throwable)
} else {
Timber.tag(TAG).d(throwable, message)
}
}
}
| mit | f01158d581e05b4a654c7f249bd2d23b | 26.571429 | 75 | 0.61658 | 3.607477 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/runAnything/activity/RunAnythingCommandLineProvider.kt | 9 | 3052 | // 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.ide.actions.runAnything.activity
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.util.execution.ParametersListUtil
abstract class RunAnythingCommandLineProvider : RunAnythingNotifiableProvider<String>() {
open fun getHelpCommandAliases(): List<String> = emptyList()
abstract override fun getHelpCommand(): String
protected abstract fun suggestCompletionVariants(dataContext: DataContext, commandLine: CommandLine): Sequence<String>
protected abstract fun run(dataContext: DataContext, commandLine: CommandLine): Boolean
override fun getCommand(value: String) = value
private fun getHelpCommands() = listOf(helpCommand) + getHelpCommandAliases()
override fun findMatchingValue(dataContext: DataContext, pattern: String): String? {
val (helpCommand, _) = extractLeadingHelpPrefix(pattern) ?: return null
if (pattern.startsWith(helpCommand)) {
return getCommand(pattern)
}
return null
}
private fun extractLeadingHelpPrefix(commandLine: String): Pair<String, String>? {
for (helpCommand in getHelpCommands()) {
val prefix = "$helpCommand "
when {
commandLine.startsWith(prefix) -> return helpCommand to commandLine.removePrefix(prefix)
prefix.startsWith(commandLine) -> return helpCommand to ""
}
}
return null
}
private fun parseCommandLine(commandLine: String): CommandLine? {
val (helpCommand, command) = extractLeadingHelpPrefix(commandLine) ?: return null
val parameters = ParametersListUtil.parse(command, true, true, true)
val toComplete = parameters.lastOrNull() ?: ""
val prefix = command.removeSuffix(toComplete).trim()
val nonEmptyParameters = parameters.filter { it.isNotEmpty() }
val completedParameters = parameters.dropLast(1).filter { it.isNotEmpty() }
return CommandLine(nonEmptyParameters, completedParameters, helpCommand, command.trim(), prefix, toComplete)
}
override fun getValues(dataContext: DataContext, pattern: String): List<String> {
val commandLine = parseCommandLine(pattern) ?: return emptyList()
val variants = suggestCompletionVariants(dataContext, commandLine)
val helpCommand = commandLine.helpCommand
val prefix = commandLine.prefix.let { if (it.isEmpty()) helpCommand else "$helpCommand $it" }
return variants.map { "$prefix $it" }.toList()
}
override fun run(dataContext: DataContext, value: String): Boolean {
val commandLine = parseCommandLine(value) ?: return false
return run(dataContext, commandLine)
}
class CommandLine(
val parameters: List<String>,
val completedParameters: List<String>,
val helpCommand: String,
val command: String,
val prefix: String,
val toComplete: String
) {
private val parameterSet by lazy { completedParameters.toSet() }
operator fun contains(command: String) = command in parameterSet
}
} | apache-2.0 | a3d0733130dff85909b2411531be33ed | 40.256757 | 140 | 0.743119 | 4.76131 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/timeline/StatusItemHolder.kt | 1 | 5310 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.timeline
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.LinearLayout
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.chad.library.adapter.base.BaseViewHolder
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractActivity
import com.sinyuk.fanfou.domain.DO.Photos
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.glide.GlideRequests
import com.sinyuk.fanfou.ui.player.PlayerView
import com.sinyuk.fanfou.util.FanfouFormatter
import com.sinyuk.fanfou.util.linkfy.FanfouUtils
import com.sinyuk.myutils.ConvertUtils
import kotlinx.android.synthetic.main.status_list_item.view.*
/**
* Created by sinyuk on 2018/4/20.
┌──────────────────────────────────────────────────────────────────┐
│ │
│ _______. __ .__ __. ____ ____ __ __ __ ___ │
│ / || | | \ | | \ \ / / | | | | | |/ / │
│ | (----`| | | \| | \ \/ / | | | | | ' / │
│ \ \ | | | . ` | \_ _/ | | | | | < │
│ .----) | | | | |\ | | | | `--' | | . \ │
│ |_______/ |__| |__| \__| |__| \______/ |__|\__\ │
│ │
└──────────────────────────────────────────────────────────────────┘
*/
class StatusItemHolder(private val view: View, private val glide: GlideRequests, private val uniqueId: String?, private val photoExtra: Bundle?) : BaseViewHolder(view) {
companion object {
fun create(parent: ViewGroup, glide: GlideRequests, uniqueId: String?, photoExtra: Bundle?): StatusItemHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.status_list_item, parent, false)
return StatusItemHolder(view, glide, uniqueId, photoExtra)
}
}
private val uidFormat = "@%s"
private val sourceFormat = "来自%s"
fun bind(status: Status) {
glide.asDrawable().load(status.playerExtracts?.profileImageUrl).avatar()
.transition(withCrossFade()).into(view.avatar)
when (status.playerExtracts?.uniqueId) {
null, uniqueId -> view.avatar.setOnClickListener(null)
else -> view.avatar.setOnClickListener {
(view.context as AbstractActivity).loadRootFragment(R.id.fragment_container,
PlayerView.newInstance(uniqueId = status.playerExtracts!!.uniqueId))
}
}
view.screenName.text = status.playerExtracts?.screenName
FanfouUtils.parseAndSetText(view.content, status.text)
FanfouUtils.parseAndSetText(view.source, String.format(sourceFormat, status.source))
val formattedId = String.format(uidFormat, status.playerExtracts?.id)
view.userId.text = formattedId
view.createdAt.text = FanfouFormatter.convertDateToStr(status.createdAt!!)
if (status.photos == null) {
glide.clear(view.image)
view.image.visibility = View.GONE
} else {
view.image.visibility = View.VISIBLE
photoExtra?.let {
view.image.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
view.image.viewTreeObserver.removeOnGlobalLayoutListener(this)
val ratio = it.getInt("h", 0) * 1.0f / it.getInt("w", 1)
val lps = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
lps.height = (view.image.width * ratio).toInt()
view.image.layoutParams = lps
}
})
}
glide.asDrawable()
.load(status.photos?.size(ConvertUtils.dp2px(view.context, Photos.LARGE_SIZE)))
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).into(view.image)
}
view.moreButton.setOnClickListener { }
}
} | mit | 9ea4c431dbb7fa818e4ff8b20501a8d9 | 44.072072 | 169 | 0.583966 | 4.147595 | false | false | false | false |
VictorAlbertos/KDirtyAndroid | app/src/main/kotlin/io.victoralbertos.kdirtyandroid/presentation/home/users/UsersFragment.kt | 1 | 3293 | package io.victoralbertos.kdirtyandroid.presentation.home.users
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.skydoves.landscapist.glide.GlideImage
import dagger.hilt.android.AndroidEntryPoint
import io.victor.kdirtyandroid.R
import io.victoralbertos.kdirtyandroid.entities.User
import io.victoralbertos.kdirtyandroid.presentation.AppScaffold
@AndroidEntryPoint
class UsersFragment : Fragment() {
private val usersViewModel: UsersViewModel by viewModels()
@ExperimentalFoundationApi
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
AppScaffold(
showBack = false,
titleToolBar = stringResource(id = R.string.list_of_users),
content = {
val items: LazyPagingItems<User> = usersViewModel.pagingData.collectAsLazyPagingItems()
LazyVerticalGrid(cells = GridCells.Fixed(3)) {
items(items.itemCount) { index ->
UserItem(items[index]!!)
}
}
}
)
}
}
}
@Composable
fun UserItem(user: User) {
Row(
modifier = Modifier
.clickable {
findNavController().navigate(UsersFragmentDirections.actionUserFragment(user))
}
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
user.avatar?.let {
GlideImage(
modifier = Modifier
.height(125.dp),
imageModel = user.avatar,
contentScale = ContentScale.Crop
)
}
}
}
@Composable
fun UserImage(
imageUrl: String,
modifier: Modifier = Modifier
) {
GlideImage(
modifier = modifier,
imageModel = imageUrl,
contentScale = ContentScale.Crop
)
}
}
| apache-2.0 | 12a17e3e34d5dcfa4e7d5d29af1595bf | 34.408602 | 111 | 0.651685 | 5.260383 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/data/database/sql/TagTable.kt | 1 | 1333 | package com.marverenic.reader.data.database.sql
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.marverenic.reader.model.Tag
import com.marverenic.reader.utils.getString
const val TAG_TABLE_NAME = "tags"
private const val TAG_ID_COL = "_ID"
private const val TAG_LABEL_COL = "label"
private const val CREATE_STATEMENT = """
CREATE TABLE $TAG_TABLE_NAME(
$TAG_ID_COL varchar PRIMARY KEY,
$TAG_LABEL_COL varchar
);
"""
class TagTable(db: SQLiteDatabase) : SqliteTable<Tag>(db) {
override val tableName = TAG_TABLE_NAME
companion object {
fun onCreate(db: SQLiteDatabase) {
db.execSQL(CREATE_STATEMENT)
}
}
override fun convertToContentValues(row: Tag, cv: ContentValues) {
cv.put(TAG_ID_COL, row.id)
cv.put(TAG_LABEL_COL, row.label)
}
override fun readValueFromCursor(cursor: Cursor) = Tag(
id = cursor.getString(TAG_ID_COL),
label = cursor.getString(TAG_LABEL_COL)
)
fun findById(tagId: String) = query(
selection = "$TAG_ID_COL = ?",
selectionArgs = arrayOf(tagId))
.firstOrNull()
} | apache-2.0 | 165ecbd4a543aa3e2dfb64730a517808 | 28.644444 | 74 | 0.607652 | 4.152648 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/widget/WidgetManager.kt | 1 | 3715 | package ch.rmy.android.http_shortcuts.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.view.View
import android.widget.RemoteViews
import ch.rmy.android.framework.extensions.createIntent
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.ExecuteActivity
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.data.domains.widgets.WidgetsRepository
import ch.rmy.android.http_shortcuts.data.models.WidgetModel
import ch.rmy.android.http_shortcuts.utils.IconUtil
import javax.inject.Inject
class WidgetManager
@Inject
constructor(
private val widgetsRepository: WidgetsRepository,
) {
suspend fun createWidget(widgetId: Int, shortcutId: ShortcutId, showLabel: Boolean, labelColor: String?) {
widgetsRepository.createWidget(widgetId, shortcutId, showLabel, labelColor)
}
suspend fun updateWidgets(context: Context, widgetIds: List<Int>) {
widgetsRepository.getWidgetsByIds(widgetIds)
.forEach { widget ->
updateWidget(context, widget)
}
}
suspend fun updateWidgets(context: Context, shortcutId: ShortcutId) {
widgetsRepository.getWidgetsByShortcutId(shortcutId)
.forEach { widget ->
updateWidget(context, widget)
}
}
private fun updateWidget(context: Context, widget: WidgetModel) {
val shortcut = widget.shortcut ?: return
RemoteViews(context.packageName, R.layout.widget).also { views ->
views.setOnClickPendingIntent(
R.id.widget_base,
ExecuteActivity.IntentBuilder(shortcut.id)
.build(context)
.let { intent ->
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE
} else 0
PendingIntent.getActivity(context, widget.widgetId, intent, flags)
}
)
if (widget.showLabel) {
views.setViewVisibility(R.id.widget_label, View.VISIBLE)
views.setTextViewText(R.id.widget_label, shortcut.name)
views.setTextColor(R.id.widget_label, widget.labelColor?.let(Color::parseColor) ?: Color.WHITE)
} else {
views.setViewVisibility(R.id.widget_label, View.GONE)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
views.setImageViewIcon(R.id.widget_icon, IconUtil.getIcon(context, shortcut.icon))
} else {
views.setImageViewUri(R.id.widget_icon, shortcut.icon.getIconURI(context, external = true))
}
AppWidgetManager.getInstance(context)
.updateAppWidget(widget.widgetId, views)
}
}
suspend fun deleteWidgets(widgetIds: List<Int>) {
widgetsRepository.deleteDeadWidgets()
widgetsRepository.deleteWidgets(widgetIds)
}
companion object {
fun getIntent(widgetId: Int) =
createIntent {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
}
fun getWidgetIdFromIntent(intent: Intent): Int? =
intent.extras?.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID,
)
?.takeUnless {
it == AppWidgetManager.INVALID_APPWIDGET_ID
}
}
}
| mit | 70a036a66a52f8f46db27119ce5f2934 | 37.298969 | 111 | 0.639569 | 4.714467 | false | false | false | false |
sky-map-team/stardroid | app/src/main/java/com/google/android/stardroid/layers/AbstractRenderablesLayer.kt | 1 | 4507 | // Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.layers
import android.content.res.Resources
import android.util.Log
import com.google.android.stardroid.renderables.*
import com.google.android.stardroid.renderer.RendererObjectManager.UpdateType
import com.google.android.stardroid.search.PrefixStore
import com.google.android.stardroid.search.SearchResult
import com.google.android.stardroid.util.MiscUtil
import java.util.*
/**
* Layer for objects which are [AstronomicalRenderable]s.
*
* @author Brent Bryan
*/
// TODO(brent): merge with AbstractLayer?
abstract class AbstractRenderablesLayer(resources: Resources, private val shouldUpdate: Boolean) :
AbstractLayer(resources) {
private val textPrimitives = ArrayList<TextPrimitive>()
private val imagePrimitives = ArrayList<ImagePrimitive>()
private val pointPrimitives = ArrayList<PointPrimitive>()
private val linePrimitives = ArrayList<LinePrimitive>()
private val astroRenderables = ArrayList<AstronomicalRenderable>()
private val searchIndex = HashMap<String, SearchResult>()
private val prefixStore = PrefixStore()
@Synchronized
override fun initialize() {
astroRenderables.clear()
initializeAstroSources(astroRenderables)
for (astroRenderable in astroRenderables) {
val renderables = astroRenderable.initialize()
textPrimitives.addAll(renderables.labels)
imagePrimitives.addAll(renderables.images)
pointPrimitives.addAll(renderables.points)
linePrimitives.addAll(renderables.lines)
val names = astroRenderable.names
if (names.isNotEmpty()) {
for (name in names) {
searchIndex[name.lowercase()] = SearchResult(name, astroRenderable)
prefixStore.add(name.lowercase())
}
}
}
// update the renderer
updateLayerForControllerChange()
}
override fun updateLayerForControllerChange() {
refreshSources(EnumSet.of(UpdateType.Reset))
if (shouldUpdate) {
addUpdateClosure(this::refreshSources)
}
}
/**
* Subclasses should override this method and add all their
* [AstronomicalRenderable] to the given [ArrayList].
*/
protected abstract fun initializeAstroSources(sources: ArrayList<AstronomicalRenderable>)
/**
* Redraws the sources on this layer, after first refreshing them based on
* the current state of the
* [com.google.android.stardroid.control.AstronomerModel].
*/
private fun refreshSources() {
refreshSources(EnumSet.noneOf(UpdateType::class.java))
}
/**
* Redraws the sources on this layer, after first refreshing them based on
* the current state of the
* [com.google.android.stardroid.control.AstronomerModel].
*/
@Synchronized
protected fun refreshSources(updateTypes: EnumSet<UpdateType>) {
for (astroRenderable in astroRenderables) {
updateTypes.addAll(astroRenderable.update())
}
if (!updateTypes.isEmpty()) {
redraw(updateTypes)
}
}
private fun redraw(updateTypes: EnumSet<UpdateType>) {
super.redraw(textPrimitives, pointPrimitives, linePrimitives, imagePrimitives, updateTypes)
}
override fun searchByObjectName(name: String): List<SearchResult> {
Log.d(TAG, "Search planets layer for $name")
val matches = ArrayList<SearchResult>()
val searchResult = searchIndex[name.lowercase()]
if (searchResult != null && searchResult.renderable.isVisible) {
matches.add(searchResult)
}
Log.d(TAG, layerName + " provided " + matches.size + "results for " + name)
return matches
}
override fun getObjectNamesMatchingPrefix(prefix: String): Set<String> {
Log.d(TAG, "Searching planets layer for prefix $prefix")
val results = prefixStore.queryByPrefix(prefix)
Log.d(TAG, "Got " + results.size + " results for prefix " + prefix + " in " + layerName)
return results
}
companion object {
val TAG = MiscUtil.getTag(AbstractRenderablesLayer::class.java)
}
} | apache-2.0 | e7b5cb51a24d7349f442ea0d9f2362f7 | 34.777778 | 98 | 0.733748 | 4.263955 | false | false | false | false |
sg26565/hott-transmitter-config | VDFEditor/src/main/kotlin/de/treichels/hott/vdfeditor/actions/UndoBuffer.kt | 1 | 2431 | package de.treichels.hott.vdfeditor.actions
import javafx.beans.property.ReadOnlyBooleanProperty
import tornadofx.*
class UndoBuffer<T>(private val items: MutableList<T>) {
// current action pointer
internal var index: Int = 0
private set
// list of actions managed by this undo buffer
internal val actions = mutableListOf<UndoableAction<T>>()
var canRedo: Boolean by property(false)
private set
var canUndo: Boolean by property(false)
private set
// JavaFX properties for binding to UI elements
fun canRedoProperty(): ReadOnlyBooleanProperty = ReadOnlyBooleanProperty.readOnlyBooleanProperty(getProperty(UndoBuffer<T>::canRedo))
fun canUndoProperty(): ReadOnlyBooleanProperty = ReadOnlyBooleanProperty.readOnlyBooleanProperty(getProperty(UndoBuffer<T>::canUndo))
// the current action
private val currentAction
get() = actions[index]
/**
* Reset this undo buffer and remove all stored actions.
*/
fun clear() {
actions.clear()
index = 0
canRedo = false
canUndo = false
}
/**
* Undo current action and move action pointer accordingly
*/
fun undo() {
if (index > 0) {
index--
currentAction.undo(items)
canRedo = true
canUndo = index > 0
}
}
/**
* Redo the current action and move action pointer accordingly
*/
fun redo() {
if (index < actions.size) {
currentAction.apply {
index++
apply(items)
}
canRedo = index < actions.size
canUndo = true
}
}
/**
* Push a new action on top of the undo buffer. The action will be applied and can be undone afterwards.
* This will also withdraw all undone actions (i.e. they can not be redone)
*/
fun push(action: UndoableAction<T>) {
// withdraw any actions that were undone previously, but not redone
while (index < actions.size)
actions.removeAt(index)
actions.add(action)
redo()
}
/**
* Undo the current action and remove is from the undo buffer. Only allowed if there are no undone actions.
*/
fun pop() {
if (index != actions.size) throw IllegalArgumentException()
undo()
actions.removeAt(index)
canRedo = false
}
}
| lgpl-3.0 | 9fd551a5264b0d9f3f59734ca45a4855 | 26.314607 | 137 | 0.611682 | 4.776031 | false | false | false | false |
kun368/ACManager | src/main/java/com/zzkun/util/web/HttpUtil.kt | 1 | 3117 | @file:Suppress("DEPRECATION")
package com.zzkun.util.web
import org.apache.commons.io.IOUtils
import org.apache.http.client.methods.HttpGet
import org.apache.http.conn.scheme.Scheme
import org.apache.http.impl.client.BasicResponseHandler
import org.apache.http.impl.client.DefaultHttpClient
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.net.URL
import java.security.cert.X509Certificate
import java.util.concurrent.Callable
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
/**
* 网页抓取工具类
* 提供Java原生抓取,JSoup,Https抓取
* Created by kun36 on 2016/7/4.
*/
@Component
open class HttpUtil {
companion object {
private val logger: Logger = LoggerFactory.getLogger(HttpUtil::class.java)
}
/**
* 重复执行任务并返回值或抛出异常
*/
fun <T> repeatDo(task: Callable<T>, time: Int): T {
var result: T? = null
var exception: Exception? = null
for (i in 1..time) {
try {
result = task.call()
if (result != null)
break
} catch (e: Exception) {
exception = e
}
}
if (result == null)
throw exception!!
return result
}
fun readURL(url: String): String {
return repeatDo(Callable {
logger.info("[*] readURL: ${url}")
IOUtils.toString(URL(url), "utf8")
}, 5)
}
fun readJsoupURL(url: String): Document {
return repeatDo(Callable {
logger.info("[*] readJsoupURL: ${url}")
Jsoup.connect(url).timeout(8888).get()
}, 5)
}
fun readHttpsURL(url: String): String {
return repeatDo(Callable {
logger.info("[*] readHttpsURL: ${url}")
val httpclient = DefaultHttpClient()
val ctx = SSLContext.getInstance("SSL")
val tm = object : X509TrustManager {
override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {
}
override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {
}
override fun getAcceptedIssuers(): Array<out X509Certificate>? {
return null
}
}
ctx.init(null, arrayOf<TrustManager>(tm), null)
val ssf = org.apache.http.conn.ssl.SSLSocketFactory(ctx)
val ccm = httpclient.getConnectionManager()
val sr = ccm.schemeRegistry
sr.register(Scheme("https", 443, ssf))
val httpget = HttpGet(url)
val params = httpclient.getParams()
httpget.params = params
val responseHandler = BasicResponseHandler()
httpclient.execute(httpget, responseHandler)
}, 5)
}
}
| gpl-3.0 | 7ad37e36d57dbd325e418a1446be8995 | 29.802083 | 95 | 0.578447 | 4.120108 | false | false | false | false |
JayNewstrom/json | plugin/compiler/src/main/kotlin/com/jaynewstrom/jsonDelight/compiler/ModelDeserializerBuilder.kt | 1 | 6987 | package com.jaynewstrom.jsonDelight.compiler
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializer
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializerFactory
import com.jaynewstrom.jsonDelight.runtime.JsonRegistrable
import com.jaynewstrom.jsonDelight.runtime.internal.ListDeserializer
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
import java.io.IOException
internal data class ModelDeserializerBuilder(
private val isPublic: Boolean,
private val packageName: String,
private val name: String,
private val fields: List<FieldDefinition>
) {
fun build(): TypeSpec {
val jsonDeserializerType = JsonDeserializer::class.asTypeName()
val typeBuilder = TypeSpec.classBuilder(JsonCompiler.deserializerName(name))
.addSuperinterface(jsonDeserializerType.parameterizedBy(JsonCompiler.jsonModelType(packageName, name)))
.addSuperinterface(JsonRegistrable::class)
.addFunction(JsonCompiler.modelClassFunSpec(packageName, name))
.addFunction(deserializeMethodSpec())
if (!isPublic) {
typeBuilder.addModifiers(KModifier.INTERNAL)
}
return typeBuilder.build()
}
private fun deserializeMethodSpec(): FunSpec {
val methodBuilder = FunSpec.builder("deserialize")
.addAnnotation(JsonCompiler.throwsIoExceptionAnnotation())
.addModifiers(KModifier.OVERRIDE)
.returns(JsonCompiler.jsonModelType(packageName, name))
.addParameter(ParameterSpec.builder(JSON_PARSER_VARIABLE_NAME, JsonParser::class).build())
.addParameter(ParameterSpec.builder(DESERIALIZER_FACTORY_VARIABLE_NAME, JsonDeserializerFactory::class.java).build())
deserializeMethodBody(methodBuilder)
return methodBuilder.build()
}
private fun deserializeMethodBody(methodBuilder: FunSpec.Builder) {
methodBuilder.addComment("Ensure we are in the correct state.")
methodBuilder.beginControlFlow("if ($JSON_PARSER_VARIABLE_NAME.currentToken() != %T.%L)", JsonToken::class.java,
JsonToken.START_OBJECT)
methodBuilder.addStatement("throw %T(%S)", IOException::class.java, "Expected data to start with an Object")
methodBuilder.endControlFlow()
methodBuilder.addComment("Initialize variables.")
fields.forEach { field ->
if (field.primitiveType != null && !field.type.isNullable && field.primitiveType != PrimitiveType.STRING) {
methodBuilder.addStatement("var ${field.fieldName}: %T = ${field.primitiveType.defaultValue}", field.type)
} else if (field.type.isNullable) {
methodBuilder.addStatement("var ${field.fieldName}: %T = null", field.type)
} else {
methodBuilder.addStatement("lateinit var ${field.fieldName}: %T", field.type)
}
}
methodBuilder.addComment("Parse fields as they come.")
methodBuilder.beginControlFlow("while ($JSON_PARSER_VARIABLE_NAME.nextToken() != %T.%L)", JsonToken::class.java,
JsonToken.END_OBJECT)
methodBuilder.addStatement("val fieldName = $JSON_PARSER_VARIABLE_NAME.getCurrentName()")
methodBuilder.addStatement("val nextToken = $JSON_PARSER_VARIABLE_NAME.nextToken()")
methodBuilder.beginControlFlow("if (nextToken == %T.%L)", JsonToken::class.java, JsonToken.VALUE_NULL)
methodBuilder.addStatement("continue")
methodBuilder.endControlFlow()
if (fields.isNotEmpty()) {
var addElse = false
fields.forEach { field ->
val fieldEqualsIfStatement = "if (fieldName == \"${field.jsonName}\")"
if (addElse) {
methodBuilder.nextControlFlow("else $fieldEqualsIfStatement")
} else {
addElse = true
methodBuilder.beginControlFlow(fieldEqualsIfStatement)
}
field.assignVariable(methodBuilder)
}
methodBuilder.nextControlFlow("else")
methodBuilder.addStatement("$JSON_PARSER_VARIABLE_NAME.skipChildren()")
methodBuilder.endControlFlow() // End if / else if.
}
methodBuilder.endControlFlow() // End while loop.
methodBuilder.addComment("Create the model given the parsed fields.")
createModel(methodBuilder)
}
private fun FieldDefinition.assignVariable(methodBuilder: FunSpec.Builder) {
if (type is ParameterizedTypeName && type.rawType == List::class.asTypeName()) {
val modelType = type.typeArguments[0]
val listDeserializerType = ListDeserializer::class.java.asTypeName()
val deserializer = getDeserializer(modelType)
val codeFormat = "$fieldName = %T(${deserializer.code}).${callDeserialize()}"
methodBuilder.addStatement(codeFormat, listDeserializerType, deserializer.codeArgument)
} else if (customDeserializer == null && primitiveType != null) {
methodBuilder.addStatement("$fieldName = $JSON_PARSER_VARIABLE_NAME.${primitiveType.parseMethod}()")
} else {
val deserializer = getDeserializer(type)
methodBuilder.addStatement("$fieldName = ${deserializer.code}.${callDeserialize()}", deserializer.codeArgument)
}
}
private fun createModel(methodBuilder: FunSpec.Builder) {
val constructorCallArguments = StringBuilder()
fields.forEach { field ->
if (!constructorCallArguments.isEmpty()) {
constructorCallArguments.append(", ")
}
constructorCallArguments.append(field.fieldName)
}
methodBuilder.addStatement("return $name(%L)", constructorCallArguments.toString())
}
private data class FieldDeserializerResult(val code: String, val codeArgument: TypeName)
private fun FieldDefinition.getDeserializer(typeName: TypeName): FieldDeserializerResult {
return if (customDeserializer == null) {
FieldDeserializerResult("$DESERIALIZER_FACTORY_VARIABLE_NAME[%T::class.java]", typeName.copy(nullable = false))
} else {
FieldDeserializerResult("%T", customDeserializer)
}
}
private fun callDeserialize(): String {
return "deserialize($JSON_PARSER_VARIABLE_NAME, $DESERIALIZER_FACTORY_VARIABLE_NAME)"
}
companion object {
private const val JSON_PARSER_VARIABLE_NAME = "jp"
private const val DESERIALIZER_FACTORY_VARIABLE_NAME = "deserializerFactory"
}
}
| apache-2.0 | b95a9c367470a4138ae493f8751b8e69 | 48.553191 | 129 | 0.687276 | 5.179392 | false | false | false | false |
drmaas/ratpack-kotlin | ratpack-kotlin-gradle/src/main/kotlin/ratpack/kotlin/gradle/RatpackKotlinPlugin.kt | 1 | 1727 | package ratpack.kotlin.gradle
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.ApplicationPluginConvention
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformJvmPlugin
import ratpack.gradle.RatpackPlugin
class RatpackKotlinPlugin : Plugin<Project> {
private val GRADLE_VERSION_BASELINE = GradleVersion.version("6.0")
override fun apply(project: Project) {
with(project) {
val gradleVersion = GradleVersion.version(gradle.gradleVersion)
if (gradleVersion < GRADLE_VERSION_BASELINE) {
throw GradleException("Ratpack requires Gradle version ${GRADLE_VERSION_BASELINE.version} or later")
}
plugins.apply(RatpackPlugin::class.java)
plugins.apply(KotlinPlatformJvmPlugin::class.java)
val application = convention.findPlugin(ApplicationPluginConvention::class.java)
application?.mainClassName = "ratpack.kotlin.runner.KotlinDslRunner"
val pluginVersion = RatpackKotlinPlugin::class.java.classLoader.getResource("version.txt")?.readText()?.trim().orEmpty()
val kotlinVersion = "1.6.21" // need a better way
val ratpackKotlinExtension = RatpackKotlinExtension(project, pluginVersion, kotlinVersion) // this is just used to add dependencies
dependencies.add("api", ratpackKotlinExtension.getDsl())
dependencies.add("runtimeOnly", ratpackKotlinExtension.getCompiler())
dependencies.add("runtimeOnly", ratpackKotlinExtension.getScriptingCompiler())
dependencies.add("runtimeOnly", ratpackKotlinExtension.getScript())
dependencies.add("testImplementation", ratpackKotlinExtension.getTest())
}
}
}
| apache-2.0 | 227993264abcf6f2c485cee8b8b5294c | 40.119048 | 137 | 0.767805 | 4.642473 | false | false | false | false |
paoloach/zdomus | cs5463/app/src/main/java/it/achdjian/paolo/cs5463/zigbee/ZDevices.kt | 1 | 1615 | package it.achdjian.paolo.cs5463.zigbee
import it.achdjian.paolo.cs5463.domusEngine.DomusEngine
import it.achdjian.paolo.cs5463.domusEngine.rest.JsonDevice
import java.util.*
/**
* Created by Paolo Achdjian on 7/10/17.
*/
object ZDevices {
private val TAG = ZDevices::class.java.name
private val devices = TreeMap<Int, ZDevice>()
fun addDevices(newDevices: Map<Int, String>) {
val iter = devices.iterator()
while (iter.hasNext()) {
val networkAddress = iter.next().key
if (!newDevices.containsKey(networkAddress)) {
iter.remove()
}
}
newDevices.keys.
filter { !devices.contains(it) }.
forEach { DomusEngine.getDevice(it) }
}
fun addDevice(newDevice: JsonDevice) {
val device = ZDevice(newDevice)
devices[device.shortAddress] = device
}
fun get(networkAddr: Int): ZDevice {
val zDevice = devices[networkAddr]
if (zDevice == null)
return nullZDevice
else
return zDevice;
}
fun get(extendAddr: String): ZDevice {
devices.values.forEach({ if (it.extendedAddr == extendAddr) return it })
return nullZDevice
}
fun addEndpoint(endpoint: ZEndpoint) {
if (devices.containsKey(endpoint.short_address)) {
devices[endpoint.short_address]?.endpoints?.put(endpoint.endpoint_id, endpoint)
}
}
fun existDevice(network: Int): Boolean {
devices.forEach({ if (it.value.shortAddress == network) return true })
return false
}
} | gpl-2.0 | cc58b2278505360bbc84ebee7f3947f9 | 26.862069 | 91 | 0.614861 | 4.109415 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | benchmarks/commonMain/src/benchmarks/immutableSet/builder/Remove.kt | 1 | 1400 | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableSet.builder
import benchmarks.*
import kotlinx.collections.immutable.PersistentSet
import kotlinx.benchmark.*
@State(Scope.Benchmark)
open class Remove {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000)
var size: Int = 0
@Param(HASH_IMPL, ORDERED_IMPL)
var implementation = ""
@Param(ASCENDING_HASH_CODE, RANDOM_HASH_CODE, COLLISION_HASH_CODE, NON_EXISTING_HASH_CODE)
var hashCodeType = ""
@Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0)
var immutablePercentage: Double = 0.0
private var elements = listOf<IntWrapper>()
private var elementsToRemove = listOf<IntWrapper>()
@Setup
fun prepare() {
elements = generateElements(hashCodeType, size)
elementsToRemove = if (hashCodeType == NON_EXISTING_HASH_CODE) {
generateElements(hashCodeType, size)
} else {
elements
}
}
@Benchmark
fun addAndRemove(): PersistentSet.Builder<IntWrapper> {
val builder = persistentSetBuilderAdd(implementation, elements, immutablePercentage)
repeat(times = size) { index ->
builder.remove(elementsToRemove[index])
}
return builder
}
} | apache-2.0 | 2de2a50bd676c235805310e396ad6d52 | 28.1875 | 107 | 0.667857 | 3.910615 | false | false | false | false |
porokoro/paperboy | sample/src/main/kotlin/com/github/porokoro/paperboy/sample/JavaSampleActivity.kt | 1 | 2207 | /*
* Copyright (C) 2015-2016 Dominik Hibbeln
*
* 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.github.porokoro.paperboy.sample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import org.jetbrains.anko.find
class JavaSampleActivity : AppCompatActivity() {
companion object {
val SAMPLE1_DEFAULT = 1
val SAMPLE1_CUSTOM = 2
val SAMPLE2_DEFAULT = 3
val SAMPLE2_CUSTOM = 4
val ARG_SAMPLE = "sample"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_java_sample)
setSupportActionBar(find(R.id.toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.content, when (intent?.getIntExtra(ARG_SAMPLE, 0)) {
SAMPLE1_DEFAULT -> JavaSample.buildDefault(this)
SAMPLE1_CUSTOM -> JavaSample.buildCustom(this)
SAMPLE2_DEFAULT -> JavaSample2.buildDefault(this)
SAMPLE2_CUSTOM -> JavaSample2.buildCustom(this)
else -> throw Exception()
})
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem?) =
when (item?.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
| apache-2.0 | 6a4132a1ffc9322adc639d5ffd27ab0c | 35.180328 | 82 | 0.624377 | 4.715812 | false | false | false | false |
artjimlop/clean-architecture-kotlin | domain/src/test/java/com/example/executor/TestThreadExecutor.kt | 1 | 908 | package com.example.executor
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
class TestThreadExecutor : ThreadExecutor {
private val workQueue: BlockingQueue<Runnable>
private val threadPoolExecutor: ThreadPoolExecutor
init {
this.workQueue = LinkedBlockingQueue()
this.threadPoolExecutor = ThreadPoolExecutor(INITIAL_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_TIME.toLong(), KEEP_ALIVE_TIME_UNIT, this.workQueue)
}
override fun execute(runnable: Runnable) {
this.threadPoolExecutor.execute(runnable)
}
companion object {
private val INITIAL_POOL_SIZE = 3
private val MAX_POOL_SIZE = 5
private val KEEP_ALIVE_TIME = 10
private val KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS
}
} | apache-2.0 | 05b30a9dc5ec9f969c5a10edf3ecd34f | 26.545455 | 86 | 0.720264 | 4.753927 | false | false | false | false |
foresterre/mal | kotlin/src/mal/core.kt | 7 | 10352 | package mal
import java.io.File
import java.util.*
val ns = hashMapOf(
envPair("+", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger + y as MalInteger }) }),
envPair("-", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger - y as MalInteger }) }),
envPair("*", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger * y as MalInteger }) }),
envPair("/", { a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger / y as MalInteger }) }),
envPair("list", { a: ISeq -> MalList(a) }),
envPair("list?", { a: ISeq -> if (a.first() is MalList) TRUE else FALSE }),
envPair("empty?", { a: ISeq -> if (a.first() !is ISeq || !(a.first() as ISeq).seq().any()) TRUE else FALSE }),
envPair("count", { a: ISeq ->
if (a.first() is ISeq) MalInteger((a.first() as ISeq).count().toLong()) else MalInteger(0)
}),
envPair("=", { a: ISeq -> pairwiseEquals(a) }),
envPair("<", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value < y.value }) }),
envPair("<=", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value <= y.value }) }),
envPair(">", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value > y.value }) }),
envPair(">=", { a: ISeq -> pairwiseCompare(a, { x, y -> x.value >= y.value }) }),
envPair("pr-str", { a: ISeq ->
MalString(a.seq().map({ it -> pr_str(it, print_readably = true) }).joinToString(" "))
}),
envPair("str", { a: ISeq ->
MalString(a.seq().map({ it -> pr_str(it, print_readably = false) }).joinToString(""))
}),
envPair("prn", { a: ISeq ->
println(a.seq().map({ it -> pr_str(it, print_readably = true) }).joinToString(" "))
NIL
}),
envPair("println", { a: ISeq ->
println(a.seq().map({ it -> pr_str(it, print_readably = false) }).joinToString(" "))
NIL
}),
envPair("read-string", { a: ISeq ->
val string = a.first() as? MalString ?: throw MalException("slurp requires a string parameter")
read_str(string.value)
}),
envPair("slurp", { a: ISeq ->
val name = a.first() as? MalString ?: throw MalException("slurp requires a filename parameter")
val text = File(name.value).readText()
MalString(text)
}),
envPair("cons", { a: ISeq ->
val list = a.nth(1) as? ISeq ?: throw MalException("cons requires a list as its second parameter")
val mutableList = list.seq().toCollection(LinkedList<MalType>())
mutableList.addFirst(a.nth(0))
MalList(mutableList)
}),
envPair("concat", { a: ISeq -> MalList(a.seq().flatMap({ it -> (it as ISeq).seq() }).toCollection(LinkedList<MalType>())) }),
envPair("nth", { a: ISeq ->
val list = a.nth(0) as? ISeq ?: throw MalException("nth requires a list as its first parameter")
val index = a.nth(1) as? MalInteger ?: throw MalException("nth requires an integer as its second parameter")
if (index.value >= list.count()) throw MalException("index out of bounds")
list.nth(index.value.toInt())
}),
envPair("first", { a: ISeq ->
if (a.nth(0) == NIL) NIL
else {
val list = a.nth(0) as? ISeq ?: throw MalException("first requires a list parameter")
if (list.seq().any()) list.first() else NIL
}
}),
envPair("rest", { a: ISeq ->
if (a.nth(0) == NIL) MalList()
else {
val list = a.nth(0) as? ISeq ?: throw MalException("rest requires a list parameter")
MalList(list.rest())
}
}),
envPair("throw", { a: ISeq ->
val throwable = a.nth(0)
throw MalCoreException(pr_str(throwable), throwable)
}),
envPair("apply", { a: ISeq ->
val function = a.nth(0) as MalFunction
val params = MalList()
a.seq().drop(1).forEach({ it ->
if (it is ISeq) {
it.seq().forEach({ x -> params.conj_BANG(x) })
} else {
params.conj_BANG(it)
}
})
function.apply(params)
}),
envPair("map", { a: ISeq ->
val function = a.nth(0) as MalFunction
MalList((a.nth(1) as ISeq).seq().map({ it ->
val params = MalList()
params.conj_BANG(it)
function.apply(params)
}).toCollection(LinkedList<MalType>()))
}),
envPair("nil?", { a: ISeq -> if (a.nth(0) == NIL) TRUE else FALSE }),
envPair("true?", { a: ISeq -> if (a.nth(0) == TRUE) TRUE else FALSE }),
envPair("false?", { a: ISeq -> if (a.nth(0) == FALSE) TRUE else FALSE }),
envPair("string?", { a: ISeq ->
if (a.nth(0) is MalString && !(a.nth(0) is MalKeyword)) TRUE else FALSE
}),
envPair("symbol?", { a: ISeq -> if (a.nth(0) is MalSymbol) TRUE else FALSE }),
envPair("symbol", { a: ISeq -> MalSymbol((a.nth(0) as MalString).value) }),
envPair("keyword", { a: ISeq ->
val param = a.nth(0)
if (param is MalKeyword) param else MalKeyword((a.nth(0) as MalString).value)
}),
envPair("keyword?", { a: ISeq -> if (a.nth(0) is MalKeyword) TRUE else FALSE }),
envPair("number?", { a: ISeq -> if (a.nth(0) is MalInteger) TRUE else FALSE }),
envPair("fn?", { a: ISeq -> if ((a.nth(0) as? MalFunction)?.is_macro ?: true) FALSE else TRUE }),
envPair("macro?", { a: ISeq -> if ((a.nth(0) as? MalFunction)?.is_macro ?: false) TRUE else FALSE }),
envPair("vector", { a: ISeq -> MalVector(a) }),
envPair("vector?", { a: ISeq -> if (a.nth(0) is MalVector) TRUE else FALSE }),
envPair("hash-map", { a: ISeq ->
val map = MalHashMap()
pairwise(a).forEach({ it -> map.assoc_BANG(it.first as MalString, it.second) })
map
}),
envPair("map?", { a: ISeq -> if (a.nth(0) is MalHashMap) TRUE else FALSE }),
envPair("assoc", { a: ISeq ->
val map = MalHashMap(a.first() as MalHashMap)
pairwise(a.rest()).forEach({ it -> map.assoc_BANG(it.first as MalString, it.second) })
map
}),
envPair("dissoc", { a: ISeq ->
val map = MalHashMap(a.first() as MalHashMap)
a.rest().seq().forEach({ it -> map.dissoc_BANG(it as MalString) })
map
}),
envPair("get", { a: ISeq ->
val map = a.nth(0) as? MalHashMap
val key = a.nth(1) as MalString
map?.elements?.get(key) ?: NIL
}),
envPair("contains?", { a: ISeq ->
val map = a.nth(0) as? MalHashMap
val key = a.nth(1) as MalString
if (map?.elements?.get(key) != null) TRUE else FALSE
}),
envPair("keys", { a: ISeq ->
val map = a.nth(0) as MalHashMap
MalList(map.elements.keys.toCollection(LinkedList<MalType>()))
}),
envPair("vals", { a: ISeq ->
val map = a.nth(0) as MalHashMap
MalList(map.elements.values.toCollection(LinkedList<MalType>()))
}),
envPair("count", { a: ISeq ->
val seq = a.nth(0) as? ISeq
if (seq != null) MalInteger(seq.count().toLong()) else ZERO
}),
envPair("sequential?", { a: ISeq -> if (a.nth(0) is ISeq) TRUE else FALSE }),
envPair("with-meta", { a: ISeq ->
val obj = a.nth(0)
val metadata = a.nth(1)
obj.with_meta(metadata)
}),
envPair("meta", { a: ISeq -> a.first().metadata }),
envPair("conj", { a: ISeq -> (a.first() as ISeq).conj(a.rest()) }),
envPair("seq", { a: ISeq ->
val obj = a.nth(0)
if (obj is ISeq) {
if (obj.count() == 0) NIL
else MalList(obj.seq().toCollection(LinkedList<MalType>()))
} else if (obj is MalString && !(obj is MalKeyword)) {
if (obj.value.length == 0) NIL
else {
var strs = obj.value.map({ c -> MalString(c.toString()) })
MalList(strs.toCollection(LinkedList<MalType>()))
}
} else {
NIL
}
}),
envPair("atom", { a: ISeq -> MalAtom(a.first()) }),
envPair("atom?", { a: ISeq -> if (a.first() is MalAtom) TRUE else FALSE }),
envPair("deref", { a: ISeq -> (a.first() as MalAtom).value }),
envPair("reset!", { a: ISeq ->
val atom = a.nth(0) as MalAtom
val value = a.nth(1)
atom.value = value
value
}),
envPair("swap!", { a: ISeq ->
val atom = a.nth(0) as MalAtom
val function = a.nth(1) as MalFunction
val params = MalList()
params.conj_BANG(atom.value)
a.seq().drop(2).forEach({ it -> params.conj_BANG(it) })
val value = function.apply(params)
atom.value = value
value
}),
envPair("readline", { a: ISeq ->
val prompt = a.first() as MalString
try {
MalString(readline(prompt.value))
} catch (e: java.io.IOException) {
throw MalException(e.message)
} catch (e: EofException) {
NIL
}
}),
envPair("time-ms", { a: ISeq -> MalInteger(System.currentTimeMillis()) })
)
private fun envPair(k: String, v: (ISeq) -> MalType): Pair<MalSymbol, MalType> = Pair(MalSymbol(k), MalFunction(v))
private fun pairwise(s: ISeq): List<Pair<MalType, MalType>> {
val (keys, vals) = s.seq().withIndex().partition({ it -> it.index % 2 == 0 })
return keys.map({ it -> it.value }).zip(vals.map({ it -> it.value }))
}
private fun pairwiseCompare(s: ISeq, pred: (MalInteger, MalInteger) -> Boolean): MalConstant =
if (pairwise(s).all({ it -> pred(it.first as MalInteger, it.second as MalInteger) })) TRUE else FALSE
private fun pairwiseEquals(s: ISeq): MalConstant =
if (pairwise(s).all({ it -> it.first == it.second })) TRUE else FALSE
| mpl-2.0 | f8a369d42713bd7e95e1b30f1202633d | 42.313808 | 133 | 0.502222 | 3.761628 | false | false | false | false |
zitmen/thunderstorm-algorithms | src/main/kotlin/cz/cuni/lf1/thunderstorm/algorithms/estimators/LeastSquaresEstimator.kt | 1 | 3263 | package cz.cuni.lf1.thunderstorm.algorithms.estimators
import cz.cuni.lf1.thunderstorm.algorithms.estimators.psf.PsfModel
import cz.cuni.lf1.thunderstorm.datastructures.GrayScaleImage
import cz.cuni.lf1.thunderstorm.datastructures.Intensity
import cz.cuni.lf1.thunderstorm.datastructures.Molecule
import cz.cuni.lf1.thunderstorm.datastructures.extensions.minus
import cz.cuni.lf1.thunderstorm.datastructures.extensions.stddev
import org.apache.commons.math3.optim.*
import org.apache.commons.math3.optim.nonlinear.vector.ModelFunction
import org.apache.commons.math3.optim.nonlinear.vector.ModelFunctionJacobian
import org.apache.commons.math3.optim.nonlinear.vector.Target
import org.apache.commons.math3.optim.nonlinear.vector.Weight
import org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer
import java.util.*
private const val MAX_ITERATIONS = 1000
public class LeastSquaresEstimator(
private val fittingRadius: Int,
private val psfModel: PsfModel,
private val useWeighting: Boolean,
private val maxIter: Int = MAX_ITERATIONS)
: Estimator {
override fun estimatePosition(image: GrayScaleImage, initialEstimate: Molecule): Molecule? {
val subimage = SubImage.createSubImage(fittingRadius, image, initialEstimate)
// init
val weights = calcWeights(useWeighting, subimage)
val observations = subimage.values
// fit
val optimizer = LevenbergMarquardtOptimizer(
SimplePointChecker(10e-10, 10e-10, maxIter))
val pv: PointVectorValuePair
pv = optimizer.optimize(
MaxEval.unlimited(),
MaxIter(MAX_ITERATIONS + 1),
ModelFunction(psfModel.getValueFunction(subimage.xgrid, subimage.ygrid)),
ModelFunctionJacobian(psfModel.getJacobianFunction(subimage.xgrid, subimage.ygrid)),
Target(observations),
InitialGuess(psfModel.transformParametersInverse(psfModel.getInitialParams(subimage))),
Weight(weights))
// correct position
pv.pointRef[0] = subimage.correctXPosition(pv.pointRef[0])
pv.pointRef[1] = subimage.correctYPosition(pv.pointRef[1])
// estimate background and return an instance of the `Molecule`
val fittedParameters = psfModel.createMoleculeFromParams(pv.pointRef)
fittedParameters.background = Intensity.fromAdCounts((observations.toTypedArray() - psfModel.getValueFunction(subimage.xgrid, subimage.ygrid).value(pv.pointRef).toTypedArray()).stddev())
return fittedParameters
}
fun calcWeights(useWeighting: Boolean, subimage: SubImage): DoubleArray {
val weights = DoubleArray(subimage.values.size)
if (!useWeighting) {
Arrays.fill(weights, 1.0)
} else {
val minWeight = 1.0 / subimage.max
val maxWeight = 1000 * minWeight
for (i in 0 until subimage.values.size) {
var weight = 1 / subimage.values[i]
if (weight.isInfinite() || weight.isNaN() || weight > maxWeight) {
weight = maxWeight
}
weights[i] = weight
}
}
return weights
}
} | gpl-3.0 | 39e068137527c69aa00e9966fc8af2d9 | 43.108108 | 194 | 0.69384 | 3.955152 | false | false | false | false |
jrenner/kotlin-voxel | core/src/main/kotlin/org/jrenner/learngl/Direction.kt | 1 | 594 | package org.jrenner.learngl
object Direction {
val Up = 0x01
val Down = 0x02
val North = 0x04
val South = 0x08
val East = 0x10
val West = 0x20
val all = arrayOf(Up, Down, North, South, East, West)
val allSize = 6
val ALL_FACES: Int = 0xFF
fun toString(n: Int): String {
return when (n) {
Up -> "Up"
Down -> "Down"
North -> "North"
South -> "South"
East -> "East"
West -> "West"
else -> "Non-direction integer: $n"
}
}
}
| apache-2.0 | 55c1577ca3b181b5465aeb20e13b8cde | 20.846154 | 57 | 0.462963 | 3.535714 | false | false | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/filter/RenderScriptBlurFilter.kt | 2 | 2324 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.filter
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import androidx.annotation.RequiresApi
import com.facebook.common.internal.Preconditions
object RenderScriptBlurFilter {
const val BLUR_MAX_RADIUS = 25
/**
* Not-in-place intrinsic Gaussian blur filter using [ScriptIntrinsicBlur] and [ ]. This require
* an Android versions >= 4.2.
*
* @param dest The [Bitmap] where the blurred image is written to.
* @param src The [Bitmap] containing the original image.
* @param context The [Context] necessary to use [RenderScript]
* @param radius The radius of the blur with a supported range 0 < radius <= [ ][.BLUR_MAX_RADIUS]
*/
@JvmStatic
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun blurBitmap(dest: Bitmap, src: Bitmap, context: Context, radius: Int) {
Preconditions.checkNotNull(dest)
Preconditions.checkNotNull(src)
Preconditions.checkNotNull(context)
Preconditions.checkArgument(radius > 0 && radius <= BLUR_MAX_RADIUS)
var rs: RenderScript? = null
try {
rs = Preconditions.checkNotNull(RenderScript.create(context))
// Create an Intrinsic Blur Script using the Renderscript
val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
// Create the input/output allocations with Renderscript and the src/dest bitmaps
val allIn = Preconditions.checkNotNull(Allocation.createFromBitmap(rs, src))
val allOut = Preconditions.checkNotNull(Allocation.createFromBitmap(rs, dest))
// Set the radius of the blur
blurScript.setRadius(radius.toFloat())
blurScript.setInput(allIn)
blurScript.forEach(allOut)
allOut.copyTo(dest)
blurScript.destroy()
allIn.destroy()
allOut.destroy()
} finally {
rs?.destroy()
}
}
@JvmStatic
fun canUseRenderScript(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
}
| mit | b55a5a3e417a33aa6251f8185a9a8c65 | 34.212121 | 100 | 0.731928 | 4.179856 | false | false | false | false |
jonnyzzz/TeamCity.Node | agent/src/main/java/com/jonnyzzz/teamcity/plugins/node/agent/grunt/GruntServiceFactory.kt | 1 | 3536 | /*
* Copyright 2013-20135 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.agent.grunt
import com.jonnyzzz.teamcity.plugins.node.agent.*
import jetbrains.buildServer.agent.AgentBuildRunnerInfo
import jetbrains.buildServer.agent.BuildAgentConfiguration
import jetbrains.buildServer.agent.runner.CommandLineBuildServiceFactory
import jetbrains.buildServer.agent.runner.CommandLineBuildService
import jetbrains.buildServer.agent.runner.ProgramCommandLine
import jetbrains.buildServer.RunBuildException
import java.util.TreeMap
import com.jonnyzzz.teamcity.plugins.node.common.*
/**
* Created by Eugene Petrenko ([email protected])
* Date: 27.04.13 10:20
*/
class GruntServiceFactory : CommandLineBuildServiceFactory {
private val bean = GruntBean()
override fun getBuildRunnerInfo(): AgentBuildRunnerInfo = object : AgentBuildRunnerInfo {
override fun getType(): String = bean.runTypeName
override fun canRun(agentConfiguration: BuildAgentConfiguration): Boolean = true
}
override fun createService(): CommandLineBuildService = GruntSession()
}
class GruntSession : BaseService() {
private val bean = GruntBean()
private fun gruntExecutable() : String =
if (agentConfiguration.systemInfo.isWindows)
"grunt.cmd"
else
"grunt"
private fun gruntExecutablePath() : String {
val mode = bean.parseMode(runnerParameters[bean.gruntMode])
val cmd = gruntExecutable()
when(mode) {
GruntExecutionMode.NPM -> {
val wd = workingDirectory / "node_modules" / ".bin"
val grunt = wd / cmd
if (!grunt.isFile) {
throw RunBuildException(
"Failed to find $cmd under $wd.\n" +
"Please install grunt and grunt-cli as project-local Node.js NPM packages")
}
return grunt.path
}
GruntExecutionMode.GLOBAL -> return cmd
else ->
throw RunBuildException("Unexpected execution mode $mode")
}
}
override fun makeProgramCommandLine(): ProgramCommandLine {
val arguments = arrayListOf<String>()
arguments.add("--no-color")
val filePath = runnerParameters[bean.file]
if (filePath != null) {
val file = checkoutDirectory.resolveEx(filePath)
if (!file.isFile) {
throw RunBuildException("Failed to find File at path: $file")
}
arguments.add("--gruntfile")
arguments.add(file.path)
}
val parameters = TreeMap<String, String>()
parameters.putAll(buildParameters.systemProperties)
val parametersAll = TreeMap<String, String>()
parametersAll.putAll(configParameters)
parametersAll.putAll(buildParameters.allParameters)
arguments.addAll(generateDefaultTeamCityParametersJSON())
arguments.addAll(runnerParameters[bean.commandLineParameterKey].fetchArguments())
arguments.addAll(bean.parseCommands(runnerParameters[bean.targets]))
return execute(gruntExecutablePath(), arguments)
}
}
| apache-2.0 | a7fb5c9759935862022cafaaaf7e2c3b | 32.358491 | 93 | 0.722851 | 4.392547 | false | false | false | false |
willowtreeapps/assertk | assertk/src/commonMain/kotlin/assertk/table.kt | 1 | 7821 | package assertk
import assertk.assertions.support.show
private class TableFailure(private val table: Table) : Failure {
private val failures: MutableMap<Int, MutableList<Throwable>> = LinkedHashMap()
override fun fail(error: Throwable) {
failures.getOrPut(table.index, { ArrayList() }).plusAssign(error)
}
override fun invoke() {
if (failures.isNotEmpty()) {
FailureContext.fail(compositeErrorMessage(failures))
}
}
private fun compositeErrorMessage(errors: Map<Int, List<Throwable>>): AssertionError {
return TableFailuresError(table, errors)
}
}
internal class TableFailuresError(
private val table: Table,
private val errors: Map<Int, List<Throwable>>
) : AssertionError() {
override val message: String?
get() {
val errorCount = errors.map { it.value.size }.sum()
val prefix = if (errorCount == 1) {
"The following assertion failed\n"
} else {
"The following assertions failed ($errorCount failures)\n"
}
return errors.map { (index, failures) ->
failures.joinToString(
transform = { "\t${it.message}" },
prefix = "\t${rowMessage(index)}\n",
separator = "\n"
)
}.joinToString(
prefix = prefix,
separator = "\n\n"
)
}
private fun rowMessage(index: Int): String {
val row = table.rows[index]
return table.columnNames.mapIndexed { i, name -> Pair(name, row[i]) }.joinToString(
prefix = "on row:(",
separator = ",",
postfix = ")",
transform = { "${it.first}=${show(it.second)}" })
}
}
/**
* A table of rows to assert on. This makes it easy to run the same assertions are a number of inputs and outputs.
* @see [tableOf]
*/
sealed class Table(internal val columnNames: Array<String>) {
internal val rows = arrayListOf<Array<out Any?>>()
internal var index = 0
protected interface TableFun {
/**
* Delegate that receives all values of a row.
*/
operator fun invoke(values: Array<out Any?>)
}
internal fun row(vararg values: Any?) {
var size: Int? = null
for (row in rows) {
if (size == null) {
size = row.size
} else {
require(size == row.size) {
"all rows must have the same size. expected:$size but got:${row.size}"
}
}
}
rows.add(values)
}
protected fun forAll(f: TableFun) {
TableFailure(this).run {
for (i in 0 until rows.size) {
index = i
f(rows[i])
}
}
}
}
/**
* A table with rows of 1 value.
* @see [tableOf]
*/
class Table1<C1> internal constructor(columnNames: Array<String>) : Table(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun row(val1: C1): Table1<C1> = apply {
super.row(val1)
}
/**
* Runs the given lambda for each row in the table.
*/
fun forAll(f: (C1) -> Unit) {
forAll(object : TableFun {
override fun invoke(values: Array<out Any?>) {
@Suppress("UNCHECKED_CAST", "UnsafeCast")
f(values[0] as C1)
}
})
}
}
/**
* A table with rows of 2 values.
* @see [tableOf]
*/
class Table2<C1, C2> internal constructor(columnNames: Array<String>) : Table(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun row(val1: C1, val2: C2): Table2<C1, C2> = apply {
super.row(val1, val2)
}
/**
* Runs the given lambda for each row in the table.
*/
fun forAll(f: (C1, C2) -> Unit) {
forAll(object : TableFun {
override fun invoke(values: Array<out Any?>) {
@Suppress("UNCHECKED_CAST", "UnsafeCast")
f(values[0] as C1, values[1] as C2)
}
})
}
}
/**
* A table with rows of 3 values.
* @see [tableOf]
*/
class Table3<C1, C2, C3> internal constructor(columnNames: Array<String>) : Table(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun row(val1: C1, val2: C2, val3: C3): Table3<C1, C2, C3> = apply {
super.row(val1, val2, val3)
}
/**
* Runs the given lambda for each row in the table.
*/
fun forAll(f: (C1, C2, C3) -> Unit) {
forAll(object : TableFun {
override fun invoke(values: Array<out Any?>) {
@Suppress("UNCHECKED_CAST", "UnsafeCast")
f(values[0] as C1, values[1] as C2, values[2] as C3)
}
})
}
}
/**
* A table with rows of 4 values.
* @see [tableOf]
*/
class Table4<C1, C2, C3, C4> internal constructor(columnNames: Array<String>) : Table(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun row(val1: C1, val2: C2, val3: C3, val4: C4): Table4<C1, C2, C3, C4> = apply {
super.row(val1, val2, val3, val4)
}
/**
* Runs the given lambda for each row in the table.
*/
fun forAll(f: (C1, C2, C3, C4) -> Unit) {
forAll(object : TableFun {
override fun invoke(values: Array<out Any?>) {
@Suppress("UNCHECKED_CAST", "UnsafeCast", "MagicNumber")
f(values[0] as C1, values[1] as C2, values[2] as C3, values[3] as C4)
}
})
}
}
/**
* Builds a table with the given column names.
*/
fun tableOf(name1: String): Table1Builder = Table1Builder(arrayOf(name1))
/**
* Builds a table with the given column names.
*/
fun tableOf(name1: String, name2: String): Table2Builder = Table2Builder(arrayOf(name1, name2))
/**
* Builds a table with the given column names.
*/
fun tableOf(name1: String, name2: String, name3: String): Table3Builder =
Table3Builder(arrayOf(name1, name2, name3))
/**
* Builds a table with the given column names.
*/
fun tableOf(name1: String, name2: String, name3: String, name4: String): Table4Builder =
Table4Builder(arrayOf(name1, name2, name3, name4))
/**
* Builds a table with the given rows.
*/
sealed class TableBuilder(internal val columnNames: Array<String>)
/**
* Builds a table with the given rows.
*/
class Table1Builder internal constructor(columnNames: Array<String>) : TableBuilder(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun <C1> row(val1: C1): Table1<C1> =
Table1<C1>(columnNames).apply { row(val1) }
}
/**
* Builds a table with the given rows.
*/
class Table2Builder internal constructor(columnNames: Array<String>) : TableBuilder(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun <C1, C2> row(val1: C1, val2: C2): Table2<C1, C2> =
Table2<C1, C2>(columnNames).apply { row(val1, val2) }
}
/**
* Builds a table with the given rows.
*/
class Table3Builder internal constructor(columnNames: Array<String>) : TableBuilder(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun <C1, C2, C3> row(val1: C1, val2: C2, val3: C3): Table3<C1, C2, C3> =
Table3<C1, C2, C3>(columnNames).apply { row(val1, val2, val3) }
}
/**
* Builds a table with the given rows.
*/
class Table4Builder internal constructor(columnNames: Array<String>) : TableBuilder(columnNames) {
/**
* Adds a row to the table with the given values.
*/
fun <C1, C2, C3, C4> row(val1: C1, val2: C2, val3: C3, val4: C4): Table4<C1, C2, C3, C4> =
Table4<C1, C2, C3, C4>(columnNames).apply { row(val1, val2, val3, val4) }
}
| mit | fbe5b9635b0186337854b135b7c29f02 | 28.402256 | 114 | 0.570643 | 3.558235 | false | false | false | false |
pratikbutani/AppIntro | appintro/src/main/java/com/github/paolorotolo/appintro/AppIntroViewPager.kt | 2 | 6065 | package com.github.paolorotolo.appintro
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.Interpolator
import androidx.viewpager.widget.ViewPager
import com.github.paolorotolo.appintro.internal.LayoutUtil
import com.github.paolorotolo.appintro.internal.ScrollerCustomDuration
const val ON_ILLEGALLY_REQUESTED_NEXT_PAGE_MAX_INTERVAL = 1000
private const val VALID_SWIPE_THRESHOLD_PX = 25
/**
* Class that controls the [AppIntro] of AppIntro.
* This is responsible of handling of paging, managing touch and dispatching events.
*
* @property isFullPagingEnabled Enable or disable swiping at all.
* @property lockPage Set the page where the lock happened.
* @property onNextPageRequestedListener Listener for Next Page events
* @property isNextPagingEnabled Enable or disable swiping to the next page.
*/
class AppIntroViewPager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) {
var isFullPagingEnabled = true
var lockPage = 0
var onNextPageRequestedListener: OnNextPageRequestedListener? = null
var isNextPagingEnabled: Boolean = true
set(value) {
field = value
if (!value) {
lockPage = currentItem
}
}
private var currentTouchDownX: Float = 0.toFloat()
private var illegallyRequestedNextPageLastCalled: Long = 0
private var customScroller: ScrollerCustomDuration? = null
private var pageChangeListener: ViewPager.OnPageChangeListener? = null
init {
// Override the Scroller instance with our own class so we can change the duration
try {
val scroller = ViewPager::class.java.getDeclaredField("mScroller")
scroller.isAccessible = true
val interpolator = ViewPager::class.java.getDeclaredField("sInterpolator")
interpolator.isAccessible = true
customScroller = ScrollerCustomDuration(context, interpolator.get(null) as Interpolator)
scroller.set(this, customScroller)
} catch (e: NoSuchFieldException) {
e.printStackTrace()
}
}
internal fun addOnPageChangeListener(listener: AppIntroBase.OnPageChangeListener) {
super.addOnPageChangeListener(listener)
this.pageChangeListener = listener
}
fun goToNextSlide() {
currentItem += if (!LayoutUtil.isRtl(context)) 1 else -1
}
fun goToPreviousSlide() {
currentItem += if (!LayoutUtil.isRtl(context)) -1 else 1
}
fun isFirstSlide(size: Int): Boolean {
return if (LayoutUtil.isRtl(context)) (currentItem - size + 1 == 0) else (currentItem == 0)
}
fun getNextItem(size: Int): Int {
return if (LayoutUtil.isRtl(context)) (size - currentItem) else currentItem + 1
}
/**
* Override is required to trigger [OnPageChangeListener.onPageSelected] for the first page.
* This is needed to correctly handle progress button display after rotation on a locked first page.
*/
override fun setCurrentItem(currentItem: Int) {
val oldItem = super.getCurrentItem()
super.setCurrentItem(currentItem)
// When you pass set current item to 0,
// The pageChangeListener won't be called so we call it on our own
if (oldItem == 0 && currentItem == 0) {
pageChangeListener?.onPageSelected(0)
}
}
/**
* Set the factor by which the Scrolling duration will change.
*/
fun setScrollDurationFactor(factor: Double) {
customScroller?.scrollDurationFactor = factor
}
override fun performClick() = super.performClick()
override fun onTouchEvent(event: MotionEvent?): Boolean {
// If paging is disabled we should ignore any viewpager touch
// (also, not display any error message)
if (!isFullPagingEnabled) {
return false
}
val canRequestNextPage = onNextPageRequestedListener?.onCanRequestNextPage() ?: true
when (event?.action) {
MotionEvent.ACTION_UP -> performClick()
MotionEvent.ACTION_DOWN -> currentTouchDownX = event.x
MotionEvent.ACTION_MOVE -> {
// If user can't request the page, we shortcircuit the ACTION_MOVE logic here.
// We need to return false, and also call onIllegallyRequestedNextPage if the
// threshold was too high (so the user can be informed).
if (!canRequestNextPage) {
if (userIllegallyRequestNextPage(event)) {
onNextPageRequestedListener?.onIllegallyRequestedNextPage()
}
return false
}
}
}
// Calling super will allow the slider to "work" left and right.
return super.onTouchEvent(event)
}
/**
* Util function to check if the user Illegaly request a swipe.
* Also checks if the event happened not earlier than every 1000ms
*/
private fun userIllegallyRequestNextPage(event: MotionEvent): Boolean {
if (Math.abs(event.x - currentTouchDownX) >= VALID_SWIPE_THRESHOLD_PX) {
if (System.currentTimeMillis() - illegallyRequestedNextPageLastCalled >=
ON_ILLEGALLY_REQUESTED_NEXT_PAGE_MAX_INTERVAL
) {
illegallyRequestedNextPageLastCalled = System.currentTimeMillis()
return true
}
}
return false
}
/**
* Register an instance of OnNextPageRequestedListener.
* Before the user swipes to the next page, this listener will be called and
* can interrupt swiping by returning false to [onCanRequestNextPage]
*
* [onIllegallyRequestedNextPage] will be called if the user tries to swipe and was not allowed
* to do so (useful for showing a toast or something similar).
*/
interface OnNextPageRequestedListener {
fun onCanRequestNextPage(): Boolean
fun onIllegallyRequestedNextPage()
}
}
| apache-2.0 | fddcd4c74c8092e208c5707a1e908e38 | 37.144654 | 104 | 0.665787 | 4.836523 | false | false | false | false |
googlearchive/background-tasks-samples | WorkManager/lib/src/main/java/com/example/background/workers/BaseFilterWorker.kt | 1 | 4370 | package com.example.background.workers
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.example.background.Constants
import java.io.*
import java.util.*
abstract class BaseFilterWorker(context: Context, parameters: WorkerParameters)
: CoroutineWorker(context, parameters) {
companion object {
const val TAG = "BaseFilterWorker"
const val ASSET_PREFIX = "file:///android_asset/"
/**
* Creates an input stream which can be used to read the given `resourceUri`.
*
* @param context the application [Context].
* @param resourceUri the [String] resourceUri.
* @return the [InputStream] for the resourceUri.
*/
@VisibleForTesting
@Throws(IOException::class)
fun inputStreamFor(
context: Context,
resourceUri: String): InputStream? {
// If the resourceUri is an Android asset URI, then use AssetManager to get a handle to
// the input stream. (Stock Images are Asset URIs).
if (resourceUri.startsWith(ASSET_PREFIX)) {
val assetManager = context.resources.assets
return assetManager.open(resourceUri.substring(ASSET_PREFIX.length))
} else {
// Not an Android asset Uri. Use a ContentResolver to get a handle to the input stream.
val resolver = context.contentResolver
return resolver.openInputStream(Uri.parse(resourceUri))
}
}
}
override suspend fun doWork(): Result {
val resourceUri = inputData.getString(Constants.KEY_IMAGE_URI)
try {
if (TextUtils.isEmpty(resourceUri)) {
Log.e(TAG, "Invalid input uri")
throw IllegalArgumentException("Invalid input uri")
}
val context = applicationContext
val inputStream = inputStreamFor(context, resourceUri!!)
val bitmap = BitmapFactory.decodeStream(inputStream)
val output = applyFilter(bitmap)
// write bitmap to a file and set the output
val outputUri = writeBitmapToFile(applicationContext, output)
return Result.success(workDataOf(Constants.KEY_IMAGE_URI to outputUri.toString()))
} catch (fileNotFoundException: FileNotFoundException) {
Log.e(TAG, "Failed to decode input stream", fileNotFoundException)
throw RuntimeException("Failed to decode input stream", fileNotFoundException)
} catch (throwable: Throwable) {
Log.e(TAG, "Error applying filter", throwable)
return Result.failure()
}
}
abstract fun applyFilter(input: Bitmap): Bitmap
/**
* Writes a given [Bitmap] to the [Context.getFilesDir] directory.
*
* @param applicationContext the application [Context].
* @param bitmap the [Bitmap] which needs to be written to the files
* directory.
* @return a [Uri] to the output [Bitmap].
*/
@Throws(FileNotFoundException::class)
private fun writeBitmapToFile(
applicationContext: Context,
bitmap: Bitmap): Uri {
// Bitmaps are being written to a temporary directory. This is so they can serve as inputs
// for workers downstream, via Worker chaining.
val name = String.format("filter-output-%s.png", UUID.randomUUID().toString())
val outputDir = File(applicationContext.filesDir, Constants.OUTPUT_PATH)
if (!outputDir.exists()) {
outputDir.mkdirs() // should succeed
}
val outputFile = File(outputDir, name)
var out: FileOutputStream? = null
try {
out = FileOutputStream(outputFile)
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* ignored for PNG */, out)
} finally {
if (out != null) {
try {
out.close()
} catch (ignore: IOException) {
}
}
}
return Uri.fromFile(outputFile)
}
}
| apache-2.0 | 3f7221b7861782eee1f575f79bc8500c | 38.369369 | 103 | 0.627689 | 5.052023 | false | false | false | false |
sxend/FrameworkBenchmarks | frameworks/Kotlin/http4k/core/src/main/kotlin/WorldRoutes.kt | 8 | 1041 |
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.with
import org.http4k.format.Jackson.array
import org.http4k.format.Jackson.json
import org.http4k.lens.Query
import org.http4k.routing.bind
import java.lang.Math.max
import java.lang.Math.min
object WorldRoutes {
private val jsonBody = Body.json().toLens()
private val numberOfQueries = Query.map {
try {
min(max(it.toInt(), 1), 500)
} catch (e: Exception) {
1
}
}.defaulted("queries", 1)
fun queryRoute(db: Database) = "/db" bind GET to {
let { Response(OK).with(jsonBody of db.findWorld()) }
}
fun multipleRoute(db: Database) = "/queries" bind GET to {
Response(OK).with(jsonBody of array(db.findWorlds(numberOfQueries(it))))
}
fun updateRoute(db: Database) = "/updates" bind GET to {
Response(OK).with(jsonBody of array(db.updateWorlds(numberOfQueries(it))))
}
} | bsd-3-clause | cfeed122c1e7aef1ceb2f97216074ae6 | 27.944444 | 82 | 0.673391 | 3.368932 | false | false | false | false |
sakuna63/requery | requery-kotlin/src/main/kotlin/io/requery/sql/KotlinEntityDataStore.kt | 1 | 6690 | /*
* Copyright 2016 requery.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.requery.sql
import io.requery.Persistable
import io.requery.TransactionIsolation
import io.requery.kotlin.*
import io.requery.meta.Attribute
import io.requery.meta.EntityModel
import io.requery.query.Expression
import io.requery.query.Result
import io.requery.query.Scalar
import io.requery.query.Tuple
import io.requery.query.element.QueryType
import io.requery.query.function.Count
import java.util.Arrays
import java.util.LinkedHashSet
import kotlin.reflect.KClass
/**
* Concrete implementation of [BlockingEntityStore] connecting to SQL database.
*
* @author Nikhil Purushe
*/
class KotlinEntityDataStore<T : Persistable>(configuration: Configuration) : BlockingEntityStore<T> {
private var data: EntityDataStore<T> = EntityDataStore(configuration)
private var context : EntityContext<T> = data.context()
private var model : EntityModel = configuration.model
override fun close() = data.close()
override fun delete(): Deletion<Scalar<Int>> =
QueryDelegate(QueryType.DELETE, model, UpdateOperation(context))
override infix fun <E : T> select(type: KClass<E>): Selection<Result<E>> {
val reader = context.read<E>(type.java)
val selection: Set<Expression<*>> = reader.defaultSelection()
val resultReader = reader.newResultReader(reader.defaultSelectionAttributes())
val query = QueryDelegate(QueryType.SELECT, model, SelectOperation(context, resultReader))
query.select(*selection.toTypedArray()).from(type)
return query
}
override fun <E : T> select(vararg attributes: QueryableAttribute<E, *>): Selection<Result<E>> {
if (attributes.isEmpty()) {
throw IllegalArgumentException()
}
val classType = attributes[0].declaringType.classType
val reader = context.read<E>(classType)
val selection: Set<Expression<*>> = LinkedHashSet(Arrays.asList<Expression<*>>(*attributes))
val resultReader = reader.newResultReader(attributes)
val query = QueryDelegate(QueryType.SELECT, model, SelectOperation(context, resultReader))
query.select(*selection.toTypedArray()).from(classType)
return query
}
override fun select(vararg expressions: Expression<*>): Selection<Result<Tuple>> {
val reader = TupleResultReader(context)
val select = SelectOperation(context, reader)
return QueryDelegate(QueryType.SELECT, model, select).select(*expressions)
}
override fun <E : T> insert(type: KClass<E>): Insertion<Result<Tuple>> {
val entityType = context.model.typeOf<E>(type.java)
val selection = LinkedHashSet<Expression<*>>()
entityType.keyAttributes.forEach { attribute -> selection.add(attribute as Expression<*>) }
val operation = InsertReturningOperation(context, selection)
val query = QueryDelegate<Result<Tuple>>(QueryType.INSERT, model, operation)
query.from(type)
return query
}
override fun <E : T> update(type: KClass<E>): Update<Scalar<Int>> =
QueryDelegate(QueryType.UPDATE, model, UpdateOperation(context))
override fun <E : T> delete(type: KClass<E>): Deletion<Scalar<Int>> {
val query = QueryDelegate(QueryType.DELETE, model, UpdateOperation(context))
query.from(type)
return query
}
override fun <E : T> count(type: KClass<E>): Selection<Scalar<Int>> {
val operation = SelectCountOperation(context)
val query = QueryDelegate<Scalar<Int>>(QueryType.SELECT, model, operation)
query.select(Count.count(type.java)).from(type)
return query
}
override fun count(vararg attributes: QueryableAttribute<T, *>): Selection<Scalar<Int>> {
val operation = SelectCountOperation(context)
return QueryDelegate<Scalar<Int>>(QueryType.SELECT, model, operation)
.select(Count.count(*attributes))
}
override fun update(): Update<Scalar<Int>> =
QueryDelegate(QueryType.UPDATE, model, UpdateOperation(context))
override fun <E : T> insert(entity: E): E = data.insert(entity)
override fun <E : T> insert(entities: Iterable<E>): Iterable<E> = data.insert(entities)
override fun <K : Any, E : T> insert(entity: E, keyClass: KClass<K>): K =
data.insert(entity, keyClass.java)
override fun <K : Any, E : T> insert(entities: Iterable<E>, keyClass: KClass<K>): Iterable<K> =
data.insert(entities, keyClass.java)
override fun <E : T> update(entity: E): E = data.update(entity)
override fun <E : T> update(entities: Iterable<E>): Iterable<E> = data.update(entities)
override fun <E : T> upsert(entity: E): E = data.upsert(entity)
override fun <E : T> upsert(entities: Iterable<E>): Iterable<E> = data.upsert(entities)
override fun <E : T> refresh(entity: E): E = data.refresh(entity)
override fun <E : T> refresh(entity: E, vararg attributes: Attribute<*, *>): E =
data.refresh(entity, *attributes)
override fun <E : T> refresh(entities: Iterable<E>, vararg attributes: Attribute<*, *>): Iterable<E> =
data.refresh(entities, *attributes)
override fun <E : T> refreshAll(entity: E): E = data.refreshAll(entity)
override fun <E : T> delete(entity: E): Void = data.delete(entity)
override fun <E : T> delete(entities: Iterable<E>): Void = data.delete(entities)
override fun <E : T, K> findByKey(type: KClass<E>, key: K): E = data.findByKey(type.java, key)
override fun <V> withTransaction(body: BlockingEntityStore<T>.() -> V): V {
try {
data.transaction().begin()
return body()
} finally {
data.transaction().close()
}
}
override fun <V> withTransaction(isolation: TransactionIsolation,
body: BlockingEntityStore<T>.() -> V): V {
try {
data.transaction().begin(isolation)
return body()
} finally {
data.transaction().close()
}
}
override fun toBlocking(): BlockingEntityStore<T> = this
}
| apache-2.0 | a38d673a31bc3c7e36f0fd7622fa1791 | 41.075472 | 106 | 0.673543 | 4.17603 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/sync/MessengerNotifications.kt | 1 | 10661 | package me.proxer.app.chat.prv.sync
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Typeface
import android.os.Build
import android.text.SpannableString
import android.text.style.StyleSpan
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.Person
import androidx.core.app.RemoteInput
import androidx.core.app.TaskStackBuilder
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.text.set
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorRes
import com.mikepenz.iconics.utils.sizeDp
import me.proxer.app.MainActivity
import me.proxer.app.R
import me.proxer.app.auth.LocalUser
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.prv.PrvMessengerActivity
import me.proxer.app.util.NotificationUtils.CHAT_CHANNEL
import me.proxer.app.util.Utils
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.LocalConferenceMap
import me.proxer.app.util.extension.getQuantityString
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.wrapper.MaterialDrawerWrapper.DrawerItem
import me.proxer.library.enums.Device
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
object MessengerNotifications {
private const val GROUP = "chat"
private const val ID = 782_373_275
private val storageHelper by safeInject<StorageHelper>()
fun showOrUpdate(context: Context, conferenceMap: LocalConferenceMap) {
val notifications = conferenceMap.entries
.asSequence()
.sortedBy { it.key.date }
.map { (conference, messages) ->
conference.id.toInt() to when {
messages.isEmpty() -> null
else -> buildIndividualChatNotification(context, conference, messages)
}
}
.plus(ID to buildChatSummaryNotification(context, conferenceMap))
.toList()
notifications.forEach { (id, notification) ->
when (notification) {
null -> NotificationManagerCompat.from(context).cancel(id)
else -> NotificationManagerCompat.from(context).notify(id, notification)
}
}
}
fun cancel(context: Context) = NotificationManagerCompat.from(context).cancel(ID)
private fun buildChatSummaryNotification(context: Context, conferenceMap: LocalConferenceMap): Notification? {
val filteredConferenceMap = conferenceMap.filter { (_, messages) -> messages.isNotEmpty() }
if (filteredConferenceMap.isEmpty()) {
return null
}
val messageAmount = filteredConferenceMap.values.sumBy { it.size }
val conferenceAmount = filteredConferenceMap.size
val messageAmountText = context.getQuantityString(R.plurals.notification_chat_message_amount, messageAmount)
val conferenceAmountText = context.getQuantityString(
R.plurals.notification_chat_conference_amount,
conferenceAmount
)
val title = context.getString(R.string.app_name)
val content = "$messageAmountText $conferenceAmountText"
val style = buildSummaryStyle(title, content, filteredConferenceMap)
val shouldAlert = conferenceMap.keys
.map { it.date }
.maxByOrNull { it }
?.isAfter(storageHelper.lastChatMessageDate)
?: true
return NotificationCompat.Builder(context, CHAT_CHANNEL)
.setSmallIcon(R.drawable.ic_stat_proxer)
.setContentTitle(title)
.setContentText(content)
.setStyle(style)
.setContentIntent(
TaskStackBuilder.create(context)
.addNextIntent(MainActivity.getSectionIntent(context, DrawerItem.MESSENGER))
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
)
.setDefaults(Notification.DEFAULT_ALL)
.setColor(ContextCompat.getColor(context, R.color.primary))
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setNumber(conferenceAmount)
.setGroup(GROUP)
.setOnlyAlertOnce(!shouldAlert)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setGroupSummary(true)
.setAutoCancel(true)
.build()
}
private fun buildSummaryStyle(
title: String,
content: String,
filteredConferenceMap: LocalConferenceMap
) = NotificationCompat.InboxStyle()
.setBigContentTitle(title)
.setSummaryText(content)
.also {
filteredConferenceMap.forEach { (conference, messages) ->
messages.firstOrNull()?.also { message ->
val sender = when {
conference.isGroup -> "${conference.topic}: ${message.username} "
else -> "${conference.topic} "
}
it.addLine(
SpannableString(sender + message.message).apply {
this[0..sender.length] = StyleSpan(Typeface.BOLD)
}
)
}
}
}
private fun buildIndividualChatNotification(
context: Context,
conference: LocalConference,
messages: List<LocalMessage>
): Notification? {
val user = storageHelper.user
if (messages.isEmpty() || user == null) {
return null
}
val content = when (messages.size) {
1 -> messages.first().message
else -> context.getQuantityString(R.plurals.notification_chat_message_amount, messages.size)
}
val conferenceIcon = buildConferenceIcon(context, conference)
val style = buildIndividualStyle(context, messages, conference, user, conferenceIcon)
val intent = TaskStackBuilder.create(context)
.addNextIntent(MainActivity.getSectionIntent(context, DrawerItem.MESSENGER))
.addNextIntent(PrvMessengerActivity.getIntent(context, conference))
.getPendingIntent(conference.id.toInt(), PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(context, CHAT_CHANNEL)
.setSmallIcon(R.drawable.ic_stat_proxer)
.setContentTitle(if (conference.isGroup) conference.topic else "")
.setContentText(content)
.setLargeIcon(conferenceIcon)
.setStyle(style)
.setContentIntent(intent)
.setColor(ContextCompat.getColor(context, R.color.primary))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setGroup(GROUP)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setAutoCancel(true)
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val remoteInput = RemoteInput.Builder(DirectReplyReceiver.REMOTE_REPLY_EXTRA)
.setLabel(context.getString(R.string.action_answer))
.build()
val replyIntent = DirectReplyReceiver.getPendingIntent(context, conference.id)
val actionReplyByRemoteInput = NotificationCompat.Action.Builder(
R.mipmap.ic_launcher,
context.getString(R.string.action_answer),
replyIntent
)
.addRemoteInput(remoteInput)
.setAllowGeneratedReplies(true)
.build()
addAction(actionReplyByRemoteInput)
}
}
.addAction(
R.drawable.ic_stat_check,
context.getString(R.string.notification_chat_read_action),
MessengerNotificationReadReceiver.getPendingIntent(context, conference.id)
)
.build()
}
private fun buildConferenceIcon(context: Context, conference: LocalConference) = when {
conference.image.isNotBlank() -> Utils.getCircleBitmapFromUrl(context, ProxerUrls.userImage(conference.image))
else -> buildGenericIcon(context, conference.isGroup)
}
private fun buildIndividualStyle(
context: Context,
messages: List<LocalMessage>,
conference: LocalConference,
user: LocalUser,
conferenceIcon: Bitmap?
): NotificationCompat.MessagingStyle {
val personImage = when {
user.image.isNotBlank() -> Utils.getCircleBitmapFromUrl(context, ProxerUrls.userImage(user.image))
else -> buildGenericIcon(context, false)
}
val person = Person.Builder()
.setKey(user.id)
.setName(user.name)
.setIcon(personImage?.toIconCompat())
.build()
return NotificationCompat.MessagingStyle(person)
.setGroupConversation(conference.isGroup)
.setConversationTitle(if (conference.isGroup) conference.topic else "")
.also {
messages.forEach { message ->
val messagePersonIcon = when (message.userId) {
user.id -> personImage
else -> conferenceIcon
}
val messagePerson = Person.Builder()
.setKey(message.userId)
.setName(message.username)
.setIcon(messagePersonIcon?.toIconCompat())
.setUri(ProxerUrls.userWeb(message.userId, Device.MOBILE).toString())
.build()
it.addMessage(message.message, message.date.toEpochMilli(), messagePerson)
}
}
}
private fun buildGenericIcon(context: Context, isGroup: Boolean) = IconicsDrawable(context).apply {
icon = when (isGroup) {
true -> CommunityMaterial.Icon.cmd_account_multiple
false -> CommunityMaterial.Icon.cmd_account
}
colorRes = R.color.primary
sizeDp = 96
}.toBitmap()
private fun Bitmap.toIconCompat() = IconCompat.createWithBitmap(this)
}
| gpl-3.0 | 1ee55e6da6e4e79f4f1e892aaf691865 | 39.382576 | 118 | 0.63146 | 5.067015 | false | false | false | false |
vmmaldonadoz/android-reddit-example | Reddit/app/src/main/java/com/thirdmono/reddit/data/entity/SubReddit.kt | 1 | 3810 | package com.thirdmono.reddit.data.entity
import com.google.gson.annotations.SerializedName
data class SubReddit(
@SerializedName("banner_img")
val bannerImg: String? = null,
@SerializedName("user_sr_theme_enabled")
val userSrThemeEnabled: Boolean? = null,
@SerializedName("submit_text_html")
val submitTextHtml: String? = null,
@SerializedName("user_is_banned")
val userIsBanned: Any? = null,
@SerializedName("wiki_enabled")
val wikiEnabled: Boolean? = null,
@SerializedName("show_media")
val showMedia: Boolean? = null,
@SerializedName("id")
val id: String? = null,
@SerializedName("submit_text")
val submitText: String? = null,
@SerializedName("display_name")
val displayName: String? = null,
@SerializedName("header_img")
val headerImg: String? = null,
@SerializedName("description_html")
val descriptionHtml: String? = null,
@SerializedName("title")
val title: String? = null,
@SerializedName("collapse_deleted_comments")
val collapseDeletedComments: Boolean? = null,
@SerializedName("over18")
val over18: Boolean? = null,
@SerializedName("public_description_html")
val publicDescriptionHtml: String? = null,
@SerializedName("spoilers_enabled")
val spoilersEnabled: Boolean? = null,
@SerializedName("icon_size")
val iconSize: List<Int>? = null,
@SerializedName("suggested_comment_sort")
val suggestedCommentSort: Any? = null,
@SerializedName("icon_img")
val iconImg: String? = null,
@SerializedName("header_title")
val headerTitle: String? = null,
@SerializedName("description")
val description: String? = null,
@SerializedName("user_is_muted")
val userIsMuted: Any? = null,
@SerializedName("submit_link_label")
val submitLinkLabel: Any? = null,
@SerializedName("accounts_active")
val accountsActive: Any? = null,
@SerializedName("public_traffic")
val publicTraffic: Boolean? = null,
@SerializedName("header_size")
val headerSize: List<Int>? = null,
@SerializedName("subscribers")
val subscribers: Int? = null,
@SerializedName("submit_text_label")
val submitTextLabel: Any? = null,
@SerializedName("lang")
val lang: String? = null,
@SerializedName("user_is_moderator")
val userIsModerator: Any? = null,
@SerializedName("key_color")
val keyColor: String? = null,
@SerializedName("name")
val name: String? = null,
@SerializedName("created")
val created: Double? = null,
@SerializedName("url")
val url: String? = null,
@SerializedName("quarantine")
val quarantine: Boolean? = null,
@SerializedName("hide_ads")
val hideAds: Boolean? = null,
@SerializedName("created_utc")
val createdUtc: Double? = null,
@SerializedName("banner_size")
val bannerSize: Any? = null,
@SerializedName("user_is_contributor")
val userIsContributor: Any? = null,
@SerializedName("public_description")
val publicDescription: String? = null,
@SerializedName("show_media_preview")
val showMediaPreview: Boolean? = null,
@SerializedName("comment_score_hide_mins")
val commentScoreHideMins: Int? = null,
@SerializedName("subreddit_type")
val subredditType: String? = null,
@SerializedName("submission_type")
val submissionType: String? = null,
@SerializedName("user_is_subscriber")
val userIsSubscriber: Any? = null
) | apache-2.0 | a52b2d029aa49d9f29e36d8834933401 | 38.697917 | 53 | 0.614698 | 4.430233 | false | false | false | false |
thomasvolk/alkali | src/main/kotlin/net/t53k/alkali/actors/Reaper.kt | 1 | 1583 | /*
* Copyright 2017 Thomas Volk
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package net.t53k.alkali.actors
import net.t53k.alkali.Actor
import net.t53k.alkali.ActorReference
import net.t53k.alkali.Terminated
class Reaper(val starter: Reaper.() -> Unit): Actor() {
private val actors = mutableListOf<ActorReference>()
override fun <T : Actor> actor(name: String, actor: T): ActorReference {
val actorRef = super.actor(name, actor)
actors += actorRef
return actorRef
}
override fun before() {
starter()
}
override fun receive(message: Any) {
when(message) {
Terminated -> {
actors -= sender()
if(actors.size == 0) {
system().shutdown()
}
}
}
}
} | apache-2.0 | 3e99de884a37c92cdc66b0ebe8206e51 | 30.68 | 76 | 0.658876 | 4.187831 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/instagram/InstagramAuthFlow.kt | 1 | 1407 | package com.baulsupp.okurl.services.instagram
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.kotlin.queryMap
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
object InstagramAuthFlow {
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String,
scopes: Iterable<String>
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val loginUrl =
"https://api.instagram.com/oauth/authorize/?client_id=$clientId&response_type=code&redirect_uri=${s.redirectUri}&scope=${scopes.joinToString(
"+"
)}"
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val tokenUrl = "https://api.instagram.com/oauth/access_token"
val body = FormBody.Builder().add("client_id", clientId)
.add("redirect_uri", s.redirectUri)
.add("client_secret", clientSecret)
.add("code", code)
.add("grant_type", "authorization_code")
.build()
val request = Request.Builder().url(tokenUrl).method("POST", body).build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(responseMap["access_token"] as String)
}
}
}
| apache-2.0 | a5c567e8d0277c9601c7767200dc809e | 30.266667 | 149 | 0.69936 | 4.043103 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/navigation/MainActivityNavigation.kt | 1 | 13262 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.navigation
import android.os.Build
import android.os.Bundle
import org.mozilla.focus.R
import org.mozilla.focus.activity.MainActivity
import org.mozilla.focus.autocomplete.AutocompleteAddFragment
import org.mozilla.focus.autocomplete.AutocompleteListFragment
import org.mozilla.focus.autocomplete.AutocompleteRemoveFragment
import org.mozilla.focus.autocomplete.AutocompleteSettingsFragment
import org.mozilla.focus.biometrics.BiometricAuthenticationFragment
import org.mozilla.focus.cookiebanner.CookieBannerFragment
import org.mozilla.focus.exceptions.ExceptionsListFragment
import org.mozilla.focus.exceptions.ExceptionsRemoveFragment
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.settings
import org.mozilla.focus.fragment.BrowserFragment
import org.mozilla.focus.fragment.FirstrunFragment
import org.mozilla.focus.fragment.UrlInputFragment
import org.mozilla.focus.fragment.about.AboutFragment
import org.mozilla.focus.fragment.onboarding.OnboardingFirstFragment
import org.mozilla.focus.fragment.onboarding.OnboardingSecondFragment
import org.mozilla.focus.fragment.onboarding.OnboardingStep
import org.mozilla.focus.fragment.onboarding.OnboardingStorage
import org.mozilla.focus.locale.screen.LanguageFragment
import org.mozilla.focus.nimbus.FocusNimbus
import org.mozilla.focus.nimbus.Onboarding
import org.mozilla.focus.searchwidget.SearchWidgetUtils
import org.mozilla.focus.settings.GeneralSettingsFragment
import org.mozilla.focus.settings.InstalledSearchEnginesSettingsFragment
import org.mozilla.focus.settings.ManualAddSearchEngineSettingsFragment
import org.mozilla.focus.settings.MozillaSettingsFragment
import org.mozilla.focus.settings.RemoveSearchEnginesSettingsFragment
import org.mozilla.focus.settings.SearchSettingsFragment
import org.mozilla.focus.settings.SettingsFragment
import org.mozilla.focus.settings.advanced.AdvancedSettingsFragment
import org.mozilla.focus.settings.advanced.SecretSettingsFragment
import org.mozilla.focus.settings.permissions.SitePermissionsFragment
import org.mozilla.focus.settings.permissions.permissionoptions.SitePermission
import org.mozilla.focus.settings.permissions.permissionoptions.SitePermissionOptionsFragment
import org.mozilla.focus.settings.privacy.PrivacySecuritySettingsFragment
import org.mozilla.focus.settings.privacy.studies.StudiesFragment
import org.mozilla.focus.state.AppAction
import org.mozilla.focus.state.Screen
import org.mozilla.focus.utils.ViewUtils
import kotlin.collections.forEach as withEach
/**
* Class performing the actual navigation in [MainActivity] by performing fragment transactions if
* needed.
*/
@Suppress("TooManyFunctions")
class MainActivityNavigation(
private val activity: MainActivity,
) {
/**
* Home screen.
*/
fun home() {
val fragmentManager = activity.supportFragmentManager
val browserFragment = fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG) as BrowserFragment?
val isShowingBrowser = browserFragment != null
val crashReporterIsVisible = browserFragment?.crashReporterIsVisible() ?: false
if (isShowingBrowser && !crashReporterIsVisible) {
showPromoteSearchWidgetDialogOrBrandedSnackbar()
}
// We add the url input fragment to the layout if it doesn't exist yet.
val transaction = fragmentManager
.beginTransaction()
// We only want to play the animation if a browser fragment is added and resumed.
// If it is not resumed then the application is currently in the process of resuming
// and the session was removed while the app was in the background (e.g. via the
// notification). In this case we do not want to show the content and remove the
// browser fragment immediately.
val shouldAnimate = isShowingBrowser && browserFragment!!.isResumed
if (shouldAnimate) {
transaction.setCustomAnimations(0, R.anim.erase_animation)
}
showStartBrowsingCfr()
// Currently this callback can get invoked while the app is in the background. Therefore we are using
// commitAllowingStateLoss() here because we can't do a fragment transaction while the app is in the
// background - like we already do in showBrowserScreenForCurrentSession().
// Ideally we'd make it possible to pause observers while the app is in the background:
// https://github.com/mozilla-mobile/android-components/issues/876
transaction
.replace(
R.id.container,
UrlInputFragment.createWithoutSession(),
UrlInputFragment.FRAGMENT_TAG,
)
.commitAllowingStateLoss()
}
private fun showStartBrowsingCfr() {
val onboardingConfig = FocusNimbus.features.onboarding.value(activity)
if (
onboardingConfig.isCfrEnabled &&
!activity.settings.isFirstRun &&
activity.settings.shouldShowStartBrowsingCfr
) {
FocusNimbus.features.onboarding.recordExposure()
activity.components.appStore.dispatch(AppAction.ShowStartBrowsingCfrChange(true))
}
}
/**
* Display the widget promo at first data clearing action and if it wasn't added after 5th Focus session
* or display branded snackbar when widget promo is not shown.
*/
@Suppress("MagicNumber")
private fun showPromoteSearchWidgetDialogOrBrandedSnackbar() {
val onboardingFeature = FocusNimbus.features.onboarding
val onboardingConfig = onboardingFeature.value(activity)
val clearBrowsingSessions = activity.components.settings.getClearBrowsingSessions()
activity.components.settings.addClearBrowsingSessions(1)
if (shouldShowPromoteSearchWidgetDialog(onboardingConfig) &&
(
clearBrowsingSessions == 0 || clearBrowsingSessions == 4
)
) {
onboardingFeature.recordExposure()
SearchWidgetUtils.showPromoteSearchWidgetDialog(activity)
} else {
ViewUtils.showBrandedSnackbar(
activity.findViewById(android.R.id.content),
R.string.feedback_erase2,
activity.resources.getInteger(R.integer.erase_snackbar_delay),
)
}
}
private fun shouldShowPromoteSearchWidgetDialog(onboadingConfig: Onboarding): Boolean {
return (
onboadingConfig.isPromoteSearchWidgetDialogEnabled &&
!activity.components.settings.searchWidgetInstalled
)
}
/**
* Show browser for tab with the given [tabId].
*/
fun browser(tabId: String) {
val fragmentManager = activity.supportFragmentManager
val urlInputFragment = fragmentManager.findFragmentByTag(UrlInputFragment.FRAGMENT_TAG) as UrlInputFragment?
if (urlInputFragment != null) {
fragmentManager
.beginTransaction()
.remove(urlInputFragment)
.commitAllowingStateLoss()
}
val browserFragment = fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG) as BrowserFragment?
if (browserFragment == null || browserFragment.tab.id != tabId) {
fragmentManager
.beginTransaction()
.replace(R.id.container, BrowserFragment.createForTab(tabId), BrowserFragment.FRAGMENT_TAG)
.commitAllowingStateLoss()
}
}
/**
* Edit URL of tab with the given [tabId].
*/
fun edit(
tabId: String,
) {
val fragmentManager = activity.supportFragmentManager
val urlInputFragment = fragmentManager.findFragmentByTag(UrlInputFragment.FRAGMENT_TAG) as UrlInputFragment?
if (urlInputFragment != null && urlInputFragment.tab?.id == tabId) {
// There's already an UrlInputFragment for this tab.
return
}
val urlFragment = UrlInputFragment.createWithTab(tabId)
fragmentManager
.beginTransaction()
.add(R.id.container, urlFragment, UrlInputFragment.FRAGMENT_TAG)
.commit()
}
/**
* Show first run onBoarding.
*/
fun firstRun() {
val onboardingFragment = if (activity.settings.isNewOnboardingEnable) {
FocusNimbus.features.onboarding.recordExposure()
val onBoardingStorage = OnboardingStorage(activity)
when (onBoardingStorage.getCurrentOnboardingStep()) {
OnboardingStep.ON_BOARDING_FIRST_SCREEN -> {
OnboardingFirstFragment()
}
OnboardingStep.ON_BOARDING_SECOND_SCREEN -> {
OnboardingSecondFragment()
}
}
} else {
FirstrunFragment.create()
}
activity.supportFragmentManager
.beginTransaction()
.replace(R.id.container, onboardingFragment, onboardingFragment::class.java.simpleName)
.commit()
}
fun showOnBoardingSecondScreen() {
activity.supportFragmentManager
.beginTransaction()
.replace(R.id.container, OnboardingSecondFragment(), OnboardingSecondFragment::class.java.simpleName)
.commit()
}
/**
* Lock app.
*
* @param bundle it is used for app navigation. If the user can unlock with success he should
* be redirected to a certain screen. It comes from the external intent.
*/
fun lock(bundle: Bundle? = null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw IllegalStateException("Trying to lock unsupported device")
}
val fragmentManager = activity.supportFragmentManager
if (fragmentManager.findFragmentByTag(BiometricAuthenticationFragment.FRAGMENT_TAG) != null) {
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && activity.isInPictureInPictureMode) {
return
}
val transaction = fragmentManager
.beginTransaction()
fragmentManager.fragments.withEach { fragment ->
transaction.remove(fragment)
}
fragmentManager
.beginTransaction()
.replace(
R.id.container,
BiometricAuthenticationFragment.createWithDestinationData(bundle),
BiometricAuthenticationFragment.FRAGMENT_TAG,
)
.commit()
}
@Suppress("ComplexMethod")
fun settings(page: Screen.Settings.Page) {
val fragment = when (page) {
Screen.Settings.Page.Start -> SettingsFragment()
Screen.Settings.Page.General -> GeneralSettingsFragment()
Screen.Settings.Page.Privacy -> PrivacySecuritySettingsFragment()
Screen.Settings.Page.Search -> SearchSettingsFragment()
Screen.Settings.Page.Advanced -> AdvancedSettingsFragment()
Screen.Settings.Page.Mozilla -> MozillaSettingsFragment()
Screen.Settings.Page.PrivacyExceptions -> ExceptionsListFragment()
Screen.Settings.Page.PrivacyExceptionsRemove -> ExceptionsRemoveFragment()
Screen.Settings.Page.SitePermissions -> SitePermissionsFragment()
Screen.Settings.Page.Studies -> StudiesFragment()
Screen.Settings.Page.SecretSettings -> SecretSettingsFragment()
Screen.Settings.Page.SearchList -> InstalledSearchEnginesSettingsFragment()
Screen.Settings.Page.SearchRemove -> RemoveSearchEnginesSettingsFragment()
Screen.Settings.Page.SearchAdd -> ManualAddSearchEngineSettingsFragment()
Screen.Settings.Page.SearchAutocomplete -> AutocompleteSettingsFragment()
Screen.Settings.Page.SearchAutocompleteList -> AutocompleteListFragment()
Screen.Settings.Page.SearchAutocompleteAdd -> AutocompleteAddFragment()
Screen.Settings.Page.SearchAutocompleteRemove -> AutocompleteRemoveFragment()
Screen.Settings.Page.About -> AboutFragment()
Screen.Settings.Page.Locale -> LanguageFragment()
Screen.Settings.Page.CookieBanner -> CookieBannerFragment()
}
val tag = "settings_" + fragment::class.java.simpleName
val fragmentManager = activity.supportFragmentManager
if (fragmentManager.findFragmentByTag(tag) != null) {
return
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment, tag)
.commit()
}
fun sitePermissionOptionsFragment(sitePermission: SitePermission) {
val fragmentManager = activity.supportFragmentManager
fragmentManager.beginTransaction()
.replace(
R.id.container,
SitePermissionOptionsFragment.addSitePermission(sitePermission = sitePermission),
SitePermissionOptionsFragment.FRAGMENT_TAG,
)
.commit()
}
}
| mpl-2.0 | d139e7fa6118d4d4a6301863e78b6d85 | 41.370607 | 116 | 0.694088 | 5.192639 | false | false | false | false |
epabst/kotlin-showcase | src/jsMain/kotlin/todo/ToDosScreen.kt | 1 | 4383 | package todo
import bootstrap.*
import extensions.firebase.reactbootstrap.ButtonBar
import extensions.reactbootstrap.UndoButton
import extensions.pouchdb.onChangedMap
import extensions.pouchdb.removeAllowingUndo
import react.*
import react.dom.br
import react.dom.div
import react.router.dom.RouteResultHistory
import react.router.dom.routeLink
import util.launchHandlingErrors
import pouchdb.Document
import pouchdb.core.Changes
interface ToDosProps : RProps {
var history: RouteResultHistory
}
interface ToDosState : RState {
var list: List<ToDo>?
}
/**
* UI for showing a list of ToDos.
* @author Eric Pabst ([email protected])
*/
class ToDosScreen(props: ToDosProps) : RComponent<ToDosProps, ToDosState>(props) {
private val resources = mutableListOf<Changes<*>>()
override fun ToDosState.init(props: ToDosProps) {
list = null
}
override fun componentDidMount() {
resources.add(Config.toDoDb.onChangedMap(Document<ToDoJS>::parse) { toDoById ->
setState { list = toDoById.values.toList() }
})
}
override fun componentWillUnmount() {
resources.forEach { it.cancel() }
}
private suspend fun delete(todo: ToDo) {
Config.toDoDb.removeAllowingUndo(todo, ToDoJS::toNormal)
}
override fun RBuilder.render() {
child(ButtonBar::class) {
attrs.heading = "To-Dos"
}
val list = state.list
child(Container::class) {
if (list == null) {
div { +"Loading..." }
} else {
child(Row::class) {
child(Col::class) { +"Description" }
child(Col::class) {
// +"Due Date"
}
child(Col::class) {}
}
if (list.isNotEmpty()) {
list.forEach { toDo ->
child(Card::class) {
attrs.body = true
child(Row::class) {
attrs.onClick = {
props.history.push("/toDos/${toDo.id}")
}
child(Col::class) {
div("text-left name") { +toDo.name }
}
child(Col::class) {
div("text-left name") {
+(toDo.dueDate?.toDisplayDateTimeString() ?: "")
}
}
child(Col::class) {
child(Button::class) {
attrs.variant = "secondary"
attrs.onClick =
{ it.stopPropagation(); launchHandlingErrors("delete $toDo") { delete(toDo) } }
+"Delete"
}
}
}
}
}
} else {
child(Row::class) {
child(Col::class) {
attrs.xs = 12
child(Card::class) {
attrs.body = true
+"There are no to-dos."
}
}
}
}
br {}
br {}
br {}
br {}
br {}
child(Row::class) {
child(Col::class) {
attrs.xs = 6
child(UndoButton::class) { }
}
child(Col::class) {
attrs.xs = 6
routeLink(to = "/toDos/new") {
child(Button::class) {
+"Add ToDo"
}
}
}
}
}
}
}
}
fun RBuilder.toDosScreen(history: RouteResultHistory): ReactElement = child(ToDosScreen::class) {
attrs.history = history
}
| apache-2.0 | 1dbafbe1d3c728e8dd8c214de985a1b8 | 32.458015 | 123 | 0.40178 | 5.199288 | false | false | false | false |
Ekito/koin | koin-projects/koin-core/src/test/java/org/koin/core/GlobalToScopeTest.kt | 1 | 2241 | package org.koin.core
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
import org.koin.Simple
import org.koin.core.error.NoBeanDefFoundException
import org.koin.core.logger.Level
import org.koin.core.qualifier.named
import org.koin.dsl.koinApplication
import org.koin.dsl.module
class GlobalToScopeTest {
@Test
fun `can't get scoped dependency without scope`() {
val koin = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope(named<ClosedScopeAPI.ScopeType>()) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
try {
koin.get<Simple.ComponentA>()
fail()
} catch (e: NoBeanDefFoundException) {
e.printStackTrace()
}
}
@Test
fun `can't get scoped dependency without scope from single`() {
val koin = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentB(get()) }
scope(named<ClosedScopeAPI.ScopeType>()) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
try {
koin.get<Simple.ComponentA>()
fail()
} catch (e: NoBeanDefFoundException) {
e.printStackTrace()
}
}
@Test
fun `get scoped dependency without scope from single`() {
val scopeId = "MY_SCOPE_ID"
val koin = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentB(getScope(scopeId).get()) }
scope(named<ClosedScopeAPI.ScopeType>()) {
scoped { Simple.ComponentA() }
}
}
)
}.koin
val scope = koin.createScope(scopeId, named<ClosedScopeAPI.ScopeType>())
assertEquals(koin.get<Simple.ComponentB>().a, scope.get<Simple.ComponentA>())
}
} | apache-2.0 | 73acf876869fde2ce0ce36fa6bf67f9f | 27.025 | 85 | 0.503793 | 5.013423 | false | true | false | false |
wordpress-mobile/WordPress-FluxC-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCLeaderboardsStore.kt | 1 | 5853 | package org.wordpress.android.fluxc.store
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.leaderboards.WCProductLeaderboardsMapper
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.Type.PRODUCTS
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.wc.orderstats.OrderStatsRestClient
import org.wordpress.android.fluxc.persistence.dao.TopPerformerProductsDao
import org.wordpress.android.fluxc.persistence.entity.TopPerformerProductEntity
import org.wordpress.android.fluxc.store.WCStatsStore.StatsGranularity
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.fluxc.utils.DateUtils
import org.wordpress.android.util.AppLog
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WCLeaderboardsStore @Inject constructor(
private val restClient: LeaderboardsRestClient,
private val productStore: WCProductStore,
private val mapper: WCProductLeaderboardsMapper,
private val coroutineEngine: CoroutineEngine,
private val topPerformersDao: TopPerformerProductsDao,
) {
@Suppress("Unused")
fun observeTopPerformerProducts(
siteId: Long,
datePeriod: String
): Flow<List<TopPerformerProductEntity>> =
topPerformersDao
.observeTopPerformerProducts(siteId, datePeriod)
.distinctUntilChanged()
@Suppress("Unused")
suspend fun getCachedTopPerformerProducts(
siteId: Long,
datePeriod: String
): List<TopPerformerProductEntity> =
topPerformersDao.getTopPerformerProductsFor(siteId, datePeriod)
suspend fun fetchTopPerformerProducts(
site: SiteModel,
granularity: StatsGranularity,
quantity: Int? = null,
addProductsPath: Boolean = false,
forceRefresh: Boolean = false,
): WooResult<List<TopPerformerProductEntity>> {
val startDate = granularity.startDateTime(site)
val endDate = granularity.endDateTime(site)
val interval = OrderStatsRestClient.OrderStatsApiUnit.fromStatsGranularity(granularity).toString()
return fetchTopPerformerProducts(
site = site,
startDate = startDate,
endDate = endDate,
quantity = quantity,
addProductsPath = addProductsPath,
forceRefresh = forceRefresh,
interval = interval
)
}
@Suppress("LongParameterList")
suspend fun fetchTopPerformerProducts(
site: SiteModel,
startDate: String,
endDate: String,
quantity: Int? = null,
addProductsPath: Boolean = false,
forceRefresh: Boolean = false,
interval: String = ""
): WooResult<List<TopPerformerProductEntity>> {
val period = DateUtils.getDatePeriod(startDate, endDate)
return coroutineEngine.withDefaultContext(AppLog.T.API, this, "fetchLeaderboards") {
fetchAllLeaderboards(
site = site,
startDate = startDate,
endDate = endDate,
quantity = quantity,
addProductsPath = addProductsPath,
forceRefresh = forceRefresh,
interval = interval
)
.model
?.firstOrNull { it.type == PRODUCTS }
?.run {
mapper.mapTopPerformerProductsEntity(
response = this,
site = site,
productStore = productStore,
datePeriod = period
)
}
?.let {
topPerformersDao.updateTopPerformerProductsFor(
siteId = site.siteId,
datePeriod = period,
it
)
WooResult(it)
} ?: WooResult(WooError(GENERIC_ERROR, UNKNOWN))
}
}
@Suppress("LongParameterList")
private suspend fun fetchAllLeaderboards(
site: SiteModel,
startDate: String,
endDate: String,
quantity: Int?,
addProductsPath: Boolean,
forceRefresh: Boolean,
interval: String,
): WooResult<List<LeaderboardsApiResponse>> {
val response = restClient.fetchLeaderboards(
site = site,
startDate = startDate,
endDate = endDate,
quantity = quantity,
addProductsPath = addProductsPath,
interval = interval,
forceRefresh = forceRefresh
)
return when {
response.isError -> WooResult(response.error)
response.result != null -> WooResult(response.result.toList())
else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN))
}
}
fun invalidateTopPerformers(siteId: Long) {
coroutineEngine.launch(AppLog.T.DB, this, "Invalidating top performer products") {
val invalidatedTopPerformers =
topPerformersDao.getTopPerformerProductsForSite(siteId)
.map { it.copy(millisSinceLastUpdated = 0) }
topPerformersDao.updateTopPerformerProductsForSite(siteId, invalidatedTopPerformers)
}
}
}
| gpl-2.0 | 088de12fe7f63754d1eda8cdd13ef72e | 39.089041 | 107 | 0.65727 | 5.311252 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckdetail/SubHeaderItem.kt | 1 | 1365 | package com.bachhuberdesign.deckbuildergwent.features.deckdetail
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import com.bachhuberdesign.deckbuildergwent.R
import com.mikepenz.fastadapter.items.AbstractItem
import kotlinx.android.synthetic.main.item_sub_header.view.*
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
class SubHeaderItem : AbstractItem<SubHeaderItem, SubHeaderItem.ViewHolder>() {
companion object {
@JvmStatic val TAG: String = SubHeaderItem::class.java.name
}
var leftText = ""
var rightText = ""
override fun getLayoutRes(): Int {
return R.layout.item_sub_header
}
override fun getType(): Int {
return R.id.sub_header_item
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
override fun bindView(holder: ViewHolder, payloads: MutableList<Any>) {
super.bindView(holder, payloads)
holder.leftText.text = leftText
holder.rightText.text = rightText
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var leftText: TextView = view.sub_header_left_text
var rightText: TextView = view.sub_header_right_text
}
} | apache-2.0 | 5d89dd623a56875423cf3a8778c61f75 | 25.269231 | 79 | 0.695238 | 4.161585 | false | false | false | false |
AIDEA775/UNCmorfi | app/src/main/java/com/uncmorfi/home/HomeFragment.kt | 1 | 4796 | package com.uncmorfi.home
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.view.View.VISIBLE
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.uncmorfi.MainActivity
import com.uncmorfi.R
import com.uncmorfi.balance.dialogs.UserOptionsDialog
import com.uncmorfi.models.DayMenu
import com.uncmorfi.models.User
import com.uncmorfi.shared.ReserveStatus.NOCACHED
import com.uncmorfi.shared.compareToToday
import com.uncmorfi.shared.getUser
import com.uncmorfi.shared.init
import com.uncmorfi.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.fragment_home.*
class HomeFragment : Fragment() {
private lateinit var mViewModel: MainViewModel
private lateinit var mUser: User
private var mDayMenu: DayMenu? = null
private lateinit var mRootView: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mRootView = view
mViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
swipeRefresh.init { updateAll() }
/*
* Menú
*/
mViewModel.getMenu().observe(viewLifecycleOwner, Observer { menuList ->
val today = menuList.firstOrNull { it.date.compareToToday() == 0 }
mDayMenu = today
today?.let {
homeMenu.setDayMenu(today)
homeMenu.visibility = VISIBLE
}
})
homeMenuShowMore.setOnClickListener {
(requireActivity() as MainActivity).change(R.id.nav_menu)
}
/*
* Tarjetas
*/
mViewModel.allUsers().observe(viewLifecycleOwner, Observer {
if (it.isNotEmpty()) {
mUser = it.first()
homeCard.setUser(mUser)
homeCard.visibility = VISIBLE
}
})
homeCard.setOnClickListener {
UserOptionsDialog
.newInstance(this, USER_OPTIONS_CODE, mUser)
.show(parentFragmentManager, "UserOptionsDialog")
}
homeCard.setOnLongClickListener {
mUser.isLoading = true
homeCard.setUser(mUser)
mViewModel.downloadUsers(mUser)
true
}
homeCardShowMore.setOnClickListener {
(requireActivity() as MainActivity).change(R.id.nav_balance)
}
/*
* Medidor
*/
mViewModel.getServings().observe(viewLifecycleOwner, Observer {
if (it.isNotEmpty()) {
homeServingsPieChart.set(it)
}
})
homeServingsPieChart.setTouchEnabled(false)
homeServingsPieChart.setOnClickListener {
mViewModel.updateServings()
}
homeServingsShowMore.setOnClickListener {
(requireActivity() as MainActivity).change(R.id.nav_servings)
}
}
private fun updateAll() {
if (mDayMenu == null) {
mViewModel.updateMenu()
}
mViewModel.updateServings()
if (::mUser.isInitialized) {
mUser.isLoading = true
homeCard.setUser(mUser)
mViewModel.downloadUsers(mUser)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
USER_OPTIONS_CODE -> {
val user = data.getUser()
user.isLoading = true
homeCard.setUser(user)
mViewModel.downloadUsers(user)
}
else -> {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.home, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.home_update -> { updateAll(); true }
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
requireActivity().setTitle(R.string.app_name)
}
override fun onStop() {
super.onStop()
mViewModel.reservation.value = NOCACHED
}
companion object {
private const val USER_OPTIONS_CODE = 1
}
}
| gpl-3.0 | b51b85f8976edcaea9852e952084ef59 | 29.935484 | 88 | 0.614599 | 4.809428 | false | false | false | false |
rumboalla/apkupdater | app/src/main/java/com/apkupdater/repository/aptoide/AptoideSearch.kt | 1 | 1477 | package com.apkupdater.repository.aptoide
import com.apkupdater.R
import com.apkupdater.model.ui.AppSearch
import com.apkupdater.model.aptoide.ListSearchAppsRequest
import com.apkupdater.model.aptoide.ListSearchAppsResponse
import com.apkupdater.util.app.AppPrefs
import com.apkupdater.util.ioScope
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.gson.jsonBody
import com.github.kittinunf.fuel.gson.responseObject
import kotlinx.coroutines.async
import org.koin.core.KoinComponent
import org.koin.core.inject
class AptoideSearch: KoinComponent {
private val baseUrl = "https://ws75.aptoide.com/api/7/"
private val appUpdates = "listSearchApps"
private val source = R.drawable.aptoide_logo
private val prefs: AppPrefs by inject()
private val exclude get() = if(prefs.settings.excludeExperimental) "alpha,beta" else ""
private val limit = "10"
private fun listSearchApps(request: ListSearchAppsRequest) = Fuel
.post(baseUrl + appUpdates)
.jsonBody(request)
.responseObject<ListSearchAppsResponse>()
fun searchAsync(text: String) = ioScope.async {
listSearchApps(ListSearchAppsRequest(text, limit, exclude)).third.fold(
success = { Result.success(parseData(it)) },
failure = { Result.failure(it) }
)
}
private fun parseData(response: ListSearchAppsResponse) = response.datalist.list.map{ app ->
AppSearch(
app.name,
app.file.path,
app.icon?.replace("http:", "https:") ?: "",
app.packageName,
source
)
}
} | gpl-3.0 | c6ac598c8d142b484c8bf85a463c1e80 | 30.446809 | 93 | 0.770481 | 3.44289 | false | false | false | false |
gtomek/open-weather-kotlin | app/src/main/java/uk/co/tomek/openweatherkt/adapter/WeatherItemAdapter.kt | 1 | 2155 | package uk.co.tomek.openweatherkt.adapter
import android.support.v7.widget.RecyclerView
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 com.github.ajalt.timberkt.Timber
import uk.co.tomek.openweatherkt.R
import uk.co.tomek.openweatherkt.extensions.loadWeatherIcon
import uk.co.tomek.openweatherkt.model.WeatherResponseItem
import java.util.*
/**
* Recycler view adapter for a weather results line.
*/
class WeatherItemAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var weatherResponseItems = listOf<WeatherResponseItem>()
set(value) {
field = value
Timber.v { "Set new weather items :$value" }
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is WeatherCellViewHolder) {
holder.bind(weatherResponseItems[position])
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_weather_cell, parent, false)
return WeatherCellViewHolder(view)
}
override fun getItemCount(): Int = weatherResponseItems.size
class WeatherCellViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.textview_item_temperature)
lateinit var temperature: TextView
@BindView(R.id.textview_item_time)
lateinit var time: TextView
@BindView(R.id.imageview_item_icon)
lateinit var icon: ImageView
init {
Timber.v { "WeatherCellViewHolder init" }
ButterKnife.bind(this, itemView)
}
fun bind(item: WeatherResponseItem) {
Timber.v { "bind item $item" }
time.text = item.dt_txt.substring(11, 16)
temperature.text = String.format(Locale.UK, "%.1f\u00B0", item.main.temp)
icon.loadWeatherIcon(item.weather[0].icon)
}
}
} | apache-2.0 | 4daec387d0372c47ff56931b35d6f52b | 33.222222 | 105 | 0.69652 | 4.275794 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/test/kotlin/glimpse/lights/SpotlightBuilderSpec.kt | 1 | 2073 | package glimpse.lights
import glimpse.Color
import glimpse.Point
import glimpse.Vector
import glimpse.degrees
import glimpse.test.GlimpseSpec
import io.kotlintest.matchers.be
class SpotlightBuilderSpec : GlimpseSpec() {
init {
"Spotlight builder" should {
"create an instance of spotlight" {
LightBuilder.SpotlightBuilder().build() should be a Light.Spotlight::class
}
"create a light with updatable position" {
var position = Vector.X_UNIT.toPoint()
val builder = LightBuilder.SpotlightBuilder()
builder.position { position }
val light = builder.build()
light.position().toVector() shouldBe Vector.X_UNIT
position = Vector.Y_UNIT.toPoint()
light.position().toVector() shouldBe Vector.Y_UNIT
}
"create a light with updatable target" {
var target = Point.ORIGIN
val builder = LightBuilder.SpotlightBuilder()
builder.target { target }
val light = builder.build()
light.target() shouldBe Point.ORIGIN
target = Vector.Z_UNIT.toPoint()
light.target().toVector() shouldBe Vector.Z_UNIT
}
"create a light with updatable angle" {
var angle = 60.degrees
val builder = LightBuilder.SpotlightBuilder()
builder.angle { angle }
val light = builder.build()
light.angle() shouldBe 60.degrees
angle = 90.degrees
light.angle() shouldBe 90.degrees
}
"create a light with updatable distance" {
var distance = 10f
val builder = LightBuilder.SpotlightBuilder()
builder.distance { distance }
val light = builder.build()
light.distance() shouldBe 10f
distance = 30f
light.distance() shouldBe 30f
}
"create a light with updatable color" {
var color = Color.RED
val builder = LightBuilder.SpotlightBuilder()
builder.color { color }
val light = builder.build()
light.color() shouldBe Color.RED
color = Color.CYAN
light.color() shouldBe Color.CYAN
}
}
"Functional spotlight builder" should {
"create an instance of spotlight" {
spotlight {} should be a Light.Spotlight::class
}
}
}
} | apache-2.0 | bd6ccf1a89492a0ffe8ca63ca7a2957c | 23.987952 | 78 | 0.690304 | 3.755435 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/widget/FindEmptyView.kt | 1 | 3192 | package me.panpf.sketch.sample.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import me.panpf.sketch.util.SketchUtils
class FindEmptyView : View {
private var fullRectList: List<Rect>? = null
private var emptyRectList: List<Rect>? = null
private var boundsRect: Rect? = null
private val boundsRectPaint: Paint = Paint()
private val fullRectPaint: Paint = Paint()
private val emptyRectPaint: Paint = Paint()
constructor(context: Context) : super(context) {
init(context)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context)
}
private fun init(context: Context) {
boundsRectPaint.style = Paint.Style.STROKE
boundsRectPaint.color = Color.parseColor("#8800CD00")
boundsRectPaint.strokeWidth = SketchUtils.dp2px(context, 1).toFloat()
fullRectPaint.color = Color.parseColor("#88FF0000")
fullRectPaint.strokeWidth = SketchUtils.dp2px(context, 1).toFloat()
fullRectPaint.style = Paint.Style.STROKE
emptyRectPaint.color = Color.parseColor("#880000CD")
emptyRectPaint.strokeWidth = SketchUtils.dp2px(context, 1).toFloat()
emptyRectPaint.style = Paint.Style.STROKE
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (fullRectList != null) {
for (fullRect in fullRectList!!) {
if (!fullRect.isEmpty) {
canvas.drawRect(
(fullRect.left * 3 + 1).toFloat(),
(fullRect.top * 3 + 1).toFloat(),
(fullRect.right * 3 - 1).toFloat(),
(fullRect.bottom * 3 - 1).toFloat(),
fullRectPaint)
}
}
}
if (emptyRectList != null) {
for (emptyRect in emptyRectList!!) {
if (!emptyRect.isEmpty) {
canvas.drawRect(
(emptyRect.left * 3 + 1).toFloat(),
(emptyRect.top * 3 + 1).toFloat(),
(emptyRect.right * 3 - 1).toFloat(),
(emptyRect.bottom * 3 - 1).toFloat(),
emptyRectPaint)
}
}
}
if (boundsRect != null && !boundsRect!!.isEmpty) {
canvas.drawRect((boundsRect!!.left * 3).toFloat(), (boundsRect!!.top * 3).toFloat(), (boundsRect!!.right * 3).toFloat(), (boundsRect!!.bottom * 3).toFloat(), boundsRectPaint)
}
}
fun setBoundsRect(boundsRect: Rect) {
this.boundsRect = boundsRect
}
fun setEmptyRectList(emptyRectList: List<Rect>?) {
this.emptyRectList = emptyRectList
}
fun setFullRectList(fullRectList: List<Rect>) {
this.fullRectList = fullRectList
}
}
| apache-2.0 | b9160147f40d1e3f0ab820cd0d0aa076 | 33.322581 | 186 | 0.580514 | 4.325203 | false | false | false | false |
b95505017/android-architecture-components | BasicRxJavaSampleKotlin/app/src/main/java/com/example/android/observability/persistence/UsersDatabase.kt | 1 | 1563 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.observability.persistence
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.content.Context
/**
* The Room database that contains the Users table
*/
@Database(entities = arrayOf(User::class), version = 1)
abstract class UsersDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile private var INSTANCE: UsersDatabase? = null
fun getInstance(context: Context): UsersDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
UsersDatabase::class.java, "Sample.db")
.build()
}
}
| apache-2.0 | a234b1942cbb3e75693a15d14076ef59 | 32.978261 | 77 | 0.68842 | 4.651786 | false | false | false | false |
simonlebras/Radio-France | app/src/main/kotlin/fr/simonlebras/radiofrance/playback/di/modules/RadioPlaybackModule.kt | 1 | 5375 | package fr.simonlebras.radiofrance.playback.di.modules
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.net.wifi.WifiManager
import android.os.PowerManager
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.media.session.MediaButtonReceiver
import android.support.v4.media.session.MediaSessionCompat
import android.support.v7.media.MediaRouter
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastSession
import com.google.android.gms.cast.framework.SessionManager
import com.google.android.gms.cast.framework.media.RemoteMediaClient
import dagger.Module
import dagger.Provides
import fr.simonlebras.radiofrance.BuildConfig.FIREBASE_ENDPOINT
import fr.simonlebras.radiofrance.di.scopes.ServiceScope
import fr.simonlebras.radiofrance.playback.*
import fr.simonlebras.radiofrance.playback.data.FirebaseService
import fr.simonlebras.radiofrance.playback.data.RadioProvider
import fr.simonlebras.radiofrance.playback.data.RadioProviderImpl
import fr.simonlebras.radiofrance.ui.browser.RadioBrowserActivity
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Named
import javax.inject.Provider
@Module
class RadioPlaybackModule {
companion object {
private const val LOCK_NAME = "Radio France lock"
const val LOCAL_KEY = "LOCAL_KEY"
const val CAST_KEY = "CAST_KEY"
}
@Provides
@ServiceScope
fun provideMediaSessionCompat(context: Context, mediaSessionCallback: MediaSessionCallback): MediaSessionCompat {
val mediaSession = MediaSessionCompat(context, RadioPlaybackService.TAG)
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS or MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS)
mediaSession.setCallback(mediaSessionCallback)
// PendingIntent for the media button
val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON)
mediaButtonIntent.setClass(context, MediaButtonReceiver::class.java)
var pendingIntent = PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0)
mediaSession.setMediaButtonReceiver(pendingIntent)
val intent = Intent(context, RadioBrowserActivity::class.java)
pendingIntent = PendingIntent.getActivity(context, RadioBrowserActivity.REQUEST_CODE_SESSION, intent, PendingIntent.FLAG_UPDATE_CURRENT)
mediaSession.setSessionActivity(pendingIntent)
return mediaSession
}
@Provides
@ServiceScope
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(FIREBASE_ENDPOINT)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
@ServiceScope
fun provideRadioService(retrofit: Retrofit): FirebaseService = retrofit.create(FirebaseService::class.java)
@Provides
@ServiceScope
fun provideRadioProvider(radioProvider: RadioProviderImpl): RadioProvider = radioProvider
@Provides
@ServiceScope
fun provideNotificationManagerCompat(context: Context): NotificationManagerCompat = NotificationManagerCompat.from(context)
@Provides
fun provideAudioManager(context: Context) = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
@Provides
fun provideWifiLock(context: Context): WifiManager.WifiLock {
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
return wifiManager.createWifiLock(LOCK_NAME)
}
@Provides
fun provideWakeLock(context: Context): PowerManager.WakeLock {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME)
}
@Provides
@ServiceScope
fun provideMediaRouter(context: Context): MediaRouter {
return MediaRouter.getInstance(context.applicationContext)
}
@Provides
@ServiceScope
fun provideCastSessionManager(context: Context, castSessionManagerListener: CastSessionManagerListener): SessionManager {
val castSessionManager = CastContext.getSharedInstance(context).sessionManager
castSessionManager.addSessionManagerListener(castSessionManagerListener, CastSession::class.java)
return castSessionManager
}
@Provides
fun provideRemoteMediaClient(context: Context): RemoteMediaClient {
val castSession = CastContext.getSharedInstance(context.applicationContext).sessionManager.currentCastSession
return castSession.remoteMediaClient
}
@Provides
@ServiceScope
@Named(LOCAL_KEY)
fun provideLocalPlaybackFactory(provider: Provider<LocalPlayback>): Function1<@JvmWildcard Context, @JvmWildcard Playback> {
return { provider.get() }
}
@Provides
@ServiceScope
@Named(CAST_KEY)
fun provideCastPlaybackFactory(provider: Provider<CastPlayback>): Function1<@JvmWildcard Context, @JvmWildcard Playback> {
return { provider.get() }
}
}
| mit | 88e3eb053e8353d58b2ba7bf8c45f031 | 39.11194 | 144 | 0.772465 | 4.926673 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/ui/topic/TopicAdapter.kt | 1 | 14996 | package im.fdx.v2ex.ui.topic
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import im.fdx.v2ex.MyApp
import im.fdx.v2ex.R
import im.fdx.v2ex.databinding.ItemReplyViewBinding
import im.fdx.v2ex.network.HttpHelper
import im.fdx.v2ex.network.NetManager
import im.fdx.v2ex.pref
import im.fdx.v2ex.ui.main.Topic
import im.fdx.v2ex.ui.main.TopicsRVAdapter
import im.fdx.v2ex.ui.member.MemberActivity
import im.fdx.v2ex.ui.node.NodeActivity
import im.fdx.v2ex.utils.Keys
import im.fdx.v2ex.utils.TimeUtil
import im.fdx.v2ex.utils.extensions.getRowNum
import im.fdx.v2ex.utils.extensions.load
import im.fdx.v2ex.utils.extensions.logd
import im.fdx.v2ex.utils.extensions.showLoginHint
import im.fdx.v2ex.view.GoodTextView
import im.fdx.v2ex.view.Popup
import im.fdx.v2ex.view.typeComment
import im.fdx.v2ex.view.typeReply
import okhttp3.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.io.IOException
private const val TYPE_HEADER = 0
private const val TYPE_ITEM = 1
/**
* Created by fdx on 15-9-7.
* 详情页的Adapter。
*/
class TopicAdapter(private val act: FragmentActivity,
private val clickMore: (Int) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var once: String? = null
val topics: MutableList<Topic> = MutableList(1) { Topic() }
val replies: MutableList<Reply> = mutableListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
when (viewType) {
TYPE_HEADER -> TopicWithCommentsViewHolder(LayoutInflater.from(act).inflate(R.layout.item_topic_with_comments, parent, false))
TYPE_ITEM -> ItemViewHolder(ItemReplyViewBinding.inflate(LayoutInflater.from(parent.context), parent, false))
else -> throw RuntimeException(" No type that matches $viewType + Make sure using types correctly")
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, p: Int) {
val position = holder.bindingAdapterPosition
when (getItemViewType(position)) {
TYPE_HEADER -> {
val topic = topics[0]
logd(topic.title)
logd(topic.content_rendered)
val mainHolder = holder as TopicWithCommentsViewHolder
mainHolder.tvTitle.text = topic.title
mainHolder.tvTitle.maxLines = 4
mainHolder.tvContent.setGoodText(topic.content_rendered)
mainHolder.tvContent.isSelected = true
mainHolder.tvContent.setTextIsSelectable(true)
mainHolder.tvReplyNumber.text = topic.replies.toString()
mainHolder.tvAuthor.text = topic.member?.username
mainHolder.tvNode.text = topic.node?.title
mainHolder.tvCreated.text = TimeUtil.getRelativeTime(topic.created)
mainHolder.ivAvatar.load(topic.member?.avatarNormalUrl)
if (topic.comments.isNotEmpty()) {
mainHolder.ll.removeAllViews()
mainHolder.dividerComments.isGone = false
topic.comments.forEach {
val view = LayoutInflater.from(act).inflate(R.layout.item_comments, mainHolder.ll, false)
val th = CommentsViewHolder(view)
th.tvCTitle.text = it.title
th.tvCTime.text = TimeUtil.getRelativeTime(it.created)
th.tvCContent.setGoodText(it.content, type = typeComment)
mainHolder.ll.addView(view)
}
}
mainHolder.tvNode.setOnClickListener{
act.startActivity<NodeActivity>(Keys.KEY_NODE_NAME to topic.node?.name!!)
}
mainHolder.ivAvatar.setOnClickListener{
act.startActivity<MemberActivity>(Keys.KEY_USERNAME to topic.member?.username!!)
}
}
TYPE_ITEM -> {
val itemVH = holder as ItemViewHolder
val replyItem = replies[position - 1]
if (position == itemCount - 1) {
itemVH.binding.divider.visibility = View.INVISIBLE
} else {
itemVH.binding.divider.visibility = View.VISIBLE
}
itemVH.bind(replyItem)
act.registerForContextMenu(itemVH.itemView)
itemVH.itemView.setOnCreateContextMenuListener { menu, _, _ ->
val menuInflater = act.menuInflater
menuInflater.inflate(R.menu.menu_reply, menu)
menu.findItem(R.id.menu_reply).setOnMenuItemClickListener {
reply(replyItem, position)
true
}
menu.findItem(R.id.menu_thank).setOnMenuItemClickListener {
thank(replyItem, itemVH)
true
}
menu.findItem(R.id.menu_copy).setOnMenuItemClickListener {
copyText(replyItem.content)
true
}
menu.findItem(R.id.menu_show_user_all_reply).setOnMenuItemClickListener {
showUserAllReply(replyItem)
true
}
menu.findItem(R.id.menu_show_user_conversation).setOnMenuItemClickListener {
showUserConversation(replyItem)
true
}
}
itemVH.binding.ivThanks.setOnClickListener { thank(replyItem, itemVH) }
itemVH.binding.tvThanks.setOnClickListener { thank(replyItem, itemVH) }
itemVH.binding.ivReply.setOnClickListener { reply(replyItem, position) }
itemVH.binding.ivReplyAvatar.setOnClickListener {
act.startActivity<MemberActivity>(Keys.KEY_USERNAME to replyItem.member!!.username)
}
if (replyItem.isThanked) {
itemVH.binding.ivThanks.imageTintList = ContextCompat.getColorStateList(act, R.color.primary)
itemVH.binding.ivThanks.isClickable = false
itemVH.binding.tvThanks.isClickable = false
} else {
itemVH.binding.ivThanks.imageTintList = null
}
itemVH.binding.tvReplyContent.popupListener = object : Popup.PopupListener {
override fun onClick(v: View, url: String) {
val username = url.split("/").last()
//问题,index可能用户输入不准确,导致了我的这个点击会出现错误。 也有可能是黑名单能影响,导致了
//了这个错误,所以,我需要进行大数据排错。
//rowNum 是真是的楼层数, 但是在数组的index = rowNum -1
var rowNum = replyItem.content.getRowNum(username)
//找不到,或大于,明显不可能,取最接近一个评论
if (rowNum == -1 || rowNum > position) {
replies.forEachIndexed { i, r ->
if (i in 0 until position && r.member?.username == username) {
rowNum = i + 1
}
}
}
if (rowNum == -1 || rowNum > position) {
return
}
Popup(act).show(v, replies[rowNum -1], rowNum, clickMore)
}
}
}
}
}
private fun showUserAllReply(replyItem: Reply) {
val theUserReplyList = replies.filter {
it.member!=null && it.member?.username == replyItem.member?.username
}
val bs = BottomListSheet.newInstance(theUserReplyList)
bs.show(act.supportFragmentManager , "list_of_user_all_reply")
}
//todo
private fun showUserConversation(replyItem: Reply) {
val oneName = replyItem.member?.username?:""
var theOtherName = ""
if (replyItem.content_rendered.contains("v2ex.com/member/")) {//说明有对话
var find = """(?<=v2ex\.com/member/)\w+""".toRegex().find(replyItem.content_rendered)
find?.let {
theOtherName = it.value
}
val theUserReplyList = replies.filter {
val username = it.member?.username
(username == oneName && hasRelate(theOtherName, it)) //需要是和other相关的
|| (username == theOtherName && hasRelate(oneName, it)) //需要是和本楼相关的
}
if (theUserReplyList.isEmpty()) {
return
}
val bs = BottomListSheet.newInstance(theUserReplyList)
bs.show(act.supportFragmentManager, "user_conversation")
}
}
fun hasRelate(name:String, item: Reply) : Boolean{
var find = """v2ex\.com/member/$name""".toRegex().find(item.content_rendered)
find?.let {
return true
}
return false
}
private fun copyText(content: String) {
logd("I click menu copy")
val manager = act.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
manager.setPrimaryClip( ClipData.newPlainText("item", content))
act.toast("评论已复制")
}
private fun thank(replyItem: Reply, itemVH: ItemViewHolder) {
logd("once: $once")
val editText: EditText = act.findViewById(R.id.et_post_reply)
if (!MyApp.get().isLogin) {
act.showLoginHint(editText)
return
}
if (once == null) {
act.toast("请刷新后重试")
return
}
val body = FormBody.Builder().add("once", once!!).build()
HttpHelper.OK_CLIENT.newCall(Request.Builder()
.url("https://www.v2ex.com/thank/reply/${replyItem.id}")
.post(body)
.build()).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
NetManager.dealError(act)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (response.code == 200) {
act.runOnUiThread {
act.toast("感谢成功")
replyItem.thanks = replyItem.thanks + 1
itemVH.binding.tvThanks.text = (replyItem.thanks).toString()
itemVH.binding.ivThanks.imageTintList = ContextCompat.getColorStateList(act, R.color.primary)
itemVH.binding.ivThanks.isClickable = false
replyItem.isThanked = true
}
} else {
NetManager.dealError(act, response.code)
}
}
})
return
}
private fun reply(replyItem: Reply, position: Int) {
val editText: EditText = act.findViewById(R.id.et_post_reply)
if (!MyApp.get().isLogin) {
act.showLoginHint(editText)
return
}
val text = "@${replyItem.member!!.username} " +
if (pref.getBoolean("pref_add_row", false)) "#$position " else ""
if (!editText.text.toString().contains(text)) {
val spanString = SpannableString(text)
val span = ForegroundColorSpan(ContextCompat.getColor(act, R.color.primary))
spanString.setSpan(span, 0, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
editText.append(spanString)
}
editText.setSelection(editText.length())
editText.requestFocus()
val imm = act.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}
override fun getItemCount() = 1 + replies.size
override fun getItemViewType(position: Int) = when (position) {
0 -> TYPE_HEADER
else -> TYPE_ITEM
}
fun updateItems(t: Topic, replies: List<Reply>) {
this.topics.clear()
this.topics.add(t)
this.replies.clear()
this.replies.addAll(replies)
replies.forEachIndexed { index ,it ->
it.isLouzu = it.member?.username == topics[0].member?.username
it.showTime = TimeUtil.getRelativeTime(it.created)
it.rowNum = index + 1
}
notifyDataSetChanged()
}
fun addItems(replies: List<Reply>) {
replies.forEachIndexed { index, it ->
it.isLouzu = it.member?.username == topics[0].member?.username
it.showTime = TimeUtil.getRelativeTime(it.created)
it.rowNum = index + 1
}
this.replies.addAll(replies)
notifyDataSetChanged()
}
}
class ItemViewHolder(var binding: ItemReplyViewBinding)
: RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n")
fun bind(data:Reply) {
binding.tvReplyContent.setGoodText(data.content_rendered , type = typeReply)
binding.tvLouzu.visibility = if (data.isLouzu) View.VISIBLE else View.GONE
binding.tvReplyRow.text = "# ${data.rowNum}"
binding.tvReplier.text = data.member?.username
binding.tvThanks.text = data.thanks.toString()
binding.ivReplyAvatar.load(data.member?.avatarNormalUrl)
binding.tvReplyTime.text = data.showTime
}
}
class TopicWithCommentsViewHolder(itemView: View)
: TopicsRVAdapter.MainViewHolder(itemView) {
internal var ll: LinearLayout = itemView.findViewById(R.id.ll_comments)
internal val dividerComments :View = itemView.findViewById(R.id.divider_comment)
}
class CommentsViewHolder(itemView: View) {
internal var tvCTitle: TextView = itemView.findViewById(R.id.tv_comment_id)
internal var tvCTime: TextView = itemView.findViewById(R.id.tv_comment_time)
internal var tvCContent: GoodTextView = itemView.findViewById(R.id.tv_comment_content)
}
| apache-2.0 | 5fe23e2ce9eda0b201919b64491fe9eb | 38.347594 | 142 | 0.592824 | 4.456693 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/processModel/engine/ExecutableProcessModel.kt | 1 | 8836 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel.engine
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.serializer
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
import net.devrieze.util.security.SecurityProvider
import nl.adaptivity.process.engine.impl.getClass
import nl.adaptivity.process.processModel.*
import nl.adaptivity.util.multiplatform.randomUUID
import nl.adaptivity.xmlutil.XmlDeserializerFactory
import nl.adaptivity.xmlutil.XmlReader
import nl.adaptivity.xmlutil.serialization.XML
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
/**
* A class representing a process model.
*
* @author Paul de Vrieze
*/
@Serializable(ExecutableProcessModel.Companion::class)
class ExecutableProcessModel : RootProcessModelBase<ExecutableProcessNode>,
ExecutableModelCommon,
SecureObject<ExecutableProcessModel> {
@JvmOverloads
constructor(builder: RootProcessModel.Builder, pedantic: Boolean = true) :
super(builder, EXEC_NODEFACTORY, pedantic)
private constructor(delegate: SerialDelegate, pedantic: Boolean = true) : super(
Builder(delegate),
EXEC_NODEFACTORY,
pedantic
)
@Transient
override val endNodeCount by lazy { modelNodes.count { it is ExecutableEndNode } }
@Transient
override val rootModel
get() = this
@Transient
override val ref: ExecutableProcessModelRef
get() = ProcessModelRef(name, handle, uuid)
override fun withPermission() = this
override fun builder(): RootProcessModel.Builder = Builder(this)
override fun update(body: RootProcessModel.Builder.() -> Unit): ExecutableProcessModel {
return ExecutableProcessModel(Builder(this).apply(body))
}
@Suppress("UNCHECKED_CAST")
override val handle: Handle<ExecutableProcessModel>
get() = super.handle as Handle<ExecutableProcessModel>
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (getClass() != other?.getClass()) return false
if (!super.equals(other)) return false
return true
}
override fun toString(): String {
return "ExecutableProcessModel() ${super.toString()}"
}
companion object: KSerializer<ExecutableProcessModel> {
private val delegateSerializer = SerialDelegate.serializer()
override val descriptor: SerialDescriptor get() = delegateSerializer.descriptor
override fun serialize(encoder: Encoder, value: ExecutableProcessModel) {
delegateSerializer.serialize(encoder, SerialDelegate(value))
}
override fun deserialize(decoder: Decoder): ExecutableProcessModel {
return ExecutableProcessModel(delegateSerializer.deserialize(decoder), true)
}
fun from(basepm: RootProcessModel<*>): ExecutableProcessModel {
return basepm as? ExecutableProcessModel ?: ExecutableProcessModel(Builder(basepm))
}
@JvmStatic
fun deserialize(reader: XmlReader): ExecutableProcessModel {
return ExecutableProcessModel(XML { autoPolymorphic = true }.decodeFromReader<XmlProcessModel.Builder>(reader))
}
@JvmStatic
inline fun build(body: Builder.() -> Unit) = Builder().apply(body).also {
if (it.uuid == null) {
it.uuid = randomUUID()
}
}.let { ExecutableProcessModel(it) }
/**
* Helper method that helps enumerating all elements in the model
*
* @param destination The collection that will contain the result.
*
* @param seen A set of process names that have already been seen (and should
* not be added again.
*
* @param node The node to start extraction from. This will go on to the
* successors.
*/
private fun extractElementsTo(
destination: MutableCollection<in ExecutableProcessNode>,
seen: MutableSet<String>,
node: ExecutableProcessNode
) {
if (node.id in seen) return
destination.add(node)
seen.add(node.id)
for (successor in node.successors) {
extractElementsTo(destination, seen, successor as ExecutableProcessNode)
}
}
}
enum class Permissions : SecurityProvider.Permission {
INSTANTIATE
}
}
val EXEC_BUILDER_VISITOR = object : ProcessNode.Visitor<ProcessNode.Builder> {
override fun visitStartNode(startNode: StartNode) = ExecutableStartNode.Builder(startNode)
override fun visitActivity(messageActivity: MessageActivity) = MessageActivityBase.Builder(messageActivity)
override fun visitActivity(compositeActivity: CompositeActivity) =
CompositeActivityBase.ReferenceBuilder(compositeActivity)
override fun visitSplit(split: Split) = ExecutableSplit.Builder(split)
override fun visitJoin(join: Join) = ExecutableJoin.Builder(join)
override fun visitEndNode(endNode: EndNode) = ExecutableEndNode.Builder(endNode)
}
object EXEC_NODEFACTORY :
ProcessModelBase.NodeFactory<ExecutableProcessNode, ExecutableProcessNode, ExecutableChildModel> {
private fun visitor(
buildHelper: ProcessModel.BuildHelper<ExecutableProcessNode, *, *, *>,
otherNodes: Iterable<ProcessNode.Builder>
) = ExecutableProcessNodeBuilderVisitor(buildHelper, otherNodes)
private class ExecutableProcessNodeBuilderVisitor(
private val buildHelper: ProcessModel.BuildHelper<ExecutableProcessNode, ProcessModel<ExecutableProcessNode>, *, *>,
val otherNodes: Iterable<ProcessNode.Builder>
) :
ProcessNode.BuilderVisitor<ExecutableProcessNode> {
override fun visitStartNode(startNode: StartNode.Builder) =
ExecutableStartNode(startNode, buildHelper)
override fun visitActivity(activity: MessageActivity.Builder) =
ExecutableMessageActivity(activity, buildHelper.newOwner, otherNodes)
override fun visitActivity(activity: CompositeActivity.ModelBuilder) =
ExecutableCompositeActivity(activity, buildHelper, otherNodes)
override fun visitActivity(activity: CompositeActivity.ReferenceBuilder) =
ExecutableCompositeActivity(activity, buildHelper, otherNodes)
override fun visitGenericActivity(builder: Activity.Builder): ExecutableProcessNode {
return when (builder) {
is RunnableActivity.Builder<*, *> -> RunnableActivity(builder, buildHelper.newOwner, otherNodes)
else -> super.visitGenericActivity(builder)
}
}
override fun visitSplit(split: Split.Builder) =
ExecutableSplit(split, buildHelper.newOwner, otherNodes)
override fun visitJoin(join: Join.Builder) =
ExecutableJoin(join, buildHelper, otherNodes)
override fun visitEndNode(endNode: EndNode.Builder) =
ExecutableEndNode(endNode, buildHelper, otherNodes)
}
override fun invoke(
baseNodeBuilder: ProcessNode.Builder,
buildHelper: ProcessModel.BuildHelper<ExecutableProcessNode, *, *, *>,
otherNodes: Iterable<ProcessNode.Builder>
): ExecutableProcessNode = baseNodeBuilder.visit(visitor(buildHelper, otherNodes))
override fun invoke(
baseChildBuilder: ChildProcessModel.Builder,
buildHelper: ProcessModel.BuildHelper<ExecutableProcessNode, *, *, *>
): ExecutableChildModel {
return ExecutableChildModel(baseChildBuilder, buildHelper)
}
override fun condition(condition: Condition) = condition.toExecutableCondition()
}
typealias ExecutableProcessModelRef = IProcessModelRef<ExecutableProcessNode, ExecutableProcessModel>
| lgpl-3.0 | c295dac19c0468c70e47561330e8fd67 | 37.086207 | 124 | 0.703486 | 5.25327 | false | false | false | false |
JetBrains/anko | anko/library/static/commons/src/main/java/Theme.kt | 2 | 2571 | @file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.Fragment
import android.content.Context
import android.content.res.Resources
import android.support.annotation.AttrRes
import android.support.annotation.ColorInt
import android.support.annotation.Dimension
import android.util.TypedValue
import android.view.View
fun Resources.Theme.attr(@AttrRes attribute: Int): TypedValue {
val typedValue = TypedValue()
if (!resolveAttribute(attribute, typedValue, true)) {
throw IllegalArgumentException("Failed to resolve attribute: $attribute")
}
return typedValue
}
@ColorInt
fun Resources.Theme.color(@AttrRes attribute: Int): Int {
val attr = attr(attribute)
if (attr.type < TypedValue.TYPE_FIRST_COLOR_INT || attr.type > TypedValue.TYPE_LAST_COLOR_INT) {
throw IllegalArgumentException("Attribute value type is not color: $attribute")
}
return attr.data
}
fun Context.attr(@AttrRes attribute: Int): TypedValue = theme.attr(attribute)
@Dimension(unit = Dimension.PX)
fun Context.dimenAttr(@AttrRes attribute: Int): Int =
TypedValue.complexToDimensionPixelSize(attr(attribute).data, resources.displayMetrics)
@ColorInt
fun Context.colorAttr(@AttrRes attribute: Int): Int = theme.color(attribute)
@Dimension(unit = Dimension.PX)
inline fun AnkoContext<*>.dimenAttr(@AttrRes attribute: Int): Int = ctx.dimenAttr(attribute)
@ColorInt
inline fun AnkoContext<*>.colorAttr(@AttrRes attribute: Int): Int = ctx.colorAttr(attribute)
inline fun AnkoContext<*>.attr(@AttrRes attribute: Int): TypedValue = ctx.attr(attribute)
@Dimension(unit = Dimension.PX)
inline fun View.dimenAttr(@AttrRes attribute: Int): Int = context.dimenAttr(attribute)
@ColorInt
inline fun View.colorAttr(@AttrRes attribute: Int): Int = context.colorAttr(attribute)
inline fun View.attr(@AttrRes attribute: Int): TypedValue = context.attr(attribute)
@Dimension(unit = Dimension.PX)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun Fragment.dimenAttr(@AttrRes attribute: Int): Int = activity.dimenAttr(attribute)
@ColorInt
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun Fragment.colorAttr(@AttrRes attribute: Int): Int = activity.colorAttr(attribute)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun Fragment.attr(@AttrRes attribute: Int): TypedValue = activity.attr(attribute)
| apache-2.0 | 3594f2b352e845335211421531c0e390 | 36.26087 | 110 | 0.772462 | 4.249587 | false | false | false | false |
ben-upsilon/up | up/src/main/java/ben/upsilon/up/BeingWidget.kt | 1 | 3762 | package ben.upsilon.up
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.RemoteViews
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Implementation of App Widget functionality.
* App Widget Configuration implemented in [BeingWidgetConfigureActivity]
*/
class BeingWidget : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
Log.d(TAG, "onUpdate")
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
// When the user deletes the widget, delete the preference associated with it.
Log.d(TAG, "onDeleted")
// for (int appWidgetId : appWidgetIds) {
// BeingWidgetConfigureActivity.Companion.deleteTitlePref(context, appWidgetId);
// }
}
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
Log.d(TAG, "onUpdate")
}
override fun onDisabled(context: Context) {
// Enter relevant functionality for when the last widget is disabled
Log.d(TAG, "onDisabled")
}
override fun onAppWidgetOptionsChanged(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, newOptions: Bundle) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
Log.d(TAG, "onAppWidgetOptionsChanged")
}
companion object {
private val TAG = BeingWidget::class.java.simpleName
internal fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager,
appWidgetId: Int) {
Log.d(TAG, "updateAppWidget")
try {
val start = SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.CHINA).parse("2016-01-28 08:25")
Log.d(TAG, "updateAppWidget: start >" + start)
Log.d(TAG, "updateAppWidget: now >" + Date())
val r = computeDiff(start, Date())
Log.d(TAG, "updateAppWidget: " + r.toString())
val widgetText = context.getString(R.string.appwidget_text, r[TimeUnit.DAYS].toString(), r[TimeUnit.HOURS].toString(), r[TimeUnit.MINUTES].toString())
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.being_widget)
views.setTextViewText(R.id.appwidget_text, widgetText)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
} catch (e: ParseException) {
e.printStackTrace()
}
}
fun computeDiff(date1: Date, date2: Date): Map<TimeUnit, Long> {
val diffInMillies = date2.time - date1.time
val units = ArrayList(EnumSet.allOf(TimeUnit::class.java))
Collections.reverse(units)
val result = LinkedHashMap<TimeUnit, Long>()
var milliesRest = diffInMillies
for (unit in units) {
val diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS)
val diffInMilliesForUnit = unit.toMillis(diff)
milliesRest -= diffInMilliesForUnit
result.put(unit, diff)
}
return result
}
}
}
| cc0-1.0 | 35879df8d63d3f8c9adbfbb8bbefa0d6 | 37.387755 | 166 | 0.640883 | 4.792357 | false | false | false | false |
RizkiMufrizal/Starter-Project | Starter-BackEnd/src/main/kotlin/org/rizki/mufrizal/starter/backend/domain/Barang.kt | 1 | 1217 | package org.rizki.mufrizal.starter.backend.domain
import org.hibernate.annotations.GenericGenerator
import org.hibernate.validator.constraints.NotEmpty
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.NotNull
/**
*
* @Author Rizki Mufrizal <[email protected]>
* @Web <https://RizkiMufrizal.github.io>
* @Since 20 August 2017
* @Time 5:46 PM
* @Project Starter-BackEnd
* @Package org.rizki.mufrizal.starter.backend.domain
* @File Barang
*
*/
@Entity
@Table(name = "tb_barang")
data class Barang(
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(length = 36, name = "id_barang")
val idBarang: String? = null,
@NotEmpty
@NotNull
@Column(length = 50, name = "nama_barang")
val namaBarang: String? = null,
@NotNull
@Enumerated(EnumType.STRING)
@Column(length = 36, name = "jenis_barang")
val jenisBarang: JenisBarang? = null
) | apache-2.0 | a46176078c4f8b1331220290b41646d9 | 28.707317 | 61 | 0.702547 | 3.676737 | false | false | false | false |
debop/debop4k | debop4k-web/src/main/kotlin/debop4k/web/utils/Webx.kt | 1 | 2500 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.web.utils
import debop4k.core.json.*
import debop4k.core.utils.asInt
import debop4k.core.utils.toUtf8Bytes
import org.springframework.http.MediaType
import javax.servlet.ServletRequest
val APPLICATION_JSON_UTF8: MediaType = MediaType(MediaType.APPLICATION_JSON.type,
MediaType.APPLICATION_JSON.subtype,
Charsets.UTF_8)
private val jsonSerialzer: JsonSerializer by lazy { JacksonSerializer() }
/**
* 객체를 Json 직렬화를 수행하고, 바이트 배열로 반환합니다.
*
* @return Json 직렬화된 정보를 담은 바이트 배열
*/
fun Any?.toJsonByteArray(): ByteArray = jsonSerialzer.toByteArray(this)
/**
* 객체가 Map 인 경우, Map의 정보를 HTTP GET 방식의 URL 을 만듭니다.
*
* @return 객체 정보를 Form UrlEncoding 방식으로 인코딩한 정보
*/
fun Map<*, *>.toUrlEncodedBytes(): ByteArray {
val builder = StringBuilder()
val mapper = DefaultObjectMapper
val props = mapper.convertValue(this, Map::class.java)
props.entries.forEach {
builder.append(it.key).append("=").append(it.value).append("&")
}
return builder.toString().toUtf8Bytes()
}
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun java.lang.Integer.getPageNo(): Int = this.asInt()
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun java.lang.Integer.getPageSize(defaultSize: Int = 10): Int
= this.asInt(defaultSize)
/**
* Request 에서 parameter 정보를 가져옵니다. 만약 없다면 defaultValue 를 반환합니다.
*
* @param paramName 파라미터 이름
* @param defaultValue 파라미터의 값이 없을 때 제공되는 값
* @return 파라미터 값
*/
fun ServletRequest.getParamValue(paramName: String, defaultValue: String): String {
return getParameter(paramName) ?: defaultValue
} | apache-2.0 | ef0754d53ab6bec327081e64dc4604f0 | 29.662162 | 84 | 0.705026 | 3.549296 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/ui/dialog/CancelChangesDialog.kt | 1 | 1402 | package com.makeevapps.simpletodolist.ui.dialog
import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.afollestad.materialdialogs.MaterialDialog
import com.makeevapps.simpletodolist.R
import com.orhanobut.logger.Logger
object CancelChangesDialog {
@SuppressLint("StaticFieldLeak")
private var dialog: MaterialDialog? = null
private var mHandler: Handler? = null
@Synchronized
fun showDialog(context: Context, onSuccess: () -> Unit) {
dismissDialog()
val builder = MaterialDialog.Builder(context)
builder.content(R.string.cancel_your_changes)
builder.positiveText(R.string.yes)
builder.onPositive({ _, _ ->
onSuccess()
})
builder.negativeText(R.string.no)
if (mHandler == null)
mHandler = Handler(Looper.getMainLooper())
mHandler!!.post {
try {
dialog = builder.show()
} catch (e: Exception) {
Logger.e("Show error dialog: $e")
}
}
}
@Synchronized
fun dismissDialog() {
if (dialog != null && dialog!!.isShowing) {
try {
dialog!!.dismiss()
} catch (e: IllegalArgumentException) {
Logger.e("Dismiss error dialog: $e")
}
}
}
} | mit | a148272906566463c3fb3ff138113638 | 24.981481 | 61 | 0.601284 | 4.768707 | false | false | false | false |
asamm/locus-api | locus-api-android/src/main/java/locus/api/android/features/computeTrack/ComputeTrackParameters.kt | 1 | 2938 | /**
* Created by menion on 10. 7. 2014.
* Class is part of Locus project
*/
package locus.api.android.features.computeTrack
import locus.api.objects.Storable
import locus.api.objects.extra.GeoDataExtra
import locus.api.objects.extra.Location
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import java.io.IOException
/**
* Container for parameters needed to compute route over [ComputeTrackService] instance.
*
* Empty constructor for 'Storable' class. Do not use directly
*/
@Suppress("MemberVisibilityCanBePrivate")
class ComputeTrackParameters() : Storable() {
/**
* Type of track that should be compute.
*/
var type: Int = GeoDataExtra.VALUE_RTE_TYPE_CAR
private set
/**
* Flag if user wants with navigation orders.
*/
var isComputeInstructions: Boolean = true
/**
* Direction angle of movement at first point [°].
*/
var currentDirection: Float = 0.0f
set(value) {
field = value
hasDirection = true
}
/**
* Flag if parameters has defined starting direction.
*/
var hasDirection: Boolean = false
private set
/**
* List of defined via-points (location)
*/
var locations: Array<Location> = arrayOf()
private set
/**
* Create new parameters for track compute.
*
* @param type type of track to compute
* @param locs list of defined points over which route should be computed
*/
constructor(type: Int, locs: Array<Location>) : this() {
this.type = type
if (locs.size < 2) {
throw IllegalArgumentException("'locs' parameter" + " cannot be 'null' or smaller then 2")
}
this.locations = locs
}
//*************************************************
// STORABLE PART
//*************************************************
override fun getVersion(): Int {
return 1
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
type = dr.readInt()
isComputeInstructions = dr.readBoolean()
currentDirection = dr.readFloat()
// read locations
val size = dr.readInt()
val locs = arrayListOf<Location>()
for (i in 0 until size) {
locs.add(Location().apply { read(dr) })
}
locations = locs.toTypedArray()
// V1
if (version >= 1) {
hasDirection = dr.readBoolean()
}
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
dw.writeInt(type)
dw.writeBoolean(isComputeInstructions)
dw.writeFloat(currentDirection)
// write locations
dw.writeInt(locations.size)
for (mLoc in locations) {
dw.writeStorable(mLoc)
}
// V1
dw.writeBoolean(hasDirection)
}
}
| mit | e902568b8e1244777ddde86f259a8e9b | 26.448598 | 102 | 0.592782 | 4.456753 | false | false | false | false |
QiBaobin/clean-architecture | data/src/main/kotlin/bob/clean/data/store/UserStoreFactory.kt | 1 | 836 | package bob.clean.data.store
import bob.clean.data.store.cache.UserCache
import bob.clean.data.store.cache.UserCacheImpl
import bob.clean.data.store.net.ServiceBuilder
import bob.clean.data.store.net.ServiceBuilderImpl
import bob.clean.data.store.net.UserServices
class UserStoreFactory(private val userCache: UserCache? = null, private val services: UserStore = UserServices(ServiceBuilderImpl().build(UserServices.Service::class.java))) {
constructor(cache: Cache, services: UserStore = UserServices(ServiceBuilderImpl().build(UserServices.Service::class.java))) : this(UserCacheImpl(cache), services)
fun createForName(name: String): UserStore {
if (userCache != null && userCache.isCachedForName(name)) {
return userCache
}
return services
}
fun createLogout() = services
}
| apache-2.0 | e2292e1a011e51805bf58ba761d52e89 | 37 | 176 | 0.751196 | 4 | false | false | false | false |
clappr/clappr-android | clappr/src/main/kotlin/io/clappr/player/plugin/control/MediaControl.kt | 1 | 16080 | package io.clappr.player.plugin.control
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.view.*
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.core.view.GestureDetectorCompat
import io.clappr.player.R
import io.clappr.player.base.*
import io.clappr.player.base.keys.Action
import io.clappr.player.base.keys.Key
import io.clappr.player.components.Core
import io.clappr.player.components.Playback
import io.clappr.player.extensions.animate
import io.clappr.player.extensions.extractInputKey
import io.clappr.player.extensions.unlessChromeless
import io.clappr.player.plugin.Plugin.State
import io.clappr.player.plugin.PluginEntry
import io.clappr.player.plugin.UIPlugin.Visibility
import io.clappr.player.plugin.core.UICorePlugin
typealias Millisecond = Long
open class MediaControl(core: Core, pluginName: String = name) :
UICorePlugin(core, name = pluginName) {
abstract class Plugin(core: Core, name: String) : UICorePlugin(core, name = name) {
enum class Panel { TOP, BOTTOM, CENTER, NONE }
enum class Position { LEFT, RIGHT, CENTER, NONE }
open var panel: Panel = Panel.NONE
open var position: Position = Position.NONE
open val isEnabled: Boolean
get() {
return state == State.ENABLED
}
open val isPlaybackIdle: Boolean
get() {
return core.activePlayback?.state == Playback.State.IDLE ||
core.activePlayback?.state == Playback.State.NONE
}
}
companion object : NamedType {
override val name = "mediaControl"
const val modalPanelViewKey = "modalPanelView"
val entry = PluginEntry.Core(
name = name,
factory = { core: Core -> MediaControl(core) }.unlessChromeless()
)
}
private val defaultShowDuration: Millisecond = 300L
private val handler = Handler()
private var lastInteractionTime = 0L
private var canShowMediaControlWhenPauseAfterTapInteraction = true
var hideAnimationEnded = false
val longShowDuration: Millisecond = 3000L
override val view by lazy {
LayoutInflater.from(applicationContext).inflate(R.layout.media_control, null) as FrameLayout
}
protected open val keysNotAllowedToIteractWithMediaControl = listOf(Key.UNDEFINED)
private val navigationKeys = listOf(Key.UP, Key.DOWN, Key.LEFT, Key.RIGHT)
protected open val allowedKeysToToggleMediaControlVisibility = navigationKeys
private val backgroundView: View by lazy { view.findViewById(R.id.background_view) as View }
private val controlsPanel by lazy { view.findViewById(R.id.controls_panel) as RelativeLayout }
private val topCenterPanel by lazy { view.findViewById(R.id.top_center) as ViewGroup }
private val topPanel by lazy { view.findViewById(R.id.top_panel) as LinearLayout }
private val topLeftPanel by lazy { view.findViewById(R.id.top_left_panel) as LinearLayout }
private val topRightPanel by lazy { view.findViewById(R.id.top_right_panel) as LinearLayout }
private val bottomPanel by lazy { view.findViewById(R.id.bottom_panel) as LinearLayout }
private val bottomLeftPanel by lazy { view.findViewById(R.id.bottom_left_panel) as LinearLayout }
private val bottomRightPanel by lazy { view.findViewById(R.id.bottom_right_panel) as LinearLayout }
private val foregroundControlsPanel by lazy { view.findViewById(R.id.foreground_controls_panel) as FrameLayout }
private val centerPanel by lazy { view.findViewById(R.id.center_panel) as LinearLayout }
protected val modalPanel by lazy { view.findViewById(R.id.modal_panel) as FrameLayout }
private val controlPlugins = mutableListOf<Plugin>()
override var state: State = State.ENABLED
set(value) {
if (value == State.ENABLED)
view.visibility = View.VISIBLE
else {
hide()
view.visibility = View.GONE
}
field = value
}
val isEnabled: Boolean
get() = state == State.ENABLED
protected val isVisible: Boolean
get() = visibility == Visibility.VISIBLE
private val isPlaybackPlaying get() = core.activePlayback?.state == Playback.State.PLAYING
private val isPlaybackIdle: Boolean
get() {
return core.activePlayback?.state == Playback.State.IDLE ||
core.activePlayback?.state == Playback.State.NONE
}
private val containerListenerIds = mutableListOf<String>()
private val playbackListenerIds = mutableListOf<String>()
private val doubleTapListener = MediaControlDoubleTapListener()
private val gestureDetector =
GestureDetectorCompat(applicationContext, MediaControlGestureDetector())
.apply {
setOnDoubleTapListener(doubleTapListener)
}
init {
hideModalPanel()
listenTo(
core,
InternalEvent.DID_CHANGE_ACTIVE_CONTAINER.value
) { setupMediaControlEvents() }
listenTo(core, InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value) { setupPlaybackEvents() }
listenTo(core, InternalEvent.DID_UPDATE_INTERACTING.value) { updateInteractionTime() }
listenTo(core, InternalEvent.DID_TOUCH_MEDIA_CONTROL.value) { updateInteractionTime() }
listenTo(core, InternalEvent.OPEN_MODAL_PANEL.value) { openModal() }
listenTo(core, InternalEvent.CLOSE_MODAL_PANEL.value) { closeModal() }
listenTo(core, Event.DID_RECEIVE_INPUT_KEY.value) { onInputReceived(it) }
}
open fun handleDidPauseEvent() {
if (!modalPanelIsOpen() && canShowMediaControlWhenPauseAfterTapInteraction) show()
canShowMediaControlWhenPauseAfterTapInteraction = true
}
open fun show(duration: Millisecond) {
val shouldAnimate = isVisible.not()
core.trigger(InternalEvent.WILL_SHOW_MEDIA_CONTROL.value)
showMediaControlElements()
showDefaultMediaControlPanels()
if (shouldAnimate) animateFadeIn(view) { setupShowDuration(duration) }
else setupShowDuration(duration)
}
private fun setupShowDuration(duration: Millisecond) {
updateInteractionTime()
if (duration > 0) {
hideDelayedWithCleanHandler(duration)
}
core.trigger(InternalEvent.DID_SHOW_MEDIA_CONTROL.value)
}
open fun animateFadeIn(view: View, onAnimationEnd: () -> Unit = {}) {
view.animate(R.anim.anim_media_control_fade_in) {
onAnimationEnd()
}
}
private fun setupMediaControlEvents() {
stopContainerListeners()
core.activeContainer?.let {
containerListenerIds.add(
listenTo(
it,
InternalEvent.ENABLE_MEDIA_CONTROL.value
) { state = State.ENABLED })
containerListenerIds.add(
listenTo(
it,
InternalEvent.DISABLE_MEDIA_CONTROL.value
) { state = State.DISABLED })
containerListenerIds.add(listenTo(it, InternalEvent.WILL_LOAD_SOURCE.value) {
state = State.ENABLED
hide()
})
}
}
private fun setupPlaybackEvents() {
stopPlaybackListeners()
core.activePlayback?.let {
playbackListenerIds.add(listenTo(it, Event.DID_PAUSE.value) {
handleDidPauseEvent()
})
}
}
protected fun modalPanelIsOpen() = modalPanel.visibility == View.VISIBLE
private fun setupPlugins() {
controlPlugins.clear()
with(core.plugins.filterIsInstance(Plugin::class.java)) {
core.options[ClapprOption.MEDIA_CONTROL_PLUGINS.value]?.let {
controlPlugins.addAll(orderedPlugins(this, it.toString()))
} ?: controlPlugins.addAll(this)
}
}
private fun orderedPlugins(list: List<Plugin>, order: String): List<Plugin> {
val pluginsOrder = order.replace(" ", "").split(",")
return list.sortedWith(compareBy { pluginsOrder.indexOf(it.name) })
}
private fun layoutPlugins() {
controlPlugins.forEach {
(it.view?.parent as? ViewGroup)?.removeView(it.view)
val parent = when (it.panel) {
Plugin.Panel.TOP ->
when (it.position) {
Plugin.Position.LEFT -> topLeftPanel
Plugin.Position.RIGHT -> topRightPanel
Plugin.Position.CENTER -> topCenterPanel
else -> topPanel
}
Plugin.Panel.BOTTOM ->
when (it.position) {
Plugin.Position.LEFT -> bottomLeftPanel
Plugin.Position.RIGHT -> bottomRightPanel
else -> bottomPanel
}
Plugin.Panel.CENTER ->
centerPanel
else -> null
}
parent?.addView(it.view)
}
}
protected fun showDefaultMediaControlPanels() {
controlsPanel.visibility = View.VISIBLE
foregroundControlsPanel.visibility = View.VISIBLE
}
open fun hideDefaultMediaControlPanels() {
controlsPanel.visibility = View.INVISIBLE
foregroundControlsPanel.visibility = View.INVISIBLE
}
private fun hideMediaControlElements() {
visibility = Visibility.HIDDEN
backgroundView.visibility = View.INVISIBLE
}
private fun showMediaControlElements() {
visibility = Visibility.VISIBLE
backgroundView.visibility = View.VISIBLE
}
protected fun hideDelayedWithCleanHandler(duration: Millisecond) {
cancelPendingHideDelayed()
hideDelayed(duration)
}
private fun hideDelayed(duration: Millisecond) {
handler.postDelayed({
val currentTime = SystemClock.elapsedRealtime()
val elapsedTime = currentTime - lastInteractionTime
val playing = (core.activePlayback?.state == Playback.State.PLAYING)
if (elapsedTime >= duration && playing) {
hide()
} else {
hideDelayed(duration)
}
}, duration)
}
private fun updateInteractionTime() {
lastInteractionTime = SystemClock.elapsedRealtime()
}
protected fun toggleVisibility() {
if (isEnabled) {
if (isVisible) {
hide()
} else {
show(longShowDuration)
}
}
}
open fun openModal() {
core.activePlayback?.pause()
hideDefaultMediaControlPanels()
animateFadeIn(modalPanel) { showModalPanel() }
val bundle = Bundle()
val map = hashMapOf<String, Any>(modalPanelViewKey to modalPanel)
bundle.putSerializable(modalPanelViewKey, map)
core.trigger(InternalEvent.DID_OPEN_MODAL_PANEL.value, bundle)
}
open fun closeModal() {
if (modalPanelIsOpen()) {
showDefaultMediaControlPanels()
animateFadeOut(modalPanel) { hideModalPanel() }
} else hideModalPanel()
core.trigger(InternalEvent.DID_CLOSE_MODAL_PANEL.value)
}
protected fun hideModalPanel() {
modalPanel.visibility = View.INVISIBLE
}
protected fun showModalPanel() {
modalPanel.visibility = View.VISIBLE
}
private fun onInputReceived(bundle: Bundle?) {
bundle?.let { handleInputKey(it) }
}
private fun handleInputKey(bundle: Bundle) {
bundle.extractInputKey()?.apply {
if (isKeysAllowedToIteractWithMediaControl(key) && action == Action.UP) {
when (isVisible) {
true -> if (navigationKeys.contains(key)) updateInteractionTime()
else -> if (allowedKeysToToggleMediaControlVisibility.contains(key)) toggleVisibility()
}
}
}
}
private fun isKeysAllowedToIteractWithMediaControl(key: Key) = keysNotAllowedToIteractWithMediaControl.contains(key).not()
private fun stopContainerListeners() {
containerListenerIds.forEach(::stopListening)
containerListenerIds.clear()
}
private fun stopPlaybackListeners() {
playbackListenerIds.forEach(::stopListening)
playbackListenerIds.clear()
}
private fun animateFadeOut(view: View, onAnimationEnd: () -> Unit = {}) {
view.animate(R.anim.anim_media_control_fade_out) {
onAnimationEnd()
}
}
protected fun setBackground(context: Context, resource: Int) {
backgroundView.background = ContextCompat.getDrawable(context, resource)
}
@SuppressLint("ClickableViewAccessibility")
override fun render() {
super.render()
view.setOnTouchListener { _, event -> gestureDetector.onTouchEvent(event) }
setupPlugins()
Handler().post { layoutPlugins() }
hide()
hideModalPanel()
}
@SuppressLint("ClickableViewAccessibility")
override fun destroy() {
controlPlugins.clear()
stopContainerListeners()
stopPlaybackListeners()
view.setOnTouchListener(null)
cancelPendingHideDelayed()
super.destroy()
}
override fun hide() {
if (isEnabled && isPlaybackIdle) return
hideAnimationEnded = false
core.trigger(InternalEvent.WILL_HIDE_MEDIA_CONTROL.value)
if (isVisible) animateFadeOut(view) { hideMediaControl() }
else hideMediaControl()
}
private fun hideMediaControl() {
hideMediaControlElements()
hideDefaultMediaControlPanels()
hideModalPanel()
hideAnimationEnded = true
cancelPendingHideDelayed()
core.trigger(InternalEvent.DID_HIDE_MEDIA_CONTROL.value)
}
protected fun cancelPendingHideDelayed() {
handler.removeCallbacksAndMessages(null)
}
override fun show() {
show(defaultShowDuration)
}
class MediaControlGestureDetector : GestureDetector.OnGestureListener {
override fun onDown(e: MotionEvent?) = true
override fun onShowPress(e: MotionEvent?) {}
override fun onSingleTapUp(e: MotionEvent?) = false
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent?,
velocityX: Float,
velocityY: Float
) = false
override fun onScroll(
e1: MotionEvent?,
e2: MotionEvent?,
distanceX: Float,
distanceY: Float
) = false
override fun onLongPress(e: MotionEvent?) {}
}
inner class MediaControlDoubleTapListener : GestureDetector.OnDoubleTapListener {
override fun onDoubleTap(event: MotionEvent?): Boolean {
canShowMediaControlWhenPauseAfterTapInteraction = isPlaybackPlaying
triggerDoubleTapEvent(event)
hide()
return true
}
override fun onDoubleTapEvent(e: MotionEvent?) = false
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
canShowMediaControlWhenPauseAfterTapInteraction = true
toggleVisibility()
return true
}
}
private fun triggerDoubleTapEvent(event: MotionEvent?) {
Bundle().apply {
putInt(InternalEventData.HEIGHT.value, view.height)
putInt(InternalEventData.WIDTH.value, view.width)
event?.let {
putFloat(InternalEventData.TOUCH_X_AXIS.value, it.x)
putFloat(InternalEventData.TOUCH_Y_AXIS.value, it.y)
}
}.also {
core.trigger(InternalEvent.DID_DOUBLE_TOUCH_MEDIA_CONTROL.value, it)
}
}
} | bsd-3-clause | af839133098dc8b692064705c2af2ce3 | 32.088477 | 126 | 0.638246 | 4.810051 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/adapters/holders/AppHolder.kt | 3 | 2011 | /*
* Copyright (C) 2014-2020 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.adapters.holders
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.amaze.filemanager.R
import com.amaze.filemanager.ui.views.ThemedTextView
class AppHolder(view: View) : RecyclerView.ViewHolder(view) {
@JvmField
val apkIcon: ImageView = view.findViewById(R.id.apk_icon)
@JvmField
val txtTitle: ThemedTextView = view.findViewById(R.id.firstline)
@JvmField
val rl: RelativeLayout = view.findViewById(R.id.second)
@JvmField
val txtDesc: TextView = view.findViewById(R.id.date)
@JvmField
val about: ImageButton = view.findViewById(R.id.properties)
@JvmField
val summary: RelativeLayout = view.findViewById(R.id.summary)
init {
apkIcon.visibility = View.VISIBLE
view.findViewById<ImageView>(R.id.picture_icon).visibility = View.GONE
view.findViewById<ImageView>(R.id.generic_icon).visibility = View.GONE
}
}
| gpl-3.0 | f4b1773e0bf9f861ef3a6630f8715f89 | 34.910714 | 107 | 0.749378 | 4.046278 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/links/GitHubIngestionLinksPayload.kt | 1 | 732 | package net.nemerosa.ontrack.extension.github.ingestion.extensions.links
import net.nemerosa.ontrack.extension.github.ingestion.extensions.support.AbstractGitHubIngestionBuildPayload
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.json.format
class GitHubIngestionLinksPayload(
owner: String,
repository: String,
runId: Long? = null,
buildName: String? = null,
buildLabel: String? = null,
val buildLinks: List<GitHubIngestionLink>,
val addOnly: Boolean,
) : AbstractGitHubIngestionBuildPayload(
owner, repository, runId, buildName, buildLabel
) {
companion object {
const val ADD_ONLY_DEFAULT = false
}
override fun toString(): String = asJson().format()
}
| mit | f69459d76c3a191f137df6d8fcc8068d | 30.826087 | 109 | 0.75 | 4.182857 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubChooseAccountDialog.kt | 1 | 3265 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import java.awt.Component
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JTextArea
class GithubChooseAccountDialog(project: Project?, parentComponent: Component?,
accounts: Collection<GithubAccount>,
descriptionText: String?, showHosts: Boolean, allowDefault: Boolean,
title: String = "Choose Github Account", okText: String = "Choose")
: DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) {
private val description: JTextArea? = descriptionText?.let {
JTextArea().apply {
font = UIUtil.getLabelFont()
text = it
lineWrap = true
wrapStyleWord = true
isEditable = false
isFocusable = false
isOpaque = false
border = null
margin = JBUI.emptyInsets()
}
}
private val accountsList: JBList<GithubAccount> = JBList<GithubAccount>(accounts).apply {
cellRenderer = object : ColoredListCellRenderer<GithubAccount>() {
override fun customizeCellRenderer(list: JList<out GithubAccount>,
value: GithubAccount,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
append(value.name)
if (showHosts) {
append(" ")
append(value.server.toString(), SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
border = JBUI.Borders.empty(0, UIUtil.DEFAULT_HGAP)
}
}
}
private val setDefaultCheckBox: JBCheckBox? = if (allowDefault) JBCheckBox("Set as default account for current project") else null
init {
this.title = title
setOKButtonText(okText)
init()
accountsList.selectedIndex = 0
}
override fun doValidate(): ValidationInfo? {
return if (accountsList.selectedValue == null) ValidationInfo("Account is not selected", accountsList) else null
}
val account: GithubAccount get() = accountsList.selectedValue
val setDefault: Boolean get() = setDefaultCheckBox?.isSelected ?: false
override fun createCenterPanel(): JComponent? {
return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.apply { description?.run(::addToTop) }
.addToCenter(JBScrollPane(accountsList).apply { preferredSize = JBDimension(150, 80) })
.apply { setDefaultCheckBox?.run(::addToBottom) }
}
override fun getPreferredFocusedComponent() = accountsList
} | apache-2.0 | ed1f42ea3185bda8ed57896dd85aaf4f | 39.320988 | 140 | 0.686677 | 4.94697 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/BaseCustomView.kt | 1 | 1103 | package com.hewking.custom
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
/**
* Created by test on 2018/1/3.
*/
open class BaseCustomView(context : Context , attrs : AttributeSet): View(context,attrs) {
init {
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
}
fun resolveSize2(size : Int, spec : Int) : Int{
val specsize = MeasureSpec.getSize(spec)
val mode = MeasureSpec.getMode(spec)
var result = size
when(mode) {
MeasureSpec.AT_MOST -> {
if (specsize < size) {
result = specsize
}
}
MeasureSpec.EXACTLY -> {
result = specsize
}
MeasureSpec.UNSPECIFIED -> {
}
}
return result
}
} | mit | 5f6f8a5242ea834964287e0923d7fdca | 18.849057 | 90 | 0.543971 | 4.693617 | false | false | false | false |
ohmae/mmupnp | sample/src/main/java/net/mm2d/upnp/sample/ServiceNode.kt | 1 | 2342 | /*
* Copyright (c) 2016 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.sample
import kotlinx.coroutines.runBlocking
import net.mm2d.upnp.Http
import net.mm2d.upnp.Service
import java.awt.Component
import java.awt.Desktop
import java.io.IOException
import java.net.URISyntaxException
import javax.swing.JFrame
import javax.swing.JMenuItem
import javax.swing.JPopupMenu
class ServiceNode(service: Service) : UpnpNode(service) {
var isSubscribing: Boolean = false
private set
override fun getDetailXml(): String = formatXml(getUserObject().description)
init {
val actions = service.actionList
for (action in actions) {
add(ActionNode(action))
}
add(StateVariableListNode(service.stateVariableList))
}
override fun getUserObject(): Service = super.getUserObject() as Service
override fun formatDescription(): String = Formatter.format(getUserObject())
override fun toString(): String = getUserObject().serviceType
override fun showContextMenu(frame: JFrame, invoker: Component, x: Int, y: Int) {
val menu = JPopupMenu()
menu.add(JMenuItem("Open Service Description").also {
it.addActionListener { openServerDescription() }
})
if (isSubscribing) {
menu.add(JMenuItem("Unsubscribe").also {
it.addActionListener { unsubscribe() }
})
} else {
menu.add(JMenuItem("Subscribe").also {
it.addActionListener { subscribe() }
})
}
menu.show(invoker, x, y)
}
private fun openServerDescription() {
val service = getUserObject()
val device = service.device
try {
val uri = Http.makeAbsoluteUrl(device.baseUrl, service.scpdUrl, device.scopeId).toURI()
Desktop.getDesktop().browse(uri)
} catch (e: IOException) {
e.printStackTrace()
} catch (e: URISyntaxException) {
e.printStackTrace()
}
}
private fun subscribe() {
isSubscribing = runBlocking { getUserObject().subscribe(true) }
}
private fun unsubscribe() {
isSubscribing = !runBlocking { getUserObject().unsubscribe() }
}
}
| mit | 7480370810e3a8a5aacbeda9b24acf18 | 29.710526 | 99 | 0.642674 | 4.479846 | false | false | false | false |
permissions-dispatcher/PermissionsDispatcher | processor/src/main/kotlin/permissions/dispatcher/processor/util/Extensions.kt | 2 | 5425 | package permissions.dispatcher.processor.util
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.OnShowRationale
import permissions.dispatcher.processor.TYPE_UTILS
import javax.lang.model.element.*
import javax.lang.model.type.TypeMirror
/**
* Returns the package name of a TypeElement.
*/
fun TypeElement.packageName() = enclosingElement.packageName()
private fun Element?.packageName(): String {
return when (this) {
is TypeElement -> packageName()
is PackageElement -> qualifiedName.toString()
else -> this?.enclosingElement?.packageName() ?: ""
}
}
// to address kotlin internal method try to remove `$module_name_build_variant` from element info.
// ex: showCamera$sample_kotlin_debug → showCamera
internal fun String.trimDollarIfNeeded(): String {
val index = indexOf("$")
return if (index == -1) this else substring(0, index)
}
/**
* Returns the simple name of an Element as a string.
*/
fun Element.simpleString() = this.simpleName.toString().trimDollarIfNeeded()
/**
* Returns the simple name of a TypeMirror as a string.
*/
fun TypeMirror.simpleString(): String {
val toString: String = this.toString()
val indexOfDot: Int = toString.lastIndexOf('.')
return if (indexOfDot == -1) toString else toString.substring(indexOfDot + 1)
}
/**
* Returns whether or not an Element is annotated with the provided Annotation class.
*/
fun <A : Annotation> Element.hasAnnotation(annotationType: Class<A>): Boolean =
this.getAnnotation(annotationType) != null
/**
* Returns whether a variable is nullable by inspecting its annotations.
*/
fun VariableElement.isNullable(): Boolean =
this.annotationMirrors
.asSequence()
.map { it.annotationType.simpleString() }
.toList()
.contains("Nullable")
/**
* Maps a variable to its TypeName, applying necessary transformations
* for Java primitive types & mirroring the variable's nullability settings.
*/
fun VariableElement.asPreparedType(): TypeName =
this.asType()
.asTypeName()
.correctJavaTypeToKotlinType()
.mapToNullableTypeIf(this.isNullable())
/**
* Returns the inherent value() of a permission Annotation.
* <p>
* If this is invoked on an Annotation that's not defined by PermissionsDispatcher, this returns an empty list.
*/
fun Annotation.permissionValue(): List<String> {
when (this) {
is NeedsPermission -> return this.value.asList()
is OnShowRationale -> return this.value.asList()
is OnPermissionDenied -> return this.value.asList()
is OnNeverAskAgain -> return this.value.asList()
}
return emptyList()
}
/**
* Returns a list of enclosed elements annotated with the provided Annotations.
*/
fun <A : Annotation> Element.childElementsAnnotatedWith(annotationClass: Class<A>): List<ExecutableElement> =
this.enclosedElements
.asSequence()
.filter { it.hasAnnotation(annotationClass) }
.map { it as ExecutableElement }
.toList()
/**
* Returns whether or not a TypeMirror is a subtype of the provided other TypeMirror.
*/
fun TypeMirror.isSubtypeOf(ofType: TypeMirror): Boolean = TYPE_UTILS.isSubtype(this, ofType)
fun FileSpec.Builder.addProperties(properties: List<PropertySpec>): FileSpec.Builder {
properties.forEach { addProperty(it) }
return this
}
fun FileSpec.Builder.addFunctions(functions: List<FunSpec>): FileSpec.Builder {
functions.forEach { addFunction(it) }
return this
}
fun FileSpec.Builder.addTypes(types: List<TypeSpec>): FileSpec.Builder {
types.forEach { addType(it) }
return this
}
/**
* To avoid KotlinPoet bugs return java.lang.class when type name is in kotlin package.
* TODO: Remove this method after being addressed on KotlinPoet side.
*/
fun TypeName.correctJavaTypeToKotlinType(): TypeName {
return if (this is ParameterizedTypeName) {
val typeArguments = this.typeArguments.map { it.correctJavaTypeToKotlinType() }.toTypedArray()
val rawType = ClassName.bestGuess(this.rawType.correctJavaTypeToKotlinType().toString())
return rawType.parameterizedBy(*typeArguments)
} else when (toString()) {
"java.lang.Byte" -> ClassName("kotlin", "Byte")
"java.lang.Double" -> ClassName("kotlin", "Double")
"java.lang.Object" -> ClassName("kotlin", "Any")
"java.lang.String" -> ClassName("kotlin", "String")
"java.util.Set" -> ClassName("kotlin.collections", "MutableSet")
"java.util.List" -> ClassName("kotlin.collections", "MutableList")
// https://github.com/permissions-dispatcher/PermissionsDispatcher/issues/599
// https://github.com/permissions-dispatcher/PermissionsDispatcher/issues/619
"kotlin.ByteArray", "kotlin.collections.List", "kotlin.collections.Set",
"kotlin.collections.MutableList", "kotlin.collections.MutableSet" -> this
else -> this
}
}
/**
* Returns this TypeName as nullable or non-nullable based on the given condition.
*/
fun TypeName.mapToNullableTypeIf(nullable: Boolean) = copy(nullable = nullable)
| apache-2.0 | 9048a5f7f7cbd0948720613fa0b679bb | 36.4 | 111 | 0.703116 | 4.515404 | false | false | false | false |
ivan-osipov/Clabo | src/main/kotlin/com/github/ivan_osipov/clabo/api/model/VideoNote.kt | 1 | 447 | package com.github.ivan_osipov.clabo.api.model
import com.google.gson.annotations.SerializedName
class VideoNote : AbstractFileDescriptor() {
@SerializedName("length")
private var _length: Int? = null
val length: Int
get() = _length!!
@SerializedName("duration")
private var _duration: Int? = null
val duration: Int
get() = _duration!!
@SerializedName("thumb")
var thumb: PhotoSize? = null
} | apache-2.0 | 1b7f02e7be44467a46e9b31b2612880f | 19.363636 | 49 | 0.659955 | 4.063636 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/osgi/impl/Activator.kt | 2 | 1262 | package tornadofx.osgi.impl
import org.osgi.framework.BundleActivator
import org.osgi.framework.BundleContext
import org.osgi.service.url.URLStreamHandlerService
import java.util.*
internal class Activator : BundleActivator {
lateinit var applicationListener: ApplicationListener
lateinit var stylesheetListener: StylesheetListener
lateinit var viewListener: ViewListener
lateinit var interceptorListener: InterceptorListener
override fun start(context: BundleContext) {
applicationListener = ApplicationListener(context)
stylesheetListener = StylesheetListener(context)
viewListener = ViewListener(context)
interceptorListener = InterceptorListener(context)
context.addServiceListener(applicationListener)
context.addServiceListener(stylesheetListener)
context.addServiceListener(viewListener)
context.addServiceListener(interceptorListener)
val cssOptions = Hashtable<String, String>()
cssOptions["url.handler.protocol"] = "css"
cssOptions["url.content.mimetype"] = "text/css"
context.registerService(URLStreamHandlerService::class.java, CSSURLStreamHandlerService(), cssOptions)
}
override fun stop(context: BundleContext) {
}
} | apache-2.0 | cff4d0e9d024d1f634113bfd469c4881 | 41.1 | 110 | 0.765452 | 5.007937 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/psi/SignatureData.kt | 1 | 1343 | package app.cash.sqldelight.core.lang.psi
import app.cash.sqldelight.core.lang.util.type
import com.alecstrong.sql.psi.core.psi.QueryElement.QueryColumn
import com.alecstrong.sql.psi.core.psi.SqlColumnDef
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.ParameterAdditionalData
fun QueryColumn.parameterValue(): SuggestedRefactoringSupport.Parameter? = element.type().let { type ->
val column = type.column ?: return null
SuggestedRefactoringSupport.Parameter(
id = type.name,
name = type.name,
type = column.columnType.typeName.text,
additionalData = column.columnConstraintList.takeIf { it.isNotEmpty() }?.let { list ->
ColumnConstraints((list.filter { it.text.isNotBlank() }.joinToString(" ") { it.text.trim() }))
},
)
}
fun SqlColumnDef.asParameter() = SuggestedRefactoringSupport.Parameter(
id = columnName.name,
name = columnName.name,
type = columnType.typeName.text,
additionalData = columnConstraintList.takeIf { it.isNotEmpty() }?.let { list ->
ColumnConstraints((list.filter { it.text.isNotBlank() }.joinToString(" ") { it.text.trim() }))
},
)
data class ColumnConstraints(val constraints: String) : ParameterAdditionalData {
override fun toString(): String {
return constraints
}
}
| apache-2.0 | fc2f9453d3c96905b82f1565ec606b95 | 38.5 | 103 | 0.753537 | 4.27707 | false | false | false | false |
hummatli/MAHAndroidUpdater | android-app-updater/src/main/java/com/mobapphome/androidappupdater/tools/HttpTools.kt | 1 | 2420 | package com.mobapphome.androidappupdater.tools
import java.io.IOException
import org.json.JSONException
import org.json.JSONObject
import org.jsoup.Jsoup
import android.util.Log
object HttpTools {
@Throws(IOException::class)
fun requestProgramInfo(url: String?): ProgramInfo? {
val doc = Jsoup
.connect(url?.trim { it <= ' ' })
.ignoreContentType(true)
.timeout(3000)
// .header("Host", "85.132.44.28")
.header("Connection", "keep-alive")
// .header("Content-Length", "111")
.header("Cache-Control", "max-age=0")
.header("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
// .header("Origin", "http://85.132.44.28")
.header("User-Agent",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Referer", url?.trim { it <= ' ' })
// This is Needed
.header("Accept-Encoding", "gzip,deflate,sdch")
.header("Accept-Language", "en-US,en;q=0.8,ru;q=0.6")
// .userAgent("Mozilla")
.get()
val jsonStr = doc.body().text()
//Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, jsonStr);
try {
val reader = JSONObject(jsonStr)
// try {
// ret.isRunMode =
// } catch (e: JSONException) {
// Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "MAH Updater is_run_mode is not available")
// }
return ProgramInfo(
name = reader.getString("name"),
updateDate = reader.getString("update_date"),
updateInfo = reader.getString("update_info"),
uriCurrent = reader.getString("uri_current"),
versionCodeCurrent = reader.getInt("version_code_current"),
versionCodeMin = reader.getInt("version_code_min"),
isRunMode = reader.getBoolean("is_run_mode"))
} catch (e: JSONException) {
Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, e.toString())
return null
}
}
}
| apache-2.0 | bf55aabae6c6454d9727c9273c8b3e00 | 37.412698 | 129 | 0.525207 | 4.080944 | false | false | false | false |
doerfli/hacked | app/src/main/kotlin/li/doerf/hacked/ui/fragments/PwnedPasswordFragment.kt | 1 | 7014 | package li.doerf.hacked.ui.fragments
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.navigation.fragment.navArgs
import io.reactivex.processors.PublishProcessor
import li.doerf.hacked.CustomEvent
import li.doerf.hacked.HackedApplication
import li.doerf.hacked.R
import li.doerf.hacked.remote.pwnedpasswords.PwnedPassword
import li.doerf.hacked.util.Analytics
import li.doerf.hacked.util.NavEvent
import li.doerf.hacked.utils.StringHelper
/**
* A simple [Fragment] subclass.
*/
class PwnedPasswordFragment : Fragment() {
private lateinit var navEvents: PublishProcessor<NavEvent>
private lateinit var fragmentRootView: View
private var isFullFragment: Boolean = false
private lateinit var pwnedButton: Button
private lateinit var progressBar: ProgressBar
private lateinit var passwordField: EditText
private lateinit var passwordPwned: TextView
private lateinit var passwordOk: TextView
private lateinit var errorMsg: TextView
private lateinit var myBroadcastReceiver: LocalBroadcastReceiver
private var enteredPassword: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
val args: PwnedPasswordFragmentArgs by navArgs()
isFullFragment = true
enteredPassword = args.password
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
// Inflate the layout for this fragment
fragmentRootView = inflater.inflate(R.layout.fragment_pwned_password, container, false)
passwordField = fragmentRootView.findViewById(R.id.password)
passwordOk = fragmentRootView.findViewById(R.id.result_ok)
passwordPwned = fragmentRootView.findViewById(R.id.result_pwned)
progressBar = fragmentRootView.findViewById(R.id.progressbar)
pwnedButton = fragmentRootView.findViewById(R.id.check_pwned)
errorMsg = fragmentRootView.findViewById(R.id.error_msg)
pwnedButton.setOnClickListener { checkPassword(passwordField.text.toString()) }
passwordField.doAfterTextChanged { action ->
pwnedButton.isEnabled = action.toString().isNotEmpty()
passwordOk.visibility = View.GONE
passwordPwned.visibility = View.GONE
}
passwordField.setOnKeyListener { _, kCode, evt ->
when {
((kCode == KeyEvent.KEYCODE_ENTER) && (evt.action == KeyEvent.ACTION_DOWN)) -> {
checkPassword(passwordField.text.toString())
return@setOnKeyListener true
}
else -> false
}
}
if (isFullFragment) {
fragmentRootView.findViewById<TextView>(R.id.title_pwned_passwords).visibility = View.GONE
}
return fragmentRootView
}
override fun onAttach(context: Context) {
super.onAttach(context)
navEvents = (requireActivity().applicationContext as HackedApplication).navEvents
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(fragmentRootView.windowToken, 0)
}
override fun onResume() {
super.onResume()
registerReceiver()
Analytics.trackView("Fragment~Password")
if (isFullFragment && enteredPassword != "" ) {
passwordField.setText(enteredPassword)
checkPassword(enteredPassword)
enteredPassword = ""
}
passwordOk.visibility = View.GONE
passwordPwned.visibility = View.GONE
progressBar.visibility = View.GONE
}
override fun onPause() {
passwordField.text.clear()
unregisterReceiver()
super.onPause()
}
private fun checkPassword(password: String) {
// navigate to full screen pwnedpassword fragment
if (! isFullFragment) {
navEvents.onNext(NavEvent(NavEvent.Destination.PWNED_PASSWORDS, null, password))
return
}
passwordOk.visibility = View.GONE
passwordPwned.visibility = View.GONE
progressBar.visibility = View.VISIBLE
errorMsg.visibility = View.GONE
PwnedPassword(LocalBroadcastManager.getInstance(requireContext())).check(password)
Analytics.trackCustomEvent(CustomEvent.CHECK_PASSWORD_PWNED)
}
private fun registerReceiver() {
val intentFilter = IntentFilter(PwnedPassword.BROADCAST_ACTION_PASSWORD_PWNED)
myBroadcastReceiver = LocalBroadcastReceiver(this)
LocalBroadcastManager.getInstance(requireContext()).registerReceiver(myBroadcastReceiver, intentFilter)
}
private fun unregisterReceiver() {
LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(myBroadcastReceiver)
}
private fun handleResult(pwned: Boolean, numPwned: Int, exception: Boolean) {
progressBar.visibility = View.GONE
if (exception) {
Analytics.trackCustomEvent(CustomEvent.PASSWORD_PWNED_EXCEPTION)
errorMsg.visibility = View.VISIBLE
} else if (!pwned) {
Analytics.trackCustomEvent(CustomEvent.PASSWORD_NOT_PWNED)
passwordOk.visibility = View.VISIBLE
} else {
Analytics.trackCustomEvent(CustomEvent.PASSWORD_PWNED)
passwordPwned.visibility = View.VISIBLE
val t = getString(R.string.password_pwned, StringHelper.addDigitSeperator(numPwned.toString()))
passwordPwned.text = t
}
}
private class LocalBroadcastReceiver(private val pwnedPasswordFragment: PwnedPasswordFragment) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "received local broadcast message")
pwnedPasswordFragment.handleResult(
intent.getBooleanExtra(PwnedPassword.EXTRA_PASSWORD_PWNED, false),
intent.getIntExtra(PwnedPassword.EXTRA_PASSWORD_PWNED_Count, 0),
intent.getBooleanExtra(PwnedPassword.EXTRA_EXCEPTION, false))
}
}
companion object {
const val TAG = "PwnedPasswordFragment"
}
}
| apache-2.0 | 2a6ffd931f75047c6a42341a6d17799e | 38.184358 | 122 | 0.700884 | 4.894627 | false | false | false | false |
dsulimchuk/DynamicQuery | src/main/kotlin/com/github/dsulimchuk/dynamicquery/Sql.kt | 1 | 1457 | package com.github.dsulimchuk.dynamicquery
import com.github.dsulimchuk.dynamicquery.core.QueryDsl
import mu.KLogging
import org.apache.commons.beanutils.PropertyUtils
import javax.persistence.EntityManager
import javax.persistence.Query
/**
* @author Dmitrii Sulimchuk
* created 23/10/16
*/
class Sql<T : Any>(val initQueryDsl: QueryDsl<T>.() -> Unit) : AbstractDialect() {
companion object : KLogging()
/**
* Prepare native query
*/
fun prepare(em: EntityManager, parameter: T, projection: String? = null): Query {
val query = QueryDsl(parameter)
query.initQueryDsl()
val queryText = query.prepareText(projection)
val result = em.createNativeQuery(queryText)
val allParameters = findAllQueryParameters(queryText)
if (allParameters.isNotEmpty()) {
if (allParameters.size == 1 && isBaseType(query.parameter)) {
logger.debug { "set parameter ${allParameters[0]} to ${query.parameter}" }
result.setParameter(allParameters[0], query.parameter)
} else {
allParameters
.map { it to PropertyUtils.getProperty(query.parameter, it) }
.forEach {
logger.debug { "set parameter ${it.first} to ${it.second}" }
result.setParameter(it.first, it.second)
}
}
}
return result
}
}
| mit | 1a6c3b4375dc5fd373673109d550f786 | 30.673913 | 90 | 0.609472 | 4.538941 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/BatchNormalization.kt | 1 | 2761 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
@PreHookRule(nodeNames = [],opNames = ["BatchNormalization"],frameworkName = "onnx")
class BatchNormalization: PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val inputVariable = sd.getVariable(op.inputsToOp[0])
val scale = sd.getVariable(op.inputsToOp[1])
val bias = sd.getVariable(op.inputsToOp[2])
val inputMean = sd.getVariable(op.inputsToOp[3])
val inputVariance = sd.getVariable(op.inputsToOp[4])
val epsilon = attributes.getOrDefault("epsilon",1e-5) as Number
val dim = 1
val output = sd.nn().batchNorm(outputNames[0],inputVariable,inputMean,inputVariance,scale,bias,epsilon.toDouble(),dim)
return mapOf(output.name() to listOf(output))
}
} | apache-2.0 | bac31099513411db4190523e25563d13 | 49.218182 | 184 | 0.707715 | 4.300623 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/findUsages/FortranEntityDeclFindUsagesHandler.kt | 1 | 1158 | package org.jetbrains.fortran.ide.findUsages
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.fortran.lang.psi.*
class FortranEntityDeclFindUsagesHandler (
element: FortranEntityDecl,
factory: FortranFindUsagesHandlerFactory
) : FortranFindUsagesHandler<FortranEntityDecl>(element, factory) {
override fun calculateScope(element: PsiElement, searchScope: SearchScope): SearchScope {
var scope : SearchScope = searchScope
val unit = runReadAction{PsiTreeUtil.getParentOfType(element, FortranProgramUnit::class.java)}
val inter = runReadAction{PsiTreeUtil.getParentOfType(element, FortranInterfaceSpecification::class.java)}
if ((runReadAction{ element.parent !is FortranBeginUnitStmt } && (unit !is FortranModule)
&& (unit !is FortranSubmodule)) || inter != null) {
scope = runReadAction { GlobalSearchScope.fileScope(element.containingFile) }
}
return scope
}
} | apache-2.0 | e3cf033371937db7dad30b5e9291f8ca | 45.36 | 114 | 0.753886 | 5.012987 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsDanglingElseInspection.kt | 3 | 2354 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.psi.RsElseBranch
import org.rust.lang.core.psi.RsIfExpr
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.endOffset
import org.rust.lang.core.psi.ext.rangeWithPrevSpace
import org.rust.lang.core.psi.ext.startOffset
/**
* Detects `else if` statements broken by new lines. A partial analogue
* of the Clippy's suspicious_else_formatting lint.
* Quick fix 1: Remove `else`
* Quick fix 2: Join `else if`
*/
class RsDanglingElseInspection : RsLocalInspectionTool() {
override fun getDisplayName() = "Dangling else"
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitElseBranch(expr: RsElseBranch) {
val elseEl = expr.`else`
val breakEl = elseEl.rightSiblings
.dropWhile { (it is PsiWhiteSpace || it is PsiComment) && '\n' !in it.text }
.firstOrNull() ?: return
val ifEl = breakEl.rightSiblings
.dropWhile { it !is RsIfExpr }
.firstOrNull() ?: return
holder.registerProblem(
expr,
TextRange(0, ifEl.startOffsetInParent + 2),
"Suspicious `else if` formatting",
SubstituteTextFix.delete(
"Remove `else`",
expr.containingFile,
elseEl.rangeWithPrevSpace(expr.prevSibling)
),
SubstituteTextFix.replace(
"Join `else if`",
expr.containingFile,
TextRange(elseEl.endOffset, ifEl.startOffset),
" "
))
}
}
override val isSyntaxOnly: Boolean = true
private val PsiElement.rightSiblings: Sequence<PsiElement>
get() = generateSequence(this.nextSibling) { it.nextSibling }
}
| mit | b5b2b629d55932783f925a3c9bf0d800 | 37.590164 | 96 | 0.604928 | 4.624754 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/SimplifyBooleanExpressionIntentionTest.kt | 3 | 6482 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
/**
* @author Moklev Vyacheslav
*/
class SimplifyBooleanExpressionIntentionTest : RsIntentionTestBase(SimplifyBooleanExpressionIntention::class) {
fun `test or`() = doAvailableTest("""
fn main() {
let a = true /*caret*/|| false;
}
""", """
fn main() {
let a = true;
}
""")
fun `test and`() = doAvailableTest("""
fn main() {
let a = true /*caret*/&& false;
}
""", """
fn main() {
let a = false;
}
""")
fun `test xor`() = doAvailableTest("""
fn main() {
let a = true /*caret*/^ false;
}
""", """
fn main() {
let a = true;
}
""")
fun `test not`() = doAvailableTest("""
fn main() {
let a = !/*caret*/true;
}
""", """
fn main() {
let a = false;
}
""")
fun `test equals true`() = doAvailableTest("""
fn main() {
let a = foo ==/*caret*/ true;
}
""", """
fn main() {
let a = foo;
}
""")
fun `test equals false`() = doAvailableTest("""
fn main() {
let a = /*caret*/foo == false;
}
""", """
fn main() {
let a = !foo;
}
""")
fun `test not equals true`() = doAvailableTest("""
fn main() {
let a = foo != /*caret*/true;
}
""", """
fn main() {
let a = !foo;
}
""")
fun `test not equals false`() = doAvailableTest("""
fn main() {
let a = foo != false/*caret*/;
}
""", """
fn main() {
let a = foo;
}
""")
fun `test parens`() = doAvailableTest("""
fn main() {
let a = (/*caret*/true);
}
""", """
fn main() {
let a = true;
}
""")
fun `test short circuit or 1`() = doAvailableTest("""
fn main() {
let a = true /*caret*/|| b;
}
""", """
fn main() {
let a = true;
}
""")
fun `test short circuit or 2`() = doAvailableTest("""
fn main() {
let a = false /*caret*/|| a;
}
""", """
fn main() {
let a = a;
}
""")
fun `test short circuit and 1`() = doAvailableTest("""
fn main() {
let a = false /*caret*/&& b;
}
""", """
fn main() {
let a = false;
}
""")
fun `test short circuit and 2`() = doAvailableTest("""
fn main() {
let a = true /*caret*/&& a;
}
""", """
fn main() {
let a = a;
}
""")
fun `test non equivalent 1`() = doAvailableTest("""
fn main() {
let a = a ||/*caret*/ true || true;
}
""", """
fn main() {
let a = true;
}
""")
fun `test non equivalent 2`() = doAvailableTest("""
fn main() {
let a = a ||/*caret*/ false;
}
""", """
fn main() {
let a = a;
}
""")
fun `test non equivalent 3`() = doAvailableTest("""
fn main() {
let a = a &&/*caret*/ false;
}
""", """
fn main() {
let a = false;
}
""")
fun `test non equivalent 4`() = doAvailableTest("""
fn main() {
let a = a &&/*caret*/ true;
}
""", """
fn main() {
let a = a;
}
""")
fun `test complex non equivalent 1`() = doAvailableTest("""
fn main() {
let a = f() && (g() &&/*caret*/ false);
}
""", """
fn main() {
let a = f() && (false);
}
""")
fun `test complex non equivalent 2`() = doAvailableTest("""
fn main() {
let a = 1 > 2 &&/*caret*/ 2 > 3 && 3 > 4 || true;
}
""", """
fn main() {
let a = true;
}
""")
fun `test complex non equivalent 3`() = doAvailableTest("""
fn main() {
let a = 1 > 2 &&/*caret*/ 2 > 3 && 3 > 4 || false;
}
""", """
fn main() {
let a = 1 > 2 && 2 > 3 && 3 > 4;
}
""")
fun `test not available 3`() = doUnavailableTest("""
fn main() {
let a = a /*caret*/&& b;
}
""")
fun `test not available 4`() = doUnavailableTest("""
fn main() {
let a = true /*caret*/^ a;
}
""")
fun `test not available 5`() = doUnavailableTest("""
fn main() {
let a = !/*caret*/a;
}
""")
fun `test not available 6`() = doUnavailableTest("""
fn main() {
let a = /*caret*/true;
}
""")
fun `test complex 1`() = doAvailableTest("""
fn main() {
let a = !(false ^ false) /*caret*/|| b;
}
""", """
fn main() {
let a = true;
}
""")
fun `test complex 2`() = doAvailableTest("""
fn main() {
let a = !(false /*caret*/^ false) || b;
}
""", """
fn main() {
let a = true;
}
""")
fun `test complex 3`() = doAvailableTest("""
fn main() {
let a = ((((((((((true)))) || b && /*caret*/c && d))))));
}
""", """
fn main() {
let a = true;
}
""")
fun `test complex 4`() = doAvailableTest("""
fn main() {
let a = true || x >= y + z || foo(1, 2, r) == 42 || flag || (flag2 && !flag3/*caret*/);
}
""", """
fn main() {
let a = true;
}
""")
fun `test find last`() = doAvailableTest("""
fn main() {
let a = true || x > 0 ||/*caret*/ x < 0 || y > 2 || y < 2 || flag;
}
""", """
fn main() {
let a = true;
}
""")
fun `test negation parens`() = doAvailableTest("""
fn main() {
if !(1 == 2/*caret*/) {}
}
""", """
fn main() {
if 1 != 2 {}
}
""")
fun `test incomplete code`() = doUnavailableTest("""
fn main() {
xs.iter()
.map(|/*caret*/)
}
""")
}
| mit | 64f8141e37cbf94ee3c0070c4c25639f | 20.463576 | 111 | 0.359611 | 4.214564 | false | true | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/person/model/Identity.kt | 1 | 687 | package de.tum.`in`.tumcampusapp.component.tumui.person.model
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
@Xml(name = "row")
data class Identity(@PropertyElement(name = "vorname") val firstName: String = "",
@PropertyElement(name = "familienname") val lastName: String = "",
@PropertyElement(name = "kennung") val id: String = "",
@PropertyElement val obfuscated_id: String = "",
@Element val obfuscated_ids: ObfuscatedIds = ObfuscatedIds()) {
override fun toString(): String = "$firstName $lastName"
}
| gpl-3.0 | f31556b8ee0781c32a1ed89180453c17 | 48.071429 | 86 | 0.666667 | 4.432258 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/ui/dialog/VerificationCodeDialog.kt | 2 | 4732 | package com.ddu.ui.dialog
import android.content.Context
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import com.ddu.R
import com.ddu.R.id.tv_error_msg
import com.ddu.R.id.tv_phone_number
import com.ddu.icore.common.ext.ctx
import com.ddu.icore.common.ext.loadAnimation
import com.ddu.icore.common.ext.showKeyboard
import com.ddu.icore.ui.view.NumberInputView
import com.ddu.icore.util.sys.ViewUtils
/**
* Created by yzbzz on 2017/5/26.
*/
class VerificationCodeDialog : DialogFragment(), View.OnClickListener {
private var mTvPhoneNumber: TextView? = null
private var mTvCountDown: TextView? = null
private var mTvResend: TextView? = null
private var mTvErrorMsg: TextView? = null
private var mLlVoiceCode: LinearLayout? = null
private var mEtPhoneNumber: NumberInputView? = null
private var mRegisterTimer: RegisterTimer? = null
private var mPhone: String? = ""
private var mContext: Context? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mPhone = arguments!!.getString(EXTRA_PHONE)
mRegisterTimer = RegisterTimer(COUNT_DOWN_TIME.toLong(), 250)
mRegisterTimer!!.start()
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog?.window!!.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window!!.setBackgroundDrawableResource(android.R.color.transparent)
val mLlLogin = inflater.inflate(R.layout.fragment_verification_code, container, false) as LinearLayout
mTvErrorMsg = ViewUtils.findViewById(mLlLogin, tv_error_msg)
mTvPhoneNumber = ViewUtils.findViewById(mLlLogin, tv_phone_number)
mTvPhoneNumber!!.text = mPhone
mLlVoiceCode = ViewUtils.findViewById(mLlLogin, R.id.ll_voice_code)
mEtPhoneNumber = ViewUtils.findViewById(mLlLogin, R.id.et_phone_number)
mEtPhoneNumber!!.postDelayed({
// mEtPhoneNumber.getEt().performClick();
// mEtPhoneNumber.getll().performClick();
activity?.showKeyboard(mEtPhoneNumber)
}, 300)
mEtPhoneNumber!!.setOnInputCallback {
mTvErrorMsg!!.visibility = View.VISIBLE
mLlLogin.startAnimation(ctx.loadAnimation(R.anim.shake))
}
mTvCountDown = ViewUtils.findViewById(mLlLogin, R.id.tv_count_down)
mTvResend = ViewUtils.findViewById(mLlLogin, R.id.btn_resend)
mTvResend!!.setOnClickListener(this)
return mLlLogin
}
override fun onClick(v: View) {
val id = v.id
when (id) {
R.id.btn_resend -> {
mEtPhoneNumber!!.clearText()
reSend()
}
}
}
private fun reSend() {
mTvResend!!.visibility = View.GONE
mTvCountDown!!.visibility = View.VISIBLE
mRegisterTimer!!.start()
}
internal inner class RegisterTimer(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onFinish() {
mTvResend!!.visibility = View.VISIBLE
mTvCountDown!!.visibility = View.GONE
}
override fun onTick(millisUntilFinished: Long) {
if (isAdded) {
mTvCountDown!!.text = resources.getString(R.string.format_count_down, millisUntilFinished / 1000)
if (millisUntilFinished / 1000 == (COUNT_DOWN_TIME / 1000 - 20).toLong()) {
mLlVoiceCode!!.visibility = View.VISIBLE
}
}
}
}
override fun onDestroy() {
super.onDestroy()
mRegisterTimer!!.cancel()
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
mEtPhoneNumber!!.performClick()
}
}
companion object {
val EXTRA_PHONE = "extra_phone"
private val COUNT_DOWN_TIME = 60 * 1000
private val COUNT_DOWN_INTERVAL: Long = 1000
fun newInstance(phone: String): VerificationCodeDialog {
val args = Bundle()
args.putString(EXTRA_PHONE, phone)
val fragment = VerificationCodeDialog()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 83e73e77c9ceae1a8846714a6cb959e3 | 32.8 | 139 | 0.65765 | 4.414179 | false | false | false | false |
matt-richardson/TeamCity.Node | server/src/com/jonnyzzz/teamcity/plugins/node/server/GruntRunType.kt | 2 | 3107 | /*
* Copyright 2013-2013 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.PropertiesProcessor
import com.jonnyzzz.teamcity.plugins.node.common.GruntBean
import com.jonnyzzz.teamcity.plugins.node.common.NodeBean
import com.jonnyzzz.teamcity.plugins.node.common.GruntExecutionMode
/*
* Copyright 2000-2013 Eugene Petrenko
*
* 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.
*/
/**
* Created by Eugene Petrenko ([email protected])
* Date: 14.01.13 21:57
*/
public class GruntRunType : RunTypeBase() {
private val bean = GruntBean()
public override fun getType(): String = bean.runTypeName
public override fun getDisplayName(): String = "Grunt"
public override fun getDescription(): String = "Executes Grunt tasks"
protected override fun getEditJsp(): String = "grunt.edit.jsp"
protected override fun getViewJsp(): String = "grunt.view.jsp"
public override fun getRunnerPropertiesProcessor(): PropertiesProcessor = PropertiesProcessor { arrayListOf() }
public override fun describeParameters(parameters: Map<String, String>): String
= "Run targets: ${bean.parseCommands(parameters[bean.targets]) join ", "}"
public override fun getDefaultRunnerProperties(): MutableMap<String, String>
= hashMapOf(bean.gruntMode to bean.gruntModeDefault.value)
public override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
val result = arrayListOf<Requirement>()
val list = super.getRunnerSpecificRequirements(runParameters)
if (list != null) result addAll list
result add Requirement(NodeBean().nodeJSConfigurationParameter, null, RequirementType.EXISTS)
if (bean.parseMode(runParameters[bean.gruntMode]) == GruntExecutionMode.GLOBAL) {
result add Requirement(bean.gruntConfigurationParameter, null, RequirementType.EXISTS)
}
return result
}
}
| apache-2.0 | c92c4199d308f7cddb32cbe5b1f67e5d | 39.881579 | 115 | 0.764725 | 4.327298 | false | false | false | false |
actions-on-google/appactions-common-biis-kotlin | app/src/test/java/com/example/android/architecture/blueprints/todoapp/data/source/DefaultTasksRepositoryTest.kt | 1 | 10908 | /*
* Copyright (C) 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.data.source
import com.example.android.architecture.blueprints.todoapp.MainCoroutineRule
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* Unit tests for the implementation of the in-memory repository with cache.
*/
@ExperimentalCoroutinesApi
class DefaultTasksRepositoryTest {
private val task1 = Task("Title1", "Description1")
private val task2 = Task("Title2", "Description2")
private val task3 = Task("Title3", "Description3")
private val newTask = Task("Title new", "Description new")
private val remoteTasks = listOf(task1, task2).sortedBy { it.id }
private val localTasks = listOf(task3).sortedBy { it.id }
private val newTasks = listOf(task3).sortedBy { it.id }
private lateinit var tasksRemoteDataSource: FakeDataSource
private lateinit var tasksLocalDataSource: FakeDataSource
// Class under test
private lateinit var tasksRepository: DefaultTasksRepository
// Set the main coroutines dispatcher for unit testing.
@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
@ExperimentalCoroutinesApi
@Before
fun createRepository() {
tasksRemoteDataSource = FakeDataSource(remoteTasks.toMutableList())
tasksLocalDataSource = FakeDataSource(localTasks.toMutableList())
// Get a reference to the class under test
tasksRepository = DefaultTasksRepository(
tasksRemoteDataSource, tasksLocalDataSource, Dispatchers.Main
)
}
@ExperimentalCoroutinesApi
@Test
fun getTasks_emptyRepositoryAndUninitializedCache() = mainCoroutineRule.runBlockingTest {
val emptySource = FakeDataSource()
val tasksRepository = DefaultTasksRepository(
emptySource, emptySource, Dispatchers.Main
)
assertThat(tasksRepository.getTasks() is Success).isTrue()
}
@Test
fun getTasks_repositoryCachesAfterFirstApiCall() = mainCoroutineRule.runBlockingTest {
// Trigger the repository to load data, which loads from remote and caches
val initial = tasksRepository.getTasks()
tasksRemoteDataSource.tasks = newTasks.toMutableList()
val second = tasksRepository.getTasks()
// Initial and second should match because we didn't force a refresh
assertThat(second).isEqualTo(initial)
}
@Test
fun getTasks_requestsAllTasksFromRemoteDataSource() = mainCoroutineRule.runBlockingTest {
// When tasks are requested from the tasks repository
val tasks = tasksRepository.getTasks(true) as Success
// Then tasks are loaded from the remote data source
assertThat(tasks.data).isEqualTo(remoteTasks)
}
@Test
fun saveTask_savesToLocalAndRemote() = mainCoroutineRule.runBlockingTest {
// Make sure newTask is not in the remote or local datasources
assertThat(tasksRemoteDataSource.tasks).doesNotContain(newTask)
assertThat(tasksLocalDataSource.tasks).doesNotContain(newTask)
// When a task is saved to the tasks repository
tasksRepository.saveTask(newTask)
// Then the remote and local sources are called
assertThat(tasksRemoteDataSource.tasks).contains(newTask)
assertThat(tasksLocalDataSource.tasks).contains(newTask)
}
@Test
fun getTasks_WithDirtyCache_tasksAreRetrievedFromRemote() = mainCoroutineRule.runBlockingTest {
// First call returns from REMOTE
val tasks = tasksRepository.getTasks()
// Set a different list of tasks in REMOTE
tasksRemoteDataSource.tasks = newTasks.toMutableList()
// But if tasks are cached, subsequent calls load from cache
val cachedTasks = tasksRepository.getTasks()
assertThat(cachedTasks).isEqualTo(tasks)
// Now force remote loading
val refreshedTasks = tasksRepository.getTasks(true) as Success
// Tasks must be the recently updated in REMOTE
assertThat(refreshedTasks.data).isEqualTo(newTasks)
}
@Test
fun getTasks_WithDirtyCache_remoteUnavailable_error() = mainCoroutineRule.runBlockingTest {
// Make remote data source unavailable
tasksRemoteDataSource.tasks = null
// Load tasks forcing remote load
val refreshedTasks = tasksRepository.getTasks(true)
// Result should be an error
assertThat(refreshedTasks).isInstanceOf(Result.Error::class.java)
}
@Test
fun getTasks_WithRemoteDataSourceUnavailable_tasksAreRetrievedFromLocal() =
mainCoroutineRule.runBlockingTest {
// When the remote data source is unavailable
tasksRemoteDataSource.tasks = null
// The repository fetches from the local source
assertThat((tasksRepository.getTasks() as Success).data).isEqualTo(localTasks)
}
@Test
fun getTasks_WithBothDataSourcesUnavailable_returnsError() = mainCoroutineRule.runBlockingTest {
// When both sources are unavailable
tasksRemoteDataSource.tasks = null
tasksLocalDataSource.tasks = null
// The repository returns an error
assertThat(tasksRepository.getTasks()).isInstanceOf(Result.Error::class.java)
}
@Test
fun getTasks_refreshesLocalDataSource() = mainCoroutineRule.runBlockingTest {
val initialLocal = tasksLocalDataSource.tasks
// First load will fetch from remote
val newTasks = (tasksRepository.getTasks(true) as Success).data
assertThat(newTasks).isEqualTo(remoteTasks)
assertThat(newTasks).isEqualTo(tasksLocalDataSource.tasks)
assertThat(tasksLocalDataSource.tasks).isEqualTo(initialLocal)
}
@Test
fun completeTask_completesTaskToServiceAPIUpdatesCache() = mainCoroutineRule.runBlockingTest {
// Save a task
tasksRepository.saveTask(newTask)
// Make sure it's active
assertThat((tasksRepository.getTask(newTask.id) as Success).data.isCompleted).isFalse()
// Mark is as complete
tasksRepository.completeTask(newTask.id)
// Verify it's now completed
assertThat((tasksRepository.getTask(newTask.id) as Success).data.isCompleted).isTrue()
}
@Test
fun completeTask_activeTaskToServiceAPIUpdatesCache() = mainCoroutineRule.runBlockingTest {
// Save a task
tasksRepository.saveTask(newTask)
tasksRepository.completeTask(newTask.id)
// Make sure it's completed
assertThat((tasksRepository.getTask(newTask.id) as Success).data.isActive).isFalse()
// Mark is as active
tasksRepository.activateTask(newTask.id)
// Verify it's now activated
val result = tasksRepository.getTask(newTask.id) as Success
assertThat(result.data.isActive).isTrue()
}
@Test
fun getTask_repositoryCachesAfterFirstApiCall() = mainCoroutineRule.runBlockingTest {
// Trigger the repository to load data, which loads from remote
tasksRemoteDataSource.tasks = mutableListOf(task1)
tasksRepository.getTask(task1.id, true)
// Configure the remote data source to store a different task
tasksRemoteDataSource.tasks = mutableListOf(task2)
val task1SecondTime = tasksRepository.getTask(task1.id, true) as Success
val task2SecondTime = tasksRepository.getTask(task2.id, true) as Success
// Both work because one is in remote and the other in cache
assertThat(task1SecondTime.data.id).isEqualTo(task1.id)
assertThat(task2SecondTime.data.id).isEqualTo(task2.id)
}
@Test
fun getTask_forceRefresh() = mainCoroutineRule.runBlockingTest {
// Trigger the repository to load data, which loads from remote and caches
tasksRemoteDataSource.tasks = mutableListOf(task1)
tasksRepository.getTask(task1.id)
// Configure the remote data source to return a different task
tasksRemoteDataSource.tasks = mutableListOf(task2)
// Force refresh
val task1SecondTime = tasksRepository.getTask(task1.id, true)
val task2SecondTime = tasksRepository.getTask(task2.id, true)
// Only task2 works because the cache and local were invalidated
assertThat((task1SecondTime as? Success)?.data?.id).isNull()
assertThat((task2SecondTime as? Success)?.data?.id).isEqualTo(task2.id)
}
@Test
fun clearCompletedTasks() = mainCoroutineRule.runBlockingTest {
val completedTask = task1.copy().apply { isCompleted = true }
tasksRemoteDataSource.tasks = mutableListOf(completedTask, task2)
tasksRepository.clearCompletedTasks()
val tasks = (tasksRepository.getTasks(true) as? Success)?.data
assertThat(tasks).hasSize(1)
assertThat(tasks).contains(task2)
assertThat(tasks).doesNotContain(completedTask)
}
@Test
fun deleteAllTasks() = mainCoroutineRule.runBlockingTest {
val initialTasks = (tasksRepository.getTasks() as? Success)?.data
// Delete all tasks
tasksRepository.deleteAllTasks()
// Fetch data again
val afterDeleteTasks = (tasksRepository.getTasks() as? Success)?.data
// Verify tasks are empty now
assertThat(initialTasks).isNotEmpty()
assertThat(afterDeleteTasks).isEmpty()
}
@Test
fun deleteSingleTask() = mainCoroutineRule.runBlockingTest {
val initialTasks = (tasksRepository.getTasks(true) as? Success)?.data
// Delete first task
tasksRepository.deleteTask(task1.id)
// Fetch data again
val afterDeleteTasks = (tasksRepository.getTasks(true) as? Success)?.data
// Verify only one task was deleted
assertThat(afterDeleteTasks?.size).isEqualTo(initialTasks!!.size - 1)
assertThat(afterDeleteTasks).doesNotContain(task1)
}
}
| apache-2.0 | f878439e794e3427dd22eb40b97c5699 | 37.408451 | 100 | 0.713696 | 4.962693 | false | true | false | false |
willjgriff/android-ethereum-wallet | app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ethereum/icap/IbanChecksumUtils.kt | 1 | 1735 | package com.github.willjgriff.ethereumwallet.ethereum.icap
import java.math.BigInteger
/**
* Created by Will on 11/03/2017.
*
* Guides: https://usersite.datalab.eu/printclass.aspx?type=wiki&id=91772
* http://ethereum.stackexchange.com/questions/12016/checksum-calculation-for-icap-address
*
* TODO: Consider adding validation
*/
class IbanChecksumUtils(private val baseConverter: BaseConverter) {
private val ICAP_XE_PREFIX = "XE"
private val IBAN_MUTIPLIER = "00"
private val IBAN_CHECK_MOD_VALUE = "97"
fun createChecksum(base36Value: String): Int {
if (base36Value.isNullOrBlank()) {
return -1
}
val valueWithXePrefix = base36Value + ICAP_XE_PREFIX
val valueAsInt = baseConverter.base36ToInteger(valueWithXePrefix)
val valueTimes100 = valueAsInt + IBAN_MUTIPLIER
val valueMod97 = BigInteger(valueTimes100).mod(BigInteger(IBAN_CHECK_MOD_VALUE))
val checksum = 98 - valueMod97.toInt()
return checksum
}
fun verifyChecksum(base36Value: String, checksum: Int): Boolean {
if (checksum < 1 || checksum > 97) {
return false
}
val checksumString = convertChecksumToDoubleDigitString(checksum)
val valueWithChecksum = baseConverter.base36ToInteger(base36Value + ICAP_XE_PREFIX) + checksumString
val bigIntMod = BigInteger(valueWithChecksum).mod(BigInteger(IBAN_CHECK_MOD_VALUE))
return bigIntMod.toString(10) == "1"
}
fun convertChecksumToDoubleDigitString(checksum: Int): String {
var checksumString = checksum.toString()
if (checksum < 10) {
checksumString = "0" + checksumString
}
return checksumString
}
} | apache-2.0 | 470fa3499d99687a3d6d8643197c9fb6 | 33.039216 | 108 | 0.682421 | 3.890135 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/settings/status/ServerStatusFragment.kt | 1 | 2737 | package me.proxer.app.settings.status
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorRes
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseContentFragment
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.extension.enableFastScroll
import me.proxer.app.util.extension.unsafeLazy
import org.koin.androidx.viewmodel.ext.android.viewModel
/**
* @author Ruben Gees
*/
class ServerStatusFragment : BaseContentFragment<List<ServerStatus>>(R.layout.fragment_server_status) {
companion object {
fun newInstance() = ServerStatusFragment().apply {
arguments = bundleOf()
}
}
override val isSwipeToRefreshEnabled = true
override val viewModel by viewModel<ServerStatusViewModel>()
private val layoutManger by unsafeLazy {
GridLayoutManager(requireContext(), DeviceUtils.calculateSpanAmount(requireActivity()))
}
private val adapter = ServerStatusAdapter()
private val overallStatus: TextView by bindView(R.id.overallStatus)
private val recyclerView: RecyclerView by bindView(R.id.recyclerView)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView.setHasFixedSize(true)
recyclerView.enableFastScroll()
recyclerView.layoutManager = layoutManger
recyclerView.adapter = adapter
}
override fun showData(data: List<ServerStatus>) {
super.showData(data)
val allServersOnline = data.all { it.online }
val overallStatusText = when (allServersOnline) {
true -> getString(R.string.fragment_server_status_overall_online)
false -> getString(R.string.fragment_server_status_overall_offline)
}
val overallStatusIcon = IconicsDrawable(requireContext())
.icon(if (allServersOnline) CommunityMaterial.Icon4.cmd_earth else CommunityMaterial.Icon4.cmd_earth_off)
.colorRes(if (allServersOnline) R.color.md_green_500 else R.color.md_red_500)
.sizeDp(48)
.paddingDp(12)
overallStatus.text = overallStatusText
overallStatus.setCompoundDrawablesWithIntrinsicBounds(overallStatusIcon, null, null, null)
adapter.swapDataAndNotifyWithDiffing(data)
}
}
| gpl-3.0 | e9c44825f00d17bfd2f856fdc2aa0bc8 | 35.013158 | 117 | 0.747534 | 4.654762 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | system/src/main/kotlin/com/commonsense/android/kotlin/system/imaging/ImageHelpers.kt | 1 | 9910 | @file:Suppress("unused", "NOTHING_TO_INLINE")
package com.commonsense.android.kotlin.system.imaging
import android.content.*
import android.graphics.*
import android.net.*
import android.support.media.ExifInterface
import android.support.annotation.*
import android.support.annotation.IntRange
import com.commonsense.android.kotlin.base.extensions.collections.*
import com.commonsense.android.kotlin.system.extensions.*
import com.commonsense.android.kotlin.system.logging.*
import kotlinx.coroutines.*
import java.io.*
/**
*
* @receiver Uri
* @param contentResolver ContentResolver
* @param ratio Double
* @param containsTransparency Boolean
* @return Deferred<Bitmap?>
*/
fun Uri.loadBitmapWithSampleSize(contentResolver: ContentResolver,
ratio: Double,
containsTransparency: Boolean = true,
shouldDownSample: Boolean = false): Deferred<Bitmap?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
val bitmapConfig = containsTransparency.map(Bitmap.Config.ARGB_8888, Bitmap.Config.RGB_565)
val bitmapOptions = BitmapFactory.Options().apply {
@IntRange(from = 1)
inSampleSize = getPowerOfTwoForSampleRatio(ratio, shouldDownSample)
inPreferredConfig = bitmapConfig//
/* inDensity = srcWidth //TODO do this later, as this will result in perfecter scaling.
inScaled = true
inTargetDensity = dstWidt * inSampleSize*/
}
tryAndLog("loadBitmapWithSampleSize") {
contentResolver.openInputStream(this@loadBitmapWithSampleSize).use { inputToDecode ->
return@tryAndLog BitmapFactory.decodeStream(inputToDecode, null, bitmapOptions)
}
}
}
/**
*
* @receiver Uri
* @param contentResolver ContentResolver
* @param bitmapConfig Bitmap.Config
* @return Deferred<BitmapFactory.Options?>
*/
fun Uri.loadBitmapSize(contentResolver: ContentResolver, bitmapConfig: Bitmap.Config = Bitmap.Config.ARGB_8888): Deferred<BitmapFactory.Options?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
val onlyBoundsOptions = BitmapFactory.Options().apply {
inJustDecodeBounds = true
inPreferredConfig = bitmapConfig//optional
}
tryAndLog("loadBitmapSize") {
contentResolver.openInputStream(this@loadBitmapSize).use { input ->
BitmapFactory.decodeStream(input, null, onlyBoundsOptions)
}
return@tryAndLog if (onlyBoundsOptions.outWidth == -1 || onlyBoundsOptions.outHeight == -1) {
null
} else {
onlyBoundsOptions
}
}
}
/**
*
* @receiver Bitmap
* @param compressionPercentage Int
* @return Deferred<Bitmap>
*/
fun Bitmap.compress(@IntRange(from = 0L, to = 100L) compressionPercentage: Int): Deferred<Bitmap> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
ByteArrayOutputStream().use { out ->
[email protected](Bitmap.CompressFormat.JPEG, compressionPercentage, out)
return@async BitmapFactory.decodeStream(ByteArrayInputStream(out.toByteArray()))
}
}
suspend fun Uri.loadBitmapPreviews(scalePreviewsPercentages: IntArray,
width: Int,
contentResolver: ContentResolver): Deferred<List<Bitmap>?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
val bitmap = [email protected](contentResolver, width).await()
?: return@async null
val compressSizes = scalePreviewsPercentages.map {
bitmap.compress(it)
}
return@async compressSizes.map { it.await() }
}
/**
*
* @param ratio Double
* @return Int
*/
@IntRange(from = 1)
fun getPowerOfTwoForSampleRatio(ratio: Double, downSample: Boolean): Int {
val scaledRatio = if (downSample) {
Math.floor(ratio)
} else {
Math.ceil(ratio)
}
val k = Integer.highestOneBit(scaledRatio.toInt())
return maxOf(k, 1)
}
/**
*
* @receiver Bitmap
* @param width Int
* @return Deferred<Bitmap?>
*/
suspend fun Bitmap.scaleToWidth(@IntRange(from = 0) width: Int): Deferred<Bitmap?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
tryAndLogSuspend("Bitmap.scaleToWidth") {
val size = getImageSize().scaleWidth(width)
Bitmap.createScaledBitmap(this@scaleToWidth, size.width, size.height, true)
}
}
/**
*
* Assumes a thumbnail is square
* @receiver Context
* @param defaultSize Int
* @param minSize Int
* @param fraction Int
* @return Int
*/
@IntRange(from = 0)
fun Context.calculateOptimalThumbnailSize(@IntRange(from = 0) defaultSize: Int = 200,
@IntRange(from = 0) minSize: Int = 50,
@IntRange(from = 0) fraction: Int = 8): Int {
val virtualSize = getVirtualScreenSize() ?: return defaultSize
val widthFraction = virtualSize.x / fraction
val heightFraction = virtualSize.y / fraction
val combined = widthFraction + heightFraction
return maxOf(combined / 2, minSize)
}
/**
*
* @receiver Bitmap
* @param exifInterface ExifInterface
* @return Deferred<Bitmap>
*/
suspend fun Bitmap.rotate(exifInterface: ExifInterface): Deferred<Bitmap> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
var rotation = 0F
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL)
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_180 -> rotation = 180F
ExifInterface.ORIENTATION_ROTATE_90 -> rotation = 90F
ExifInterface.ORIENTATION_ROTATE_270 -> rotation = 270F
}
return@async [email protected](rotation).await()
}
/**
*
* @receiver Bitmap
* @param degrees Float
* @return Deferred<Bitmap>
*/
fun Bitmap.rotate(@FloatRange(from = 0.0, to = 360.0) degrees: Float): Deferred<Bitmap> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
val matrix = Matrix()
if (degrees != 0f) {
matrix.preRotate(degrees)
}
return@async Bitmap.createBitmap(this@rotate, 0, 0, width, height, matrix, true)
}
/**
*
* @receiver Uri
* @param contentResolver ContentResolver
* @param width Int
* @return Deferred<Bitmap?>
*/
suspend fun Uri.loadBitmapRotatedCorrectly(contentResolver: ContentResolver, width: Int): Deferred<Bitmap?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
tryAndLogSuspend("loadImage") {
val exif = getExifForImage(contentResolver).await()
val bitmap = loadBitmapScaled(contentResolver, width).await()
if (exif != null) {
bitmap?.rotate(exif)?.await()
} else {
bitmap
}
}
}
/**
*
* @receiver Uri
* @param contentResolver ContentResolver
* @return Deferred<ExifInterface?>
*/
fun Uri.getExifForImage(contentResolver: ContentResolver) = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
tryAndLog("getExifForImage") {
contentResolver.openInputStream(this@getExifForImage)?.use { input ->
return@tryAndLog ExifInterface(input)
}
}
}
/**
*
* @receiver Bitmap
* @param outputStream OutputStream
* @param quality Int
* @param format Bitmap.CompressFormat
*/
fun Bitmap.outputTo(outputStream: OutputStream, @IntRange(from = 0, to = 100) quality: Int, format: Bitmap.CompressFormat) {
compress(format, quality, outputStream)
}
/**
* Allows to save a bitmap to the given location, using the supplied arguements for controlling the quality / format.
* @receiver Bitmap
* @param path Uri
* @param contentResolver ContentResolver
* @param quality Int
* @param format Bitmap.CompressFormat
* @return Deferred<Unit?>
*/
fun Bitmap.saveTo(path: Uri, contentResolver: ContentResolver, @IntRange(from = 0, to = 100) quality: Int,
format: Bitmap.CompressFormat) = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
tryAndLog("saveTo") {
contentResolver.openOutputStream(path)?.use {
[email protected](it, quality, format)
}
}
}
/**
* want to be able to load a "scaled bitmap"
* @receiver Uri
* @param contentResolver ContentResolver
* @param width Int
* @return Deferred<Bitmap?>
*/
suspend fun Uri.loadBitmapScaled(contentResolver: ContentResolver, width: Int): Deferred<Bitmap?> = GlobalScope.async(Dispatchers.Default, CoroutineStart.DEFAULT) {
val onlyBoundsOptions = [email protected](contentResolver).await()
?: return@async null
val originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
.map(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth)
val ratio = (originalSize > width).map(originalSize / width.toDouble(), 1.0)
return@async loadBitmapWithSampleSize(contentResolver, ratio).await()
}
/**
*
* @receiver Bitmap
* @return ImageSize
*/
fun Bitmap.getImageSize(): ImageSize = ImageSize(width, height)
/**
*
* @property width Int
* @property height Int
* @constructor
*/
data class ImageSize(val width: Int, val height: Int) {
override fun toString(): String = "$width-$height"
}
/**
*
*/
val ImageSize.largest: Int
get() = maxOf(width, height)
/**
* Scales the imaage to the max width given.
* @receiver ImageSize
* @param destWidth Int
* @return ImageSize
*/
fun ImageSize.scaleWidth(destWidth: Int): ImageSize {
val destFloat = destWidth.toFloat()
val srcFloat = width.toFloat()
val ratio = (1f / (maxOf(destFloat, srcFloat) / minOf(destFloat, srcFloat)))
return applyRatio(ratio)
}
/**
*
* @receiver ImageSize
* @param ratio Float
* @return ImageSize
*/
fun ImageSize.applyRatio(ratio: Float): ImageSize =
ImageSize((width * ratio).toInt(), (height * ratio).toInt())
| mit | 1be7660490a7dda19e2acb23c77352f2 | 31.598684 | 212 | 0.688799 | 4.291901 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/messages/dto/MessagesHistoryMessageAttachment.kt | 1 | 2697 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.messages.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.audio.dto.AudioAudio
import com.vk.sdk.api.base.dto.BaseLink
import com.vk.sdk.api.docs.dto.DocsDoc
import com.vk.sdk.api.market.dto.MarketMarketItem
import com.vk.sdk.api.photos.dto.PhotosPhoto
import com.vk.sdk.api.video.dto.VideoVideo
import com.vk.sdk.api.wall.dto.WallWallpostFull
/**
* @param type
* @param audio
* @param audioMessage
* @param doc
* @param graffiti
* @param link
* @param market
* @param photo
* @param video
* @param wall
*/
data class MessagesHistoryMessageAttachment(
@SerializedName("type")
val type: MessagesHistoryMessageAttachmentType,
@SerializedName("audio")
val audio: AudioAudio? = null,
@SerializedName("audio_message")
val audioMessage: MessagesAudioMessage? = null,
@SerializedName("doc")
val doc: DocsDoc? = null,
@SerializedName("graffiti")
val graffiti: MessagesGraffiti? = null,
@SerializedName("link")
val link: BaseLink? = null,
@SerializedName("market")
val market: MarketMarketItem? = null,
@SerializedName("photo")
val photo: PhotosPhoto? = null,
@SerializedName("video")
val video: VideoVideo? = null,
@SerializedName("wall")
val wall: WallWallpostFull? = null
)
| mit | 47decc0377d746cec592625588bcb08e | 36.458333 | 81 | 0.695217 | 4.092564 | false | false | false | false |
seratch/kotliquery | src/main/kotlin/kotliquery/Connection.kt | 1 | 671 | package kotliquery
import java.sql.SQLException
/**
* Database Connection.
*/
data class Connection(
val underlying: java.sql.Connection,
val driverName: String = "",
val jtaCompatible: Boolean = false
) {
fun begin() {
underlying.autoCommit = false
if (!jtaCompatible) {
underlying.isReadOnly = false
}
}
fun commit() {
underlying.commit()
underlying.autoCommit = true
}
fun rollback() {
underlying.rollback()
try {
underlying.autoCommit = true
} catch (e: SQLException) {
}
}
fun close() {
underlying.close()
}
} | mit | 130e92ea3786662e753f461f75fac7a9 | 16.684211 | 41 | 0.558867 | 4.503356 | false | false | false | false |
hei1233212000/avaje-ebeanorm-examples | e-kotlin-maven/src/main/java/org/example/domain/Contact.kt | 1 | 1125 | package org.example.domain;
import com.avaje.ebean.Model
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.avaje.ebean.Model.Finder
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Contact entity bean.
*/
Entity
Table(name = "be_contact")
public class Contact() : BaseModel() {
Size(max = 50)
public var firstName: String? = null;
Size(max = 50)
public var lastName: String? = null;
Size(max = 200)
public var email: String? = null;
Size(max = 20)
public var phone: String? = null;
NotNull
ManyToOne(optional = false)
public var customer: Customer? = null;
/**
* Construct with firstName and lastName.
*/
constructor(firstName: String, lastName: String) : this() {
this.firstName = firstName;
this.lastName = lastName;
}
companion object : Model.Find<Long, Contact>() {
/**
* Alternate to secondary constructor ...
*/
fun of(first: String, last: String): Contact {
return Contact(first, last);
}
}
}
| apache-2.0 | 75a540596985e36b4db8b1b449ca7f8e | 19.833333 | 61 | 0.686222 | 3.826531 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.