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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vincentvalenlee/nineshop | src/main/kotlin/org/open/openstore/file/contributors/FileSystemKey.kt | 1 | 887 | package org.open.openstore.file.contributors
import org.open.openstore.file.FileSystemOptions
import org.open.openstore.file.FileSystemOptions.Companion.EMPTY_OPTIONS
/**
* 标识一个文件系统的key
*/
class FileSystemKey(private val key: Comparable<*>, private val fileSystemOptions: FileSystemOptions = EMPTY_OPTIONS):Comparable<FileSystemKey> {
override fun compareTo(o: FileSystemKey): Int {
val comparable = key as Comparable<Comparable<*>>// Keys must implement comparable, and be comparable to themselves
val ret = comparable.compareTo(o.key)
if (ret != 0) {
// other filesystem
return ret
}
return fileSystemOptions.compareTo(o.fileSystemOptions)
}
override fun toString(): String {
return super.toString() + " [key=" + key + ", fileSystemOptions=" + fileSystemOptions + "]"
}
} | gpl-3.0 | 8c1f42cffe06a250898e35be6750706a | 32.461538 | 145 | 0.690449 | 4.479381 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/utils.kt | 1 | 6449 | // 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.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.text.TextWithMnemonic
import com.intellij.ui.RawCommandLineEditor
import com.intellij.ui.SearchTextField
import com.intellij.ui.TitledSeparator
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.HyperlinkEventAction
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.builder.components.DslLabel
import com.intellij.ui.dsl.builder.components.DslLabelType
import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.GridLayoutComponentProperty
import com.intellij.ui.dsl.gridLayout.toGaps
import org.jetbrains.annotations.ApiStatus
import javax.swing.*
import javax.swing.text.JTextComponent
/**
* Internal component properties for UI DSL
*/
@ApiStatus.Internal
internal enum class DslComponentPropertyInternal {
/**
* A mark that component is a cell label, see [Cell.label]
*
* Value: true
*/
CELL_LABEL
}
/**
* [JPanel] descendants that should use default vertical gaps around similar to other standard components like labels, text fields etc
*/
private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf(
RawCommandLineEditor::class,
SearchTextField::class,
SegmentedButtonComponent::class,
SegmentedButtonToolbar::class,
TextFieldWithBrowseButton::class,
TitledSeparator::class
)
/**
* Throws exception instead of logging warning. Useful while forms building to avoid layout mistakes
*/
private const val FAIL_ON_WARN = false
private val LOG = Logger.getInstance("JetBrains UI DSL")
/**
* Components that can have assigned labels
*/
private val ALLOWED_LABEL_COMPONENTS = listOf(
JComboBox::class,
JSlider::class,
JSpinner::class,
JTable::class,
JTextComponent::class,
JTree::class,
SegmentedButtonComponent::class,
SegmentedButtonToolbar::class
)
internal val JComponent.origin: JComponent
get() {
// todo Move into components implementation
return when (this) {
is TextFieldWithBrowseButton -> textField
is ComponentWithBrowseButton<*> -> childComponent
else -> {
val interactiveComponent = getClientProperty(DslComponentProperty.INTERACTIVE_COMPONENT) as JComponent?
interactiveComponent ?: this
}
}
}
internal fun prepareVisualPaddings(component: JComponent): Gaps {
var customVisualPaddings = component.getClientProperty(DslComponentProperty.VISUAL_PADDINGS) as? Gaps
if (customVisualPaddings == null) {
// todo Move into components implementation
// Patch visual paddings for known components
customVisualPaddings = when (component) {
is RawCommandLineEditor -> component.editorField.insets.toGaps()
is SearchTextField -> component.textEditor.insets.toGaps()
is JScrollPane -> Gaps.EMPTY
is ComponentWithBrowseButton<*> -> component.childComponent.insets.toGaps()
else -> {
if (component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) != null) {
Gaps.EMPTY
}
else {
null
}
}
}
}
if (customVisualPaddings == null) {
return component.insets.toGaps()
}
component.putClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS, false)
return customVisualPaddings
}
internal fun getComponentGaps(left: Int, right: Int, component: JComponent, spacing: SpacingConfiguration): Gaps {
val top = getDefaultVerticalGap(component, spacing)
var bottom = top
if (component.getClientProperty(DslComponentProperty.NO_BOTTOM_GAP) == true) {
bottom = 0
}
return Gaps(top = top, left = left, bottom = bottom, right = right)
}
/**
* Returns default top and bottom gap for [component]. All non [JPanel] components or
* [DEFAULT_VERTICAL_GAP_COMPONENTS] have default vertical gap, zero otherwise
*/
internal fun getDefaultVerticalGap(component: JComponent, spacing: SpacingConfiguration): Int {
val noDefaultVerticalGap = component is JPanel
&& component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) == null
&& !DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz -> clazz.isInstance(component) }
return if (noDefaultVerticalGap) 0 else spacing.verticalComponentGap
}
internal fun createComment(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): DslLabel {
val result = DslLabel(DslLabelType.COMMENT)
result.action = action
result.maxLineLength = maxLineLength
result.text = text
return result
}
internal fun labelCell(label: JLabel, cell: CellBaseImpl<*>?) {
val mnemonic = TextWithMnemonic.fromMnemonicText(label.text)
val mnemonicExists = label.displayedMnemonic != 0 || label.displayedMnemonicIndex >= 0 || mnemonic?.hasMnemonic() == true
if (cell !is CellImpl<*>) {
if (mnemonicExists) {
warn("Cannot assign mnemonic to Panel and other non-component cells, label '${label.text}'")
}
return
}
val component = getLabelComponentFor(cell.component.origin)
if (component == null) {
if (mnemonicExists) {
warn("Unsupported labeled component ${cell.component.javaClass.name}, label '${label.text}'")
}
return
}
label.labelFor = component
}
private fun getLabelComponentFor(component: JComponent): JComponent? {
val labelFor = component.getClientProperty(DslComponentProperty.LABEL_FOR)
if (labelFor != null) {
if (labelFor is JComponent) {
return labelFor
}
else {
throw UiDslException("LABEL_FOR must be a JComponent: ${labelFor::class.java.name}")
}
}
if (ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(component) }) {
return component
}
return null
}
internal fun warn(message: String) {
if (FAIL_ON_WARN) {
throw UiDslException(message)
}
else {
LOG.warn(message)
}
}
| apache-2.0 | 769284a942a3e3800435306019bd21a6 | 32.764398 | 158 | 0.743371 | 4.512946 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinInplacePropertyIntroducer.kt | 5 | 6380 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pass
import com.intellij.psi.PsiElement
import com.intellij.ui.NonFocusableCheckBox
import com.intellij.ui.PopupMenuListenerAdapter
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.ExtractionResult
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.ExtractionTarget
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.generateDeclaration
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.processDuplicatesSilently
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.types.KotlinType
import javax.swing.*
import javax.swing.event.PopupMenuEvent
class KotlinInplacePropertyIntroducer(
property: KtProperty,
editor: Editor,
project: Project,
@Nls title: String,
doNotChangeVar: Boolean,
exprType: KotlinType?,
private var extractionResult: ExtractionResult,
private val availableTargets: List<ExtractionTarget>
) : KotlinInplaceVariableIntroducer<KtProperty>(
property, editor, project, title, KtExpression.EMPTY_ARRAY, null, false, property, false, doNotChangeVar, exprType, false
) {
init {
assert(availableTargets.isNotEmpty()) { "No targets available: ${property.getElementTextWithContext()}" }
}
private var currentTarget: ExtractionTarget = extractionResult.config.generatorOptions.target
set(value: ExtractionTarget) {
if (value == currentTarget) return
field = value
runWriteActionAndRestartRefactoring {
with(extractionResult.config) {
extractionResult = copy(generatorOptions = generatorOptions.copy(target = currentTarget)).generateDeclaration(property)
property = extractionResult.declaration as KtProperty
myElementToRename = property
}
}
updatePanelControls()
}
private var replaceAll: Boolean = true
private var property: KtProperty
get() = myDeclaration
set(value: KtProperty) {
myDeclaration = value
}
private fun isInitializer(): Boolean = currentTarget == ExtractionTarget.PROPERTY_WITH_INITIALIZER
override fun initPanelControls() {
if (availableTargets.size > 1) {
addPanelControl(
ControlWrapper {
val propertyKindComboBox = with(JComboBox(availableTargets.map { it.targetName.capitalize() }.toTypedArray())) {
addPopupMenuListener(
object : PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) {
ApplicationManager.getApplication().invokeLater {
currentTarget = availableTargets[selectedIndex]
}
}
}
)
selectedIndex = availableTargets.indexOf(currentTarget)
this
}
val propertyKindLabel = JLabel(KotlinBundle.message("label.text.introduce.as"))
propertyKindLabel.labelFor = propertyKindComboBox
val panel = JPanel()
panel.add(propertyKindLabel)
panel.add(propertyKindComboBox)
panel
}
)
}
if (ExtractionTarget.PROPERTY_WITH_INITIALIZER in availableTargets) {
val condition = { isInitializer() }
createVarCheckBox?.let {
val initializer = object : Pass<JComponent>() {
override fun pass(t: JComponent) {
(t as JCheckBox).isSelected = property.isVar
}
}
addPanelControl(ControlWrapper(it, condition, initializer))
}
createExplicitTypeCheckBox?.let {
val initializer = object : Pass<JComponent>() {
override fun pass(t: JComponent) {
(t as JCheckBox).isSelected = property.typeReference != null
}
}
addPanelControl(ControlWrapper(it, condition, initializer))
}
}
val occurrenceCount = extractionResult.duplicateReplacers.size
if (occurrenceCount > 1) {
addPanelControl(
ControlWrapper {
val replaceAllCheckBox = NonFocusableCheckBox(
KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount))
replaceAllCheckBox.isSelected = replaceAll
replaceAllCheckBox.addActionListener { replaceAll = replaceAllCheckBox.isSelected }
replaceAllCheckBox
}
)
}
}
override fun addTypeReferenceVariable(builder: TemplateBuilderImpl) {
if (!isInitializer()) return
super.addTypeReferenceVariable(builder)
}
override fun checkLocalScope(): PsiElement {
return myElementToRename.parentsWithSelf.first { it is KtClassOrObject || it is KtFile }
}
override fun performRefactoring(): Boolean {
if (replaceAll) {
processDuplicatesSilently(extractionResult.duplicateReplacers, myProject)
}
return true
}
} | apache-2.0 | 6b54eea0b84c754a2d59ff7faaf79a55 | 40.705882 | 139 | 0.643574 | 5.732255 | false | false | false | false |
GunoH/intellij-community | java/idea-ui/src/com/intellij/ide/projectView/actions/ModuleDependenciesCleaner.kt | 7 | 6873 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.projectView.actions
import com.intellij.analysis.AnalysisScope
import com.intellij.ide.JavaUiBundle
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.OrderEntryUtil
import com.intellij.packageDependencies.DependenciesToolWindow
import com.intellij.packageDependencies.ForwardDependenciesBuilder
import com.intellij.packageDependencies.ui.DependenciesPanel
import com.intellij.psi.PsiFile
import com.intellij.ui.content.ContentFactory
import org.jetbrains.concurrency.AsyncPromise
/**
* Finds and removes dependencies which aren't used in the code.
*/
class ModuleDependenciesCleaner(private val module: Module, dependenciesToCheck: Collection<Module>) {
private val dependenciesToCheck = dependenciesToCheck.toSet()
private val project = module.project
fun startInBackground(promise: AsyncPromise<Unit>) {
val builder = ForwardDependenciesBuilder(project, AnalysisScope(module))
object : Task.Backgroundable(project, JavaUiBundle.message("progress.title.searching.for.redundant.dependencies", module.name)) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
builder.analyze()
runReadAction { processRedundantDependencies(builder.directDependencies, promise) }
}
}.queue()
}
private fun processRedundantDependencies(directDependencies: Map<PsiFile, Set<PsiFile>>, promise: AsyncPromise<Unit>) {
val fileIndex = ProjectFileIndex.getInstance(module.project)
val usedModules = directDependencies.values.asSequence().flatten().mapNotNullTo(HashSet()) {
it.virtualFile?.let { file -> fileIndex.getModuleForFile(file) }
}
val dependenciesToRemove = dependenciesToCheck - usedModules
if (dependenciesToRemove.isEmpty()) {
val builder = ForwardDependenciesBuilder(project, AnalysisScope(module))
for ((file, dependencies) in directDependencies) {
if (!file.isValid) continue
val relevantDependencies = dependencies.filterTo(LinkedHashSet()) { psiFile ->
val virtualFile = psiFile.virtualFile
virtualFile != null && fileIndex.getModuleForFile(virtualFile) in dependenciesToCheck
}
if (relevantDependencies.isNotEmpty()) {
builder.directDependencies[file] = relevantDependencies
builder.dependencies[file] = relevantDependencies
}
}
showNothingToCleanNotification(builder)
promise.setResult(Unit)
return
}
ApplicationManager.getApplication().invokeLater {
runWriteAction {
removeDependencies(dependenciesToRemove, usedModules)
promise.setResult(Unit)
}
}
}
private fun removeDependencies(dependenciesToRemove: Set<Module>, usedModules: HashSet<Module>) {
if (module.isDisposed || dependenciesToRemove.any { it.isDisposed }) return
val model = ModuleRootManager.getInstance(module).modifiableModel
val rootModelProvider = object : RootModelProvider {
override fun getModules(): Array<Module> {
return ModuleManager.getInstance(project).modules
}
override fun getRootModel(module: Module): ModuleRootModel {
return if (module == [email protected]) model else ModuleRootManager.getInstance(module)
}
}
val transitiveDependenciesToAdd = LinkedHashSet<Module>()
val removedDependencies = ArrayList<Module>()
for (dependency in dependenciesToRemove) {
val entry = OrderEntryUtil.findModuleOrderEntry(model, dependency)
if (entry != null) {
val additionalDependencies = JavaProjectDependenciesAnalyzer.findExportedDependenciesReachableViaThisDependencyOnly(module, dependency, rootModelProvider)
additionalDependencies.entries
.filter { (it.key as? ModuleOrderEntry)?.module in usedModules }
.mapNotNullTo(transitiveDependenciesToAdd) { (it.value as? ModuleOrderEntry)?.module }
model.removeOrderEntry(entry)
removedDependencies.add(dependency)
}
}
for (dependency in transitiveDependenciesToAdd) {
model.addModuleOrderEntry(dependency)
}
model.commit()
showSuccessNotification(removedDependencies, transitiveDependenciesToAdd)
}
private fun showSuccessNotification(dependenciesToRemove: List<Module>, transitiveDependenciesToAdd: Set<Module>) {
val transitiveDependenciesMessage =
if (transitiveDependenciesToAdd.isNotEmpty()) JavaUiBundle.message("notification.content.transitive.dependencies.were.added", transitiveDependenciesToAdd.first().name, transitiveDependenciesToAdd.size - 1)
else ""
val notification = Notification("Dependencies", JavaUiBundle.message("notification.title.dependencies.were.cleaned.up", module.name),
JavaUiBundle.message("notification.content.unused.dependencies.were.removed", dependenciesToRemove.first().name, dependenciesToRemove.size - 1, transitiveDependenciesMessage),
NotificationType.INFORMATION)
notification.notify(project)
}
private fun showNothingToCleanNotification(builder: ForwardDependenciesBuilder) {
val notification = Notification("Dependencies",
JavaUiBundle.message("notification.content.none.module.dependencies.can.be.safely.removed", module.name), NotificationType.INFORMATION)
notification.addAction(ShowDependenciesAction(module, builder))
notification.notify(project)
}
private class ShowDependenciesAction(private val module: Module, private val builder: ForwardDependenciesBuilder)
: NotificationAction(JavaUiBundle.message("notification.action.text.show.dependencies")) {
private val project = module.project
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val panel = DependenciesPanel(project, listOf(builder), LinkedHashSet())
val content = ContentFactory.getInstance().createContent(panel, JavaUiBundle.message("tab.title.module.dependencies", module.name), false)
content.setDisposer(panel)
panel.setContent(content)
DependenciesToolWindow.getInstance(project).addContent(content)
}
}
} | apache-2.0 | c5dcd098c7be694e27e222042c2d96af | 48.811594 | 211 | 0.760949 | 5.152174 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/learnIde/HeightLimitedPane.kt | 12 | 3256 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.welcomeScreen.learnIde
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.LearnIdeContentColorsAndFonts.PARAGRAPH_STYLE
import com.intellij.ui.JBColor
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import java.awt.Dimension
import java.awt.event.MouseEvent
import javax.swing.JTextPane
import javax.swing.plaf.FontUIResource
import javax.swing.plaf.TextUI
import javax.swing.text.DefaultCaret
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
/**
* This panel has limited height by its preferred size and doesn't grow more. The maximum width
* could be limited as well by setting maximumWidth.
*/
class HeightLimitedPane(text: String, private val relativeFontSize: Int, val fontColor: JBColor, private val isBold: Boolean = false, private val maximumWidth: Int? = null) : JTextPane() {
val style = SimpleAttributeSet()
init {
border = JBUI.Borders.empty()
isEditable = false
StyleConstants.setFontFamily(style, JBUI.Fonts.label().fontName)
if (isBold) StyleConstants.setBold(style, true)
StyleConstants.setForeground(style, fontColor)
StyleConstants.setFontSize(style, adjustFont().size)
document.insertString(0, text, style)
//ensure that style has been applied
styledDocument.setCharacterAttributes(0, text.length, style, true)
styledDocument.setParagraphAttributes(0, text.length, style, true)
isOpaque = false
isEditable = false
alignmentX = LEFT_ALIGNMENT
highlighter = null
//make JTextPane transparent for mouse actions
caret = object : DefaultCaret() {
override fun mousePressed(e: MouseEvent?) {
[email protected] { it.mousePressed(e) }
}
override fun mouseReleased(e: MouseEvent?) {
[email protected] { it.mouseReleased(e) }
}
override fun mouseEntered(e: MouseEvent?) {
[email protected] { it.mouseEntered(e) }
}
override fun mouseExited(e: MouseEvent?) {
[email protected] { it.mouseExited(e) }
}
}
}
override fun getMaximumSize(): Dimension {
if (maximumWidth == null) {
return this.preferredSize
}
else {
return Dimension(width, this.preferredSize.height)
}
}
override fun setUI(ui: TextUI?) {
super.setUI(ui)
if (font != null) {
font = FontUIResource(adjustFont())
}
}
private fun adjustFont() = JBUI.Fonts.label().deriveFont(JBUI.Fonts.label().size2D + JBUIScale.scale(relativeFontSize) + if (SystemInfo.isWindows) JBUIScale.scale(1) else 0)
override fun updateUI() {
super.updateUI()
@Suppress("SENSELESS_COMPARISON")
if (font != null && style != null) {
StyleConstants.setFontSize(style, font.size)
styledDocument.setCharacterAttributes(0, text.length, style, true)
styledDocument.setParagraphAttributes(0, text.length, PARAGRAPH_STYLE, true)
}
}
} | apache-2.0 | ccfa8f5d87a8b597dd0a8dc9e947bb47 | 35.595506 | 188 | 0.730344 | 4.163683 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/collection/VirtualStorageDataCollection.kt | 2 | 1089 | package com.github.kerubistan.kerub.model.collection
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import java.io.Serializable
import java.util.UUID
data class VirtualStorageDataCollection(
override val stat: VirtualStorageDevice,
override val dynamic: VirtualStorageDeviceDynamic? = null
) : DataCollection<UUID, VirtualStorageDevice, VirtualStorageDeviceDynamic>, Serializable {
inline fun updateDynamic(update: (VirtualStorageDeviceDynamic) -> VirtualStorageDeviceDynamic) =
update(this.dynamic ?: VirtualStorageDeviceDynamic(id = stat.id, allocations = listOf()))
inline fun updateWithDynamic(update: (VirtualStorageDeviceDynamic) -> VirtualStorageDeviceDynamic) =
this.copy(dynamic = this.updateDynamic(update))
init {
this.validate()
dynamic?.apply {
check(stat.readOnly || allocations.size <= 1) {
"only read only storage devices can have multiple allocations " +
"- ${stat.id} has readOnly: ${stat.readOnly} and allocations $allocations"
}
}
}
} | apache-2.0 | b3fa58310945b9d318af32f396a776bb | 35.333333 | 101 | 0.782369 | 4.518672 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/tracker/LookupCompletedTracker.kt | 9 | 2825 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.tracker
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.personalization.UserFactorDescriptions
import com.intellij.completion.ml.personalization.UserFactorStorage
import com.intellij.completion.ml.storage.MutableLookupStorage
import com.intellij.completion.ml.util.idString
import com.intellij.textMatching.PrefixMatchingType
/**
* @author Vitaliy.Bibaev
*/
class LookupCompletedTracker : LookupFinishListener() {
override fun cancelled(lookup: LookupImpl, canceledExplicitly: Boolean) {
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater ->
updater.fireLookupCancelled()
}
}
override fun typedSelect(lookup: LookupImpl,
element: LookupElement) {
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater ->
updater.fireTypedSelectPerformed()
}
}
override fun explicitSelect(lookup: LookupImpl, element: LookupElement) {
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.COMPLETION_FINISH_TYPE) { updater ->
updater.fireExplicitCompletionPerformed()
}
val prefixLength = lookup.getPrefixLength(element)
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) { updater ->
updater.fireCompletionPerformed(prefixLength)
}
val itemPosition = lookup.selectedIndex
if (itemPosition != -1) {
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.SELECTED_ITEM_POSITION) { updater ->
updater.fireCompletionPerformed(itemPosition)
}
}
if (prefixLength > 1) {
val pattern = lookup.itemPattern(element)
val isMnemonicsUsed = !element.lookupString.startsWith(pattern)
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.MNEMONICS_USAGE) { updater ->
updater.fireCompletionFinished(isMnemonicsUsed)
}
val storage = MutableLookupStorage.get(lookup)?.getItemStorage(element.idString())
val type = storage?.getLastUsedFactors()?.get("prefix_matching_type") as? PrefixMatchingType
if (type != null) {
UserFactorStorage.applyOnBoth(lookup.project, UserFactorDescriptions.PREFIX_MATCHING_TYPE) { updater ->
updater.fireCompletionPerformed(type)
}
}
}
}
}
| apache-2.0 | 9d57cd79b045efa13ca09a360b2aabb8 | 43.84127 | 140 | 0.703009 | 4.87069 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerImpl.kt | 5 | 7934 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.ProjectModelElement
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Transient
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
val EMPTY_STATE: ExternalStateComponent = ExternalStateComponent()
/**
* This class isn't used in the new implementation of project model, which is based on [Workspace Model][com.intellij.workspaceModel.ide].
* It shouldn't be used directly, its interface [ExternalSystemModulePropertyManager] should be used instead.
*/
@Suppress("DEPRECATION")
@State(name = "ExternalSystem")
class ExternalSystemModulePropertyManagerImpl(private val module: Module) : ExternalSystemModulePropertyManager(),
PersistentStateComponent<ExternalStateComponent>, ProjectModelElement {
override fun getExternalSource(): ProjectModelExternalSource? = store.externalSystem?.let {
ExternalProjectSystemRegistry.getInstance().getSourceById(it)
}
private var store = if (module.project.isExternalStorageEnabled) ExternalStateComponent() else ExternalStateModule(module)
override fun getState(): ExternalStateComponent = store as? ExternalStateComponent ?: EMPTY_STATE
override fun loadState(state: ExternalStateComponent) {
store = state
}
@Suppress("DEPRECATION")
override fun getExternalSystemId(): String? = store.externalSystem
override fun getExternalModuleType(): String? = store.externalSystemModuleType
override fun getExternalModuleVersion(): String? = store.externalSystemModuleVersion
override fun getExternalModuleGroup(): String? = store.externalSystemModuleGroup
override fun getLinkedProjectId(): String? = store.linkedProjectId
override fun getRootProjectPath(): String? = store.rootProjectPath
override fun getLinkedProjectPath(): String? = store.linkedProjectPath
@Suppress("DEPRECATION")
override fun isMavenized(): Boolean = store.isMavenized
@Suppress("DEPRECATION")
override fun setMavenized(mavenized: Boolean) {
if (mavenized) {
// clear external system API options
// see com.intellij.openapi.externalSystem.service.project.manage.ModuleDataService#setModuleOptions
unlinkExternalOptions()
}
// must be after unlinkExternalOptions
store.isMavenized = mavenized
}
override fun swapStore() {
val oldStore = store
val isMaven = oldStore.isMavenized
if (oldStore is ExternalStateModule) {
store = ExternalStateComponent()
}
else {
store = ExternalStateModule(module)
}
store.externalSystem = if (store is ExternalStateModule && isMaven) null else oldStore.externalSystem
if (store !is ExternalStateComponent) {
// do not set isMavenized for ExternalStateComponent it just set externalSystem
store.isMavenized = isMaven
}
store.linkedProjectId = oldStore.linkedProjectId
store.linkedProjectPath = oldStore.linkedProjectPath
store.rootProjectPath = oldStore.rootProjectPath
store.externalSystemModuleGroup = oldStore.externalSystemModuleGroup
store.externalSystemModuleVersion = oldStore.externalSystemModuleVersion
if (oldStore is ExternalStateModule) {
oldStore.isMavenized = false
oldStore.unlinkExternalOptions()
}
}
override fun unlinkExternalOptions() {
store.unlinkExternalOptions()
}
override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) {
// clear maven option, must be first
store.isMavenized = false
store.externalSystem = id.toString()
store.linkedProjectId = moduleData.id
store.linkedProjectPath = moduleData.linkedExternalProjectPath
store.rootProjectPath = projectData?.linkedExternalProjectPath ?: ""
store.externalSystemModuleGroup = moduleData.group
store.externalSystemModuleVersion = moduleData.version
}
override fun setExternalId(id: ProjectSystemId) {
store.externalSystem = id.id
}
override fun setLinkedProjectPath(path: String?) {
store.linkedProjectPath = path
}
override fun setRootProjectPath(path: String?) {
store.rootProjectPath = path
}
override fun setExternalModuleType(type: String?) {
store.externalSystemModuleType = type
}
}
private interface ExternalOptionState {
var externalSystem: String?
var externalSystemModuleVersion: String?
var linkedProjectPath: String?
var linkedProjectId: String?
var rootProjectPath: String?
var externalSystemModuleGroup: String?
var externalSystemModuleType: String?
var isMavenized: Boolean
}
private fun ExternalOptionState.unlinkExternalOptions() {
externalSystem = null
linkedProjectId = null
linkedProjectPath = null
rootProjectPath = null
externalSystemModuleGroup = null
externalSystemModuleVersion = null
}
@Suppress("DEPRECATION")
private class ModuleOptionDelegate(private val key: String) : ReadWriteProperty<ExternalStateModule, String?> {
override operator fun getValue(thisRef: ExternalStateModule, property: KProperty<*>) = thisRef.module.getOptionValue(key)
override operator fun setValue(thisRef: ExternalStateModule, property: KProperty<*>, value: String?) {
thisRef.module.setOption(key, value)
}
}
@Suppress("DEPRECATION")
private class ExternalStateModule(internal val module: Module) : ExternalOptionState {
override var externalSystem by ModuleOptionDelegate(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY)
override var externalSystemModuleVersion by ModuleOptionDelegate("external.system.module.version")
override var externalSystemModuleGroup by ModuleOptionDelegate("external.system.module.group")
override var externalSystemModuleType by ModuleOptionDelegate("external.system.module.type")
override var linkedProjectPath by ModuleOptionDelegate("external.linked.project.path")
override var linkedProjectId by ModuleOptionDelegate("external.linked.project.id")
override var rootProjectPath by ModuleOptionDelegate("external.root.project.path")
override var isMavenized: Boolean
get() = "true" == module.getOptionValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY)
set(value) {
module.setOption(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY, if (value) "true" else null)
}
}
class ExternalStateComponent : ExternalOptionState {
@get:Attribute
override var externalSystem: String? = null
@get:Attribute
override var externalSystemModuleVersion: String? = null
@get:Attribute
override var externalSystemModuleGroup: String? = null
@get:Attribute
override var externalSystemModuleType: String? = null
@get:Attribute
override var linkedProjectPath: String? = null
@get:Attribute
override var linkedProjectId: String? = null
@get:Attribute
override var rootProjectPath: String? = null
@get:Transient
override var isMavenized: Boolean
get() = externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
set(value) {
externalSystem = if (value) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null
}
} | apache-2.0 | 3fe0bc6fadb18f77bab4b0b76aee795c | 36.429245 | 147 | 0.780691 | 5.449176 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/java/impl/catalogue/CatalogueImpl.kt | 1 | 5107 | package xyz.nulldev.ts.api.java.impl.catalogue
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceInjector
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.util.syncChaptersWithSource
import xyz.nulldev.ts.api.java.model.catalogue.Catalogue
import xyz.nulldev.ts.api.java.model.catalogue.CataloguePage
import xyz.nulldev.ts.api.java.util.*
import xyz.nulldev.ts.ext.fetchPageListFromCacheThenNet
import xyz.nulldev.ts.ext.kInstanceLazy
import java.util.*
class CatalogueImpl : Catalogue {
private val sourceManager: SourceManager by kInstanceLazy()
private val sourceInjector by lazy {
SourceInjector(sourceManager)
}
private val downloadManager: DownloadManager by kInstanceLazy()
private val db: DatabaseHelper by kInstanceLazy()
private val prefs: PreferencesHelper by kInstanceLazy()
override val sources: List<CatalogueSource>
get() = sourceManager.getCatalogueSources()
override val enabledSources: List<CatalogueSource>
get() {
val languages = prefs.enabledLanguages().getOrDefault()
val hiddenCatalogues = prefs.hiddenCatalogues().getOrDefault()
return sources
.filter { it.lang in languages }
.filterNot { it.id.toString() in hiddenCatalogues }
.sortedBy { "(${it.lang}) ${it.name}" } +
sourceManager.get(LocalSource.ID) as LocalSource
}
override val onlineSources: List<HttpSource>
get() = sources.filterIsInstance<HttpSource>()
override val loginSources: List<LoginSource>
get() = sources.filterIsInstance<LoginSource>()
override fun getCatalogueContent(page: Int, source: CatalogueSource, query: String, filters: FilterList?): CataloguePage {
//Get catalogue from source
//TODO Possibly compare filters to see if filters have changed?
val observable = if (query.isNotBlank() || filters != null) {
source.fetchSearchManga(page, query, filters ?: source.getFilterList())
} else {
source.fetchPopularManga(page)
}
//Actually get manga from catalogue
val pageObj = observable.toBlocking().first()
val manga = pageObj.mangas.map { networkToLocalManga(it, source.id) }
return CataloguePage(manga, page, if(pageObj.hasNextPage) page + 1 else null)
}
private fun networkToLocalManga(sManga: SManga, sourceId: Long): Manga {
var localManga = db.getManga(sManga.url, sourceId).executeAsBlocking()
if (localManga == null) {
val newManga = Manga.create(sManga.url, sManga.title, sourceId)
newManga.copyFrom(sManga)
val result = db.insertManga(newManga).executeAsBlocking()
newManga.id = result.insertedId()
localManga = newManga
}
return localManga
}
override fun getSource(id: Long) = sourceManager.get(id)
override fun registerSource(source: CatalogueSource) {
sourceInjector.registerSource(source)
}
override fun updateMangaInfo(manga: Manga): Manga {
manga.copyFrom(manga.sourceObj.ensureLoaded().fetchMangaDetails(manga).toBlocking().first())
db.insertManga(manga).executeAsBlocking()
return manga
}
override fun updateMangaChapters(manga: Manga): Pair<List<Chapter>, List<Chapter>> {
val sourceObj = manga.sourceObj.ensureLoaded()
val result = syncChaptersWithSource(db,
sourceObj.fetchChapterList(manga).toBlocking().first(),
manga,
sourceObj)
//If we find new chapters, update the "last update" field in the manga object
if(result.first.isNotEmpty() || result.second.isNotEmpty()) {
manga.last_update = Date().time
db.updateLastUpdated(manga).executeAsBlocking()
}
return result
}
override fun getPageList(chapter: Chapter): List<Page> {
val manga = chapter.manga.ensureInDatabase()
val sourceObj = manga.sourceObj.ensureLoaded()
return if (chapter.isDownloaded) {
// Fetch the page list from disk.
downloadManager.buildPageList(sourceObj, manga, chapter)
} else {
(sourceObj as? HttpSource)?.fetchPageListFromCacheThenNet(chapter)
?: sourceObj.fetchPageList(chapter)
}.toBlocking().first()
}
} | apache-2.0 | f04350551f48cb4d98c3d290ff61ba58 | 41.92437 | 126 | 0.694733 | 4.584381 | false | false | false | false |
perqin/daily-wallpapers | app/src/main/java/com/perqin/dailywallpapers/data/models/wallpaper/WallpapersLiveData.kt | 1 | 906 | package com.perqin.dailywallpapers.data.models.wallpaper
import android.arch.lifecycle.LiveData
import com.perqin.dailywallpapers.data.models.wallpaperssource.WallpapersSource
import java.util.*
/**
* Created on 11/5/17.
*
* @author perqin
*/
class WallpapersLiveData : LiveData<List<Wallpaper>>() {
var wallpapersSource: WallpapersSource? = null
set(value) {
field = value
updateWallpapers()
}
var date: Calendar = Calendar.getInstance()
set(value) {
field = value
updateWallpapers()
}
private fun updateWallpapers() {
// TODO: Update from network as well as local cache
if (wallpapersSource != null) {
val wallpaper = Wallpaper(null, wallpapersSource!!.uid!!, date.timeInMillis, "https://www.google.com/some-image.jpg")
value = listOf(wallpaper)
}
}
}
| apache-2.0 | 5d1b04bfa27580644c973917af774913 | 27.3125 | 129 | 0.636865 | 4.118182 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/view/window/preferences/tab/network.kt | 1 | 2182 | package koma.gui.view.window.preferences.tab
import javafx.collections.FXCollections
import javafx.scene.control.ButtonBar
import javafx.scene.control.ComboBox
import koma.gui.view.window.preferences.PreferenceWindow
import koma.gui.view.window.preferences.tab.network.AddProxyField
import koma.gui.view.window.preferences.tab.network.ExistingProxy
import koma.gui.view.window.preferences.tab.network.NewProxy
import koma.gui.view.window.preferences.tab.network.ProxyOption
import koma.koma_app.appState
import koma.storage.persistence.settings.AppSettings
import koma.storage.persistence.settings.encoding.ProxyList
import link.continuum.desktop.gui.*
class NetworkSettingsTab(
parent: PreferenceWindow,
private val proxyList: ProxyList,
private val settings: AppSettings = appState.store.settings
) {
val root = VBox()
private val select: ComboBox<ProxyOption>
private val proxyField = AddProxyField()
init {
val proxyOptions: List<ProxyOption> = proxyList.list().map { ExistingProxy(it) } + NewProxy()
select = ComboBox(FXCollections.observableArrayList(
proxyOptions
))
select.selectionModel.selectFirst()
val creating = booleanBinding(select.valueProperty()) { value is NewProxy }
proxyField.root.visibleWhen(creating)
val selectedExisting = booleanBinding(select.valueProperty()) { value is ExistingProxy }
val valid = selectedExisting.or(creating.and(proxyField.isValid))
with(root) {
spacing = 5.0
label("Proxy Option")
add(select)
add(proxyField.root)
add(ButtonBar().apply {
button("Ok") {
enableWhen(valid)
action {
save()
parent.close()
}
}
})
}
}
fun save() {
val selection = select.value
val proxy = if ( selection is ExistingProxy) {
selection.proxy
} else {
proxyField.getProxy().getOrNull()?:return
}
proxyList.setDefault(proxy)
}
}
| gpl-3.0 | 8f6bad2391a01a9e0c542e943853da64 | 33.09375 | 102 | 0.643905 | 4.603376 | false | false | false | false |
atlarge-research/opendc-simulator | opendc-model-odc/jpa/src/main/kotlin/com/atlarge/opendc/model/odc/platform/JpaExperimentManager.kt | 1 | 4814 | /*
* MIT License
*
* Copyright (c) 2017 atlarge-research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.atlarge.opendc.model.odc.platform
import com.atlarge.opendc.model.odc.integration.jpa.schema.ExperimentState
import com.atlarge.opendc.model.odc.integration.jpa.transaction
import com.atlarge.opendc.simulator.platform.Experiment
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import com.atlarge.opendc.model.odc.integration.jpa.schema.Experiment as InternalExperiment
/**
* A manager for [Experiment]s received from a JPA database.
*
* @property factory The JPA entity manager factory to create [EntityManager]s to retrieve entities from the database
* from.
* @property collectMachineStates Flag to indicate machine states will be collected.
* @property collectTaskStates Flag to indicate task states will be collected.
* @property collectStageMeasurements Flag to indicate stage measurements will be collected.
* @property collectTaskMetrics Flag to indicate task metrics will be collected.
* @property collectJobMetrics Flag to indicate job metrics will be collected.
* @author Fabian Mastenbroek ([email protected])
*/
class JpaExperimentManager(private val factory: EntityManagerFactory,
private val collectMachineStates: Boolean = true,
private val collectTaskStates: Boolean = true,
private val collectStageMeasurements: Boolean = false,
private val collectTaskMetrics: Boolean = false,
private val collectJobMetrics: Boolean = false) : AutoCloseable {
/**
* The entity manager for this experiment.
*/
private var manager: EntityManager = factory.createEntityManager()
/**
* The amount of experiments in the queue. This property is not guaranteed to run in constant time.
*/
val size: Int
get() {
return manager.createQuery("SELECT COUNT(e.id) FROM experiments e WHERE e.state = :s",
java.lang.Long::class.java)
.setParameter("s", ExperimentState.QUEUED)
.singleResult.toInt()
}
/**
* Poll an [Experiment] from the database and claim it.
*
* @return The experiment that has been polled from the database or `null` if there are no experiments in the
* queue.
*/
fun poll(): JpaExperiment? {
var result: JpaExperiment? = null
manager.transaction {
var experiment: InternalExperiment? = null
val results = manager.createQuery("SELECT e FROM experiments e WHERE e.state = :s",
InternalExperiment::class.java)
.setParameter("s", ExperimentState.QUEUED)
.setMaxResults(1)
.resultList
if (!results.isEmpty()) {
experiment = results.first()
experiment!!.state = ExperimentState.CLAIMED
}
result = experiment?.let {
JpaExperiment(
manager,
it,
collectMachineStates,
collectTaskStates,
collectStageMeasurements,
collectTaskMetrics,
collectJobMetrics
)
}
}
manager = factory.createEntityManager()
return result
}
/**
* Close this resource, relinquishing any underlying resources.
* This method is invoked automatically on objects managed by the
* `try`-with-resources statement.*
*
* @throws Exception if this resource cannot be closed
*/
override fun close() = manager.close()
}
| mit | b82b767a7fe948f76068a3614a7c6429 | 41.60177 | 117 | 0.665351 | 4.957775 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/details/DetailsActivity.kt | 1 | 3720 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.details
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.marktony.zhihudaily.R
import com.marktony.zhihudaily.data.ContentType
import com.marktony.zhihudaily.data.source.repository.DoubanMomentContentRepository
import com.marktony.zhihudaily.data.source.repository.GuokrHandpickContentRepository
import com.marktony.zhihudaily.data.source.repository.ZhihuDailyContentRepository
import com.marktony.zhihudaily.injection.Injection
/**
* Created by lizhaotailang on 2017/5/24.
*
* Activity for displaying the details of content.
*/
class DetailsActivity : AppCompatActivity() {
private lateinit var mDetailsFragment: DetailsFragment
private var mType: ContentType = ContentType.TYPE_ZHIHU_DAILY
companion object {
const val KEY_ARTICLE_TYPE = "KEY_ARTICLE_TYPE"
const val KEY_ARTICLE_ID = "KEY_ARTICLE_ID"
const val KEY_ARTICLE_TITLE = "KEY_ARTICLE_TITLE"
const val KEY_ARTICLE_IS_FAVORITE = "KEY_ARTICLE_IS_FAVORITE"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.frame)
if (savedInstanceState != null) {
mDetailsFragment = supportFragmentManager.getFragment(savedInstanceState, DetailsFragment::class.java.simpleName) as DetailsFragment
} else {
mDetailsFragment = DetailsFragment.newInstance()
supportFragmentManager.beginTransaction()
.add(R.id.container, mDetailsFragment, DetailsFragment::class.java.simpleName)
.commit()
}
mType = intent.getSerializableExtra(KEY_ARTICLE_TYPE) as ContentType
when {
mType === ContentType.TYPE_ZHIHU_DAILY -> DetailsPresenter(
mDetailsFragment,
Injection.provideZhihuDailyNewsRepository(this@DetailsActivity),
Injection.provideZhihuDailyContentRepository(this@DetailsActivity))
mType === ContentType.TYPE_DOUBAN_MOMENT -> DetailsPresenter(
mDetailsFragment,
Injection.provideDoubanMomentNewsRepository(this@DetailsActivity),
Injection.provideDoubanMomentContentRepository(this@DetailsActivity))
mType === ContentType.TYPE_GUOKR_HANDPICK -> DetailsPresenter(
mDetailsFragment,
Injection.provideGuokrHandpickNewsRepository(this@DetailsActivity),
Injection.provideGuokrHandpickContentRepository(this@DetailsActivity))
}
}
override fun onDestroy() {
super.onDestroy()
ZhihuDailyContentRepository.destroyInstance()
DoubanMomentContentRepository.destroyInstance()
GuokrHandpickContentRepository.destroyInstance()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (mDetailsFragment.isAdded) {
supportFragmentManager.putFragment(outState, DetailsFragment::class.java.simpleName, mDetailsFragment)
}
}
}
| apache-2.0 | 32951773e70c68df8f78c3c835670bc2 | 39.434783 | 144 | 0.709409 | 5.152355 | false | false | false | false |
markusfisch/BinaryEye | app/src/main/kotlin/de/markusfisch/android/binaryeye/fragment/HistoryFragment.kt | 1 | 11722 | package de.markusfisch.android.binaryeye.fragment
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.SearchManager
import android.content.Context
import android.database.Cursor
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.view.ActionMode
import android.support.v7.widget.SearchView
import android.support.v7.widget.SwitchCompat
import android.view.*
import android.widget.EditText
import android.widget.ListView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.ScansAdapter
import de.markusfisch.android.binaryeye.app.*
import de.markusfisch.android.binaryeye.content.copyToClipboard
import de.markusfisch.android.binaryeye.content.shareText
import de.markusfisch.android.binaryeye.database.*
import de.markusfisch.android.binaryeye.io.askForFileName
import de.markusfisch.android.binaryeye.io.toSaveResult
import de.markusfisch.android.binaryeye.view.*
import de.markusfisch.android.binaryeye.widget.toast
import kotlinx.coroutines.*
class HistoryFragment : Fragment() {
private lateinit var useHistorySwitch: SwitchCompat
private lateinit var listView: ListView
private lateinit var fab: View
private lateinit var progressView: View
private val parentJob = Job()
private val scope = CoroutineScope(Dispatchers.IO + parentJob)
private val actionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(
mode: ActionMode,
menu: Menu
): Boolean {
mode.menuInflater.inflate(
R.menu.fragment_history_edit,
menu
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
lockStatusBarColor()
val ac = activity ?: return false
ac.window.statusBarColor = ContextCompat.getColor(
ac,
R.color.accent_dark
)
}
return true
}
override fun onPrepareActionMode(
mode: ActionMode,
menu: Menu
): Boolean {
return false
}
override fun onActionItemClicked(
mode: ActionMode,
item: MenuItem
): Boolean {
val ac = activity ?: return false
return when (item.itemId) {
R.id.copy_scan -> {
scansAdapter?.getSelectedContent("\n")?.let {
ac.copyToClipboard(it)
ac.toast(R.string.copied_to_clipboard)
}
closeActionMode()
true
}
R.id.edit_scan -> {
scansAdapter?.forSelection { id, position ->
ac.askForName(
id,
scansAdapter?.getName(position),
scansAdapter?.getContent(position)
)
}
closeActionMode()
true
}
R.id.remove_scan -> {
scansAdapter?.getSelectedIds()?.let {
if (it.isNotEmpty()) {
ac.askToRemoveScans(it)
}
}
closeActionMode()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode) {
closeActionMode()
}
}
private var scansAdapter: ScansAdapter? = null
private var listViewState: Parcelable? = null
private var actionMode: ActionMode? = null
private var filter: String? = null
private var clearListMenuItem: MenuItem? = null
private var exportHistoryMenuItem: MenuItem? = null
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
state: Bundle?
): View? {
val ac = activity ?: return null
ac.setTitle(R.string.history)
val view = inflater.inflate(
R.layout.fragment_history,
container,
false
)
useHistorySwitch = view.findViewById(
R.id.use_history
) as SwitchCompat
initHistorySwitch(useHistorySwitch)
listView = view.findViewById(R.id.scans)
listView.setOnItemClickListener { _, _, _, id ->
showScan(id)
}
listView.setOnItemLongClickListener { _, v, position, id ->
scansAdapter?.select(v, id, position)
if (actionMode == null && ac is AppCompatActivity) {
actionMode = ac.delegate.startSupportActionMode(
actionModeCallback
)
}
true
}
listView.setOnScrollListener(systemBarListViewScrollListener)
fab = view.findViewById(R.id.share)
fab.setOnClickListener { v ->
v.context.pickListSeparatorAndShare()
}
progressView = view.findViewById(R.id.progress_view)
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
update()
return view
}
override fun onDestroy() {
super.onDestroy()
scansAdapter?.changeCursor(null)
parentJob.cancel()
}
override fun onPause() {
super.onPause()
listViewState = listView.onSaveInstanceState()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_history, menu)
initSearchView(menu.findItem(R.id.search))
menu.setGroupVisible(R.id.scans_available, scansAdapter?.count != 0)
clearListMenuItem = menu.findItem(R.id.clear)
exportHistoryMenuItem = menu.findItem(R.id.export_history)
}
private fun initSearchView(item: MenuItem?) {
item ?: return
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
item.isVisible = false
} else {
val ac = activity ?: return
val searchView = item.actionView as SearchView
val searchManager = ac.getSystemService(
Context.SEARCH_SERVICE
) as SearchManager
searchView.setSearchableInfo(
searchManager.getSearchableInfo(ac.componentName)
)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
update(query)
return false
}
override fun onQueryTextChange(query: String): Boolean {
update(query)
return false
}
})
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.clear -> {
context.askToRemoveScans()
true
}
R.id.export_history -> {
askToExportToFile()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun initHistorySwitch(switchView: SwitchCompat) {
switchView.setOnCheckedChangeListener { _, isChecked ->
prefs.useHistory = isChecked
}
if (prefs.useHistory) {
switchView.toggle()
}
}
private fun updateAndClearFilter() {
filter = null
update()
}
private fun update(query: String? = null) {
query?.let { filter = it }
scope.launch {
val cursor = db.getScans(filter)
withContext(Dispatchers.Main) {
val ac = activity ?: return@withContext
val hasScans = cursor != null && cursor.count > 0
if (filter == null) {
if (!hasScans) {
listView.emptyView = useHistorySwitch
}
ActivityCompat.invalidateOptionsMenu(ac)
}
enableMenuItems(hasScans)
fab.visibility = if (hasScans) {
View.VISIBLE
} else {
View.GONE
}
cursor?.let { cursor ->
// Close previous cursor.
scansAdapter?.also { it.changeCursor(null) }
scansAdapter = ScansAdapter(ac, cursor)
listView.adapter = scansAdapter
listViewState?.also {
listView.onRestoreInstanceState(it)
}
}
}
}
}
private fun enableMenuItems(enabled: Boolean) {
clearListMenuItem?.isEnabled = enabled
exportHistoryMenuItem?.isEnabled = enabled
}
private fun closeActionMode() {
unlockStatusBarColor()
scansAdapter?.clearSelection()
actionMode?.finish()
actionMode = null
scansAdapter?.notifyDataSetChanged()
}
private fun showScan(id: Long) = db.getScan(id)?.also { scan ->
closeActionMode()
try {
fragmentManager?.addFragment(DecodeFragment.newInstance(scan))
} catch (e: IllegalArgumentException) {
// Ignore, can never happen.
}
}
// Dialogs don't have a parent layout.
@SuppressLint("InflateParams")
private fun Context.askForName(id: Long, text: String?, content: String?) {
val view = LayoutInflater.from(this).inflate(
R.layout.dialog_enter_name, null
)
val nameView = view.findViewById<EditText>(R.id.name)
nameView.setText(text)
AlertDialog.Builder(this)
.setTitle(
if (content.isNullOrEmpty()) {
getString(R.string.binary_data)
} else {
content
}
)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val name = nameView.text.toString()
db.renameScan(id, name)
update()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}
private fun Context.askToRemoveScans(ids: List<Long>) {
AlertDialog.Builder(this)
.setMessage(
if (ids.size > 1) {
R.string.really_remove_selected_scans
} else {
R.string.really_remove_scan
}
)
.setPositiveButton(android.R.string.ok) { _, _ ->
ids.forEach { db.removeScan(it) }
if (scansAdapter?.count == 1) {
updateAndClearFilter()
} else {
update()
}
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
}
.show()
}
private fun Context.askToRemoveScans() {
AlertDialog.Builder(this)
.setMessage(
if (filter == null) {
R.string.really_remove_all_scans
} else {
R.string.really_remove_selected_scans
}
)
.setPositiveButton(android.R.string.ok) { _, _ ->
db.removeScans(filter)
updateAndClearFilter()
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
}
.show()
}
private fun askToExportToFile() {
scope.launch {
val ac = activity ?: return@launch
progressView.useVisibility {
// Write permission is only required before Android Q.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
!ac.hasWritePermission { askToExportToFile() }
) {
return@useVisibility
}
val options = ac.resources.getStringArray(
R.array.export_options_values
)
val delimiter = alertDialog<String>(ac) { resume ->
setTitle(R.string.export_as)
setItems(R.array.export_options_names) { _, which ->
resume(options[which])
}
} ?: return@useVisibility
val name = withContext(Dispatchers.Main) {
ac.askForFileName(
when (delimiter) {
"db" -> ".db"
"json" -> ".json"
else -> ".csv"
}
)
} ?: return@useVisibility
val message = when (delimiter) {
"db" -> ac.exportDatabase(name)
else -> db.getScansDetailed(filter)?.use {
when (delimiter) {
"json" -> ac.exportJson(name, it)
else -> ac.exportCsv(name, it, delimiter)
}
} ?: false
}.toSaveResult()
withContext(Dispatchers.Main) {
ac.toast(message)
}
}
}
}
private fun Context.pickListSeparatorAndShare() {
val separators = resources.getStringArray(
R.array.list_separators_values
)
AlertDialog.Builder(this)
.setTitle(R.string.pick_list_separator)
.setItems(R.array.list_separators_names) { _, which ->
shareScans(separators[which])
}
.show()
}
private fun shareScans(format: String) = scope.launch {
progressView.useVisibility {
var text: String? = null
db.getScansDetailed(filter)?.use { cursor ->
val details = format.split(":")
text = when (details[0]) {
"text" -> cursor.exportText(details[1])
"csv" -> cursor.exportCsv(details[1])
else -> cursor.exportJson()
}
}
text?.let {
withContext(Dispatchers.Main) {
context.shareText(it)
}
}
}
}
}
private fun Cursor.exportText(separator: String): String {
val sb = StringBuilder()
val contentIndex = getColumnIndex(Database.SCANS_CONTENT)
if (contentIndex > -1 && moveToFirst()) {
do {
val content = getString(contentIndex)
if (content?.isNotEmpty() == true) {
sb.append(content)
sb.append(separator)
}
} while (moveToNext())
}
return sb.toString()
}
| mit | 3c14f603626bd73870fb3f7192de2ab8 | 24.762637 | 78 | 0.686402 | 3.492849 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/JamiLinkAccountFragment.kt | 1 | 5995 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Béraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.content.Context
import android.os.Bundle
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import cx.ring.databinding.FragAccJamiLinkBinding
import net.jami.model.AccountCreationModel
class JamiLinkAccountFragment : Fragment() {
private lateinit var model: AccountCreationModel
private var mBinding: FragAccJamiLinkBinding? = null
private var mCurrentFragment: Fragment? = null
private val onBackPressedCallback: OnBackPressedCallback =
object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
if (mCurrentFragment is ProfileCreationFragment) {
val fragment = mCurrentFragment as ProfileCreationFragment
(activity as AccountWizardActivity?)!!.profileCreated(fragment.model!!, false)
return
}
mBinding!!.pager.currentItem = mBinding!!.pager.currentItem - 1
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putSerializable("model", model)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (savedInstanceState != null) {
model = savedInstanceState.getSerializable("model") as AccountCreationModel
}
return FragAccJamiLinkBinding.inflate(inflater, container, false).apply {
mBinding = this
}.root
}
override fun onDestroyView() {
super.onDestroyView()
mBinding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pagerAdapter = ScreenSlidePagerAdapter(childFragmentManager, model)
mBinding!!.pager.adapter = pagerAdapter
mBinding!!.pager.disableScroll(true)
mBinding!!.pager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
mCurrentFragment = pagerAdapter.getRegisteredFragment(position)
onBackPressedCallback.isEnabled = mCurrentFragment is ProfileCreationFragment
}
override fun onPageScrollStateChanged(state: Int) {}
})
}
override fun onAttach(context: Context) {
super.onAttach(context)
requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
}
fun scrollPagerFragment(accountCreationModel: AccountCreationModel?) {
if (accountCreationModel == null) {
mBinding!!.pager.currentItem = mBinding!!.pager.currentItem - 1
return
}
mBinding!!.pager.currentItem = mBinding!!.pager.currentItem + 1
for (fragment in childFragmentManager.fragments) {
if (fragment is JamiAccountPasswordFragment) {
fragment.setUsername(accountCreationModel.username)
}
}
}
private class ScreenSlidePagerAdapter(fm: FragmentManager, model: AccountCreationModel) :
FragmentStatePagerAdapter(fm) {
var ringAccountViewModel: AccountCreationModelImpl = model as AccountCreationModelImpl
var mRegisteredFragments = SparseArray<Fragment>()
override fun getItem(position: Int): Fragment {
var fragment: Fragment? = null
when (position) {
0 -> fragment = JamiLinkAccountPasswordFragment.newInstance(ringAccountViewModel)
1 -> fragment = ProfileCreationFragment.newInstance(ringAccountViewModel)
}
return fragment!!
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val fragment = super.instantiateItem(container, position) as Fragment
mRegisteredFragments.put(position, fragment)
return super.instantiateItem(container, position)
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
mRegisteredFragments.remove(position)
super.destroyItem(container, position, `object`)
}
override fun getCount(): Int {
return NUM_PAGES
}
fun getRegisteredFragment(position: Int): Fragment {
return mRegisteredFragments[position]
}
}
companion object {
val TAG = JamiLinkAccountFragment::class.simpleName!!
private const val NUM_PAGES = 2
fun newInstance(ringAccountViewModel: AccountCreationModelImpl): JamiLinkAccountFragment {
val fragment = JamiLinkAccountFragment()
fragment.model = ringAccountViewModel
return fragment
}
}
} | gpl-3.0 | f237223227bfe3d9a53d0e62b7ca3cc8 | 38.966667 | 115 | 0.68702 | 5.414634 | false | false | false | false |
addonovan/ftc-ext | ftc-ext/src/main/java/com/addonovan/ftcext/control/HardwareMapExtensions.kt | 1 | 11140 | package com.addonovan.ftcext.control
import com.addonovan.ftcext.*
import com.addonovan.ftcext.hardware.*
import com.addonovan.ftcext.reflection.ClassFinder
import com.qualcomm.robotcore.hardware.*
import com.qualcomm.robotcore.hardware.HardwareMap.DeviceMapping
import java.lang.reflect.*
import java.util.*
/**
* HardwareMap Extension functions
*
* @author addonovan
* @since 6/25/16
*/
/** Type alias for satan. */
private class DeviceClassMap : HashMap< Class< out HardwareDevice >, DeviceMapping< out HardwareDevice > >()
{
inline fun < reified T : HardwareDevice > addEntry( mapping: DeviceMapping< out T > ) = put( T::class.java, mapping );
}
/**
* This exists for logging and keeping track of device class maps.
*/
private object HardwareMapExtension : ILog by getLog( HardwareMapExtension::class )
{
/** Maps the deviceClassMap to the HardwareMap. */
private val deviceClassMapMap = HashMap< HardwareMap, DeviceClassMap >();
internal val HardwareExtensions: MutableList< Class< * > > by lazy()
{
ClassFinder().inheritsFrom( HardwareDevice::class.java ).with( HardwareExtension::class.java ).get();
}
/**
* Gets (or creates) the single DeviceClassMap for the instance of the hardware map given.
*
* @param[hardwareMap]
* The hardware map to fetch an instance of a DeviceClassMap for.
* @return The instance of the DeviceClassMap for the hardware map.
*/
fun getDeviceClassMap( hardwareMap: HardwareMap ): DeviceClassMap
{
if ( !deviceClassMapMap.containsKey( hardwareMap ) )
{
deviceClassMapMap[ hardwareMap ] = DeviceClassMap();
}
return deviceClassMapMap[ hardwareMap ]!!;
}
}
/** A map of the base hardware class versus the */
private val HardwareMap.deviceClassMap: DeviceClassMap
get()
{
val map = HardwareMapExtension.getDeviceClassMap( this );
// initialize the map the first time around
if ( map.isEmpty() )
{
map.addEntry( dcMotorController );
map.addEntry( dcMotor );
map.addEntry( servoController );
map.addEntry( servo );
map.addEntry( legacyModule );
map.addEntry( touchSensorMultiplexer );
map.addEntry( deviceInterfaceModule );
map.addEntry( analogInput );
map.addEntry( digitalChannel );
map.addEntry( opticalDistanceSensor );
map.addEntry( touchSensor );
map.addEntry( pwmOutput );
map.addEntry( i2cDevice );
map.addEntry( analogOutput );
map.addEntry( colorSensor );
map.addEntry( led );
map.addEntry( accelerationSensor );
map.addEntry( compassSensor );
map.addEntry( gyroSensor );
map.addEntry( irSeekerSensor );
map.addEntry( lightSensor );
map.addEntry( ultrasonicSensor );
map.addEntry( voltageSensor );
}
return map;
}
/**
* The world's shittiest guess and check! This makes it slightly nicer looking for
* java users to actually use the method, but it's far less efficient. Oh well.
*
* @param[name]
* The name of the device to fetch.
*/
@Suppress( "unchecked_cast" )
fun < T : HardwareDevice > HardwareMap.getDeviceByGuess( name: String ): T
{
HardwareMapExtension.HardwareExtensions.forEach { extensionClass ->
try
{
return getDeviceByType( extensionClass as Class< out HardwareDevice >, name ) as T;
}
catch ( e: Exception ){} // ignore these exceptions, this is trial by error after all
};
throw NullPointerException( "No Hardware Device with the name '$name' with the required type!" );
}
/**
* Gets the correct device from the Hardware device mappings in the HardwareMap by
* using the type of HardwareDevice to find the correct hardware device mapping
* and the name to get the correct value out of it.
*
* @param[type]
* The type of hardware device to find.
* @param[name]
* The name of the hardware device to return.
*
* @return The hardware device with the given type and name.
*
* @throws IllegalArgumentException
* If [type] had no DeviceMapping associated with it.
* @throws NullPointerException
* If there was no entry for [name] with the type [type].
* @throws IllegalAnnotationValueException
* If the [type] class had a [HardwareExtension] annotation on it that had
* an invalid value (that is, one that doesn't have a value in the backing
* map of classes and `DeviceMapping`s) assigned to the `hardwareMapType`
* parameter.
* This should *never* happen to an end-user, that would mean that the
* developer who wrote the extension did so wrongly.
* @throws IllegalClassSetupException
* If [type] is a [HardwareExtension] that has been insufficiently
* set up, which could be for a multitude of reasons, check the
* error message if this occurs for more details.
*/
@Suppress( "unchecked_cast" )
fun HardwareMap.getDeviceByType( type: Class< out HardwareDevice >, name: String ): HardwareDevice
{
var baseType = type;
val isExtension = type.isHardwareExtension();
var constructor: Constructor< out HardwareDevice >? = null;
if ( isExtension )
{
constructor = findExtensionConstructor( type );
baseType = type.getHardwareMapType().java;
}
else
{
// keep going up the hierarchy for hardware devices until:
// 1. the base type is in the class map
// 2. the base type's superclass is HardwareDevice itself
//
// after the loop breaks we know that:
// if there's a key for "baseType" that we can find the correct device mapping for the type
// otherwise, we need to throw an exception because there's no map for the given type
while ( !deviceClassMap.containsKey( baseType ) && baseType.superclass != HardwareDevice::class.java )
{
baseType = baseType.superclass as Class< out HardwareDevice >;
}
}
// the second condition was met, but the device is still not a
// direct descendant of anything in the hardware device mappings
// so we can't find the correct map for it
if ( !deviceClassMap.containsKey( baseType ) )
{
HardwareMapExtension.e( "Can't find a device mapping for the given type: ${type.name}" );
HardwareMapExtension.e( "This means that there's no way to get the hardware device from the hardware map!" );
throw IllegalArgumentException( "No hardware device mapping for type: ${type.canonicalName}!" );
}
val deviceMapping = deviceClassMap[ type ]!!; // we're ensured that one exists by the previous block
try
{
val device = deviceMapping[ name ]!!;
if ( isExtension )
{
// if it's an extension, create the extension object and return it
// 1 parameter is just the hardware device
if ( constructor!!.typeParameters.size == 1 )
{
return constructor.newInstance( device );
}
// 2 parameters is the hardware device AND its name
else if ( constructor.typeParameters.size == 2 )
{
return constructor.newInstance( device, name );
}
else
{
throw IllegalStateException( "huh but how?" ); // not descriptive, but will probably never occur
}
}
else
{
// if it's not an extension, just return the value from the map
return device;
}
}
// catch an IllegalArgumentException from the deviceMapping.get() method
catch ( ex: IllegalArgumentException )
{
HardwareMapExtension.e( "Failed to find the device by name $name!", ex );
throw NullPointerException( "No device with the type ${type.simpleName} by the name \"$name\"" );
}
// catch the other exceptions
catch ( ex: Throwable )
{
// if they're from the newInstance invocation
if ( ex is InstantiationError ) throw IllegalClassSetupException( type, "class is uninstantiable" );
if ( ex is IllegalAccessException ) throw IllegalClassSetupException( type, "constructor isn't accessible" );
// IllegalArgumentException can't happen as the constructor has already been chosen for the specified arguments
if ( ex is InvocationTargetException ) HardwareMapExtension.e( "Exception while invoking HardwareExtension constructor: ${ex.javaClass.name}" );
throw ex; // throw it again
}
}
/**
* Finds the correct Hardware extension constructor.
*
* @param[type]
* The hardware extension class.
*
* @return The constructor for the extension, if one exists.
*
* @throws IllegalAnnotationValueException
* If the [type] class had a [HardwareExtension] annotation on it that had
* an invalid value (that is, one that doesn't have a value in the backing
* map of classes and `DeviceMapping`s) assigned to the `hardwareMapType`
* parameter.
* This should *never* happen to an end-user, that would mean that the
* developer who wrote the extension did so wrongly.
* @throws IllegalClassSetupException
* If [type] is a [HardwareExtension] that has been insufficiently
* set up, which could be for a multitude of reasons, check the
* error message if this occurs for more details.
*/
private fun HardwareMap.findExtensionConstructor( type: Class< out HardwareDevice > ): Constructor< out HardwareDevice >
{
var constructor: Constructor< out HardwareDevice >? = null;
// If the class is an @HardwareExtension, we can get the base type right out of the
// annotation parameters
val baseType = type.getHardwareMapType().java;
// ensure the base type is a valid one
if ( !deviceClassMap.containsKey( baseType ) )
{
HardwareMapExtension.e( "The @HardwareExtension.hardwareMapType value for class \"${type.simpleName}\" isn't supported!" );
throw IllegalAnnotationValueException( HardwareExtension::class.java, "hardwareMapType", type );
}
// ensure that there's a correct constructor for the extension class
try
{
constructor = type.getConstructor( baseType );
}
catch ( nsme: NoSuchMethodException ) {}
// try to select a more specific one, but fall back to the other one
try
{
constructor = type.getConstructor( baseType, String::class.java );
}
catch ( nsme: NoSuchMethodException ) {}
// if it's still null at this point
if ( constructor == null )
{
HardwareMapExtension.e( "Failed to find a constructor of either type in the hardware extension class: ${type.simpleName}!" );
throw IllegalClassSetupException(
type, "HardwareExtension devices must conform to certain constructor requirements!"
);
}
return constructor;
}
| mit | 28b77a7671dbc7f4d66e4f083c6f243b | 37.150685 | 152 | 0.653411 | 4.609019 | false | false | false | false |
CaMnter/AndroidLife | kotlin-life/src/main/java/com/camnter/newlife/kotlin/clazz/Clazz.kt | 1 | 801 | package com.camnter.newlife.kotlin.clazz
import android.content.Context
import android.os.Bundle
import android.widget.Toast
/**
* @author CaMnter
*/
open class KotlinSuperClass(name: String)
class KotlinClass(name: String, age: String) : KotlinSuperClass(name) {
init {
}
fun onCreate(savedInstanceState: Bundle?) {
}
fun add(x: Int, y: Int): Int = x + y
fun toast(context: Context, message: String, length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(context, message, length).show()
}
fun niceToast(context: Context, message: String, tag: String = niceText("KotlinClass"), length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(context, "class: $tag", length).show()
}
private fun niceText(text: String): String = "class: $text"
} | apache-2.0 | ba58da880707792fb4d8fe8f8dd3836b | 20.675676 | 127 | 0.67166 | 3.608108 | false | false | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/dao/ImageRepository.kt | 1 | 4336 | package com.ak47.cms.cms.dao
import com.ak47.cms.cms.entity.Image
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.transaction.annotation.Transactional
/**
* Created by jack on 2017/7/17.
*/
interface ImageRepository : PagingAndSortingRepository<Image, Long> {
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.category like %:category% order by a.gmtModified desc")
fun findByCategory(@Param("category") category: String): MutableList<Image>
@Query("select count(*) from #{#entityName} a where a.url = :url")
fun countByUrl(@Param("url") url: String): Int
/**源数据列表*/
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 order by rand()") override fun findAll(pageable: Pageable): Page<Image>
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.category like %:searchText% order by rand()")
fun search(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
/**收藏列表*/
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.isFavorite=1 order by a.gmtModified desc")
fun findAllFavorite(pageable: Pageable): Page<Image>
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.isFavorite=1 and a.category like %:searchText% order by a.gmtModified desc")
fun searchFavorite(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
@Modifying
@Transactional
@Query("update #{#entityName} a set a.isFavorite=1,a.gmtModified=now() where a.id=:id")
fun addFavorite(@Param("id") id: Long)
@Modifying
@Transactional
@Query("update #{#entityName} a set a.isDeleted=1 where a.id=:id")
fun delete(@Param("id") id: Long)
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.sourceType=1 order by rand()")
fun findGankAll(pageable: Pageable): Page<Image>
@Query("SELECT a from #{#entityName} a where a.sourceType=1 and a.isDeleted=0 and a.category like %:searchText% order by rand()")
fun searchGank(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
@Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.sourceType=:source_type order by rand()")
fun findAllImageByType(@Param("source_type") source_type: Int, pageable: Pageable): Page<Image>
@Query("SELECT a from #{#entityName} a where a.sourceType=:source_type and a.isDeleted=0 and a.category like %:searchText% order by rand()")
fun searchImageByType(@Param("source_type") source_type: Int, @Param("searchText") searchText: String, pageable: Pageable): Page<Image>
}
/**
@Query注解里面的value和nativeQuery=true,意思是使用原生的sql查询语句.
sql模糊查询like语法,我们在写sql的时候是这样写的
like '%?%'
但是在@Query的value字符串中, 这样写
like %?1%
另外,要注意的是: 对于执行update和delete语句需要添加@Modifying注解,以通知Spring Data 这是一个DELETE或UPDATE操作。
UPDATE或者DELETE操作需要使用事务,此时需要 定义Service层,在Service层的方法上添加事务操作。
注意JPQL不支持INSERT操作,可以使用 nativeQuery 来进行插入操作。
所谓本地查询,就是使用原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作。
使用@Param注解注入参数
SPEL表达式(使用时请参考最后的补充说明)
'#{#entityName}'值为'Image'对象对应的数据表名称(image)。
'#{#entityName}'是实体类的名称,
实体类 Image 使用@Entity注解后,spring会将实体类 Image 纳入管理。默认'#{#entityName}'的值就是 'Image'。
但是如果使用了@Entity(name = "image")来注解实体类 Image, 此时'#{#entityName}'的值就变成了'image'。
到此,事情就明了了,只需要在用 @Entity 来注解实体类时指定 name 为此实体类对应的表名。在 JPQL 语句中,就可以把'#{#entityName}'来作为数据表名使用。
*/
| apache-2.0 | 6c6efc19e77d8325e7264f4251bc5975 | 39.876404 | 145 | 0.739417 | 3.17452 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/InventoryClickListener.kt | 1 | 5596 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.bukkit.extension.addLore
import com.rpkit.core.service.Services
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKCraftingAction
import com.rpkit.professions.bukkit.profession.RPKProfessionService
import org.bukkit.GameMode
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.FurnaceInventory
import kotlin.math.roundToInt
import kotlin.random.Random
class InventoryClickListener(private val plugin: RPKProfessionsBukkit) : Listener {
@EventHandler
fun onInventoryClick(event: InventoryClickEvent) {
if (event.clickedInventory !is FurnaceInventory) return
if (event.slotType != InventoryType.SlotType.RESULT) return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val professionService = Services[RPKProfessionService::class.java] ?: return
val bukkitPlayer = event.whoClicked as? Player ?: return
if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
val item = event.currentItem ?: return
if (item.amount == 0 || item.type == Material.AIR) return
val material = item.type
val professions = professionService.getPreloadedProfessions(character)
if (professions == null) {
event.whoClicked.sendMessage(plugin.messages.noPreloadedProfessions)
event.isCancelled = true
return
}
val professionLevels = professions
.associateWith { profession -> professionService.getPreloadedProfessionLevel(character, profession) ?: 1 }
val potentialQualities = professionLevels.entries
.mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.SMELT, material, level) }
val quality = potentialQualities.maxByOrNull(RPKItemQuality::durabilityModifier)
val amount = professionLevels.entries.maxOfOrNull { (profession, level) ->
profession.getAmountFor(
RPKCraftingAction.SMELT,
material,
level
)
} ?: (plugin.config.getDouble("default.smelting.$material.amount", 1.0) * item.amount)
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = (amount * item.amount).roundToInt()
} else if (amount < 1) {
val random = Random.nextDouble()
if (random <= amount) {
item.amount = 1
} else {
event.currentItem = null
return
}
}
event.currentItem = item
professions.forEach { profession ->
val receivedExperience = plugin.config.getInt("professions.${profession.name.value}.experience.items.smelting.$material", 0) * item.amount
if (receivedExperience > 0) {
professionService.getProfessionExperience(character, profession).thenAccept { characterProfessionExperience ->
professionService.setProfessionExperience(character, profession, characterProfessionExperience + receivedExperience).thenRunAsync {
val level = professionService.getProfessionLevel(character, profession).join()
val experience = professionService.getProfessionExperience(character, profession).join()
event.whoClicked.sendMessage(plugin.messages.smeltExperience.withParameters(
profession = profession,
level = level,
receivedExperience = receivedExperience,
experience = experience - profession.getExperienceNeededForLevel(level),
nextLevelExperience = profession.getExperienceNeededForLevel(level + 1) - profession.getExperienceNeededForLevel(level),
totalExperience = experience,
totalNextLevelExperience = profession.getExperienceNeededForLevel(level + 1),
material = material
))
}
}
}
}
}
} | apache-2.0 | 93b6abb267dbcf065b2b117da697eba9 | 49.423423 | 151 | 0.677806 | 5.355024 | false | false | false | false |
wakim/esl-pod-client | app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/adapter/PodcastListAdapter.kt | 2 | 3688 | package br.com.wakim.eslpodclient.ui.podcastlist.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import br.com.wakim.eslpodclient.R
import br.com.wakim.eslpodclient.data.model.PodcastItem
import br.com.wakim.eslpodclient.ui.podcastlist.view.PodcastListItemView
import java.util.*
class PodcastListAdapter : RecyclerView.Adapter<PodcastListAdapter.ViewHolder>,
View.OnClickListener {
companion object {
const val LOADING_TYPE = 0
const val ITEM_TYPE = 1
}
val list : MutableList<PodcastItem> = mutableListOf()
val layoutInflater : LayoutInflater
var clickListener : ((PodcastItem) -> Unit)? = null
var overflowMenuClickListener : ((PodcastItem, View) -> Unit)? = null
var loading : Boolean = false
set(value) {
val old = field
field = value
if (old != value) {
val size = list.size
if (value)
notifyItemInserted(size)
else
notifyItemRemoved(size)
}
}
constructor(context: Context) : super() {
layoutInflater = LayoutInflater.from(context)
}
override fun getItemViewType(position: Int): Int =
if (loading && position == list.size) LOADING_TYPE else ITEM_TYPE
override fun onCreateViewHolder(viewGroup: ViewGroup?, viewType: Int): PodcastListAdapter.ViewHolder? {
return if (viewType == ITEM_TYPE) {
val view = layoutInflater.inflate(R.layout.list_item_podcast, viewGroup, false) as PodcastListItemView
view.setOnClickListener(this)
view.overflowMenuClickListener = overflowMenuClickListener
ViewHolder(view)
} else ViewHolder(layoutInflater.inflate(R.layout.list_item_loading, viewGroup, false))
}
override fun onBindViewHolder(viewHolder: PodcastListAdapter.ViewHolder?, position: Int) {
if (viewHolder!!.itemViewType == LOADING_TYPE) {
val lp = viewHolder.itemView.layoutParams as? RecyclerView.LayoutParams
lp?.height = if (list.size == 0) RecyclerView.LayoutParams.MATCH_PARENT else RecyclerView.LayoutParams.WRAP_CONTENT
} else {
val item = list[position]
viewHolder.view()?.bind(item)
}
}
override fun getItemCount(): Int = list.size + if (loading) 1 else 0
fun setItems(list: ArrayList<PodcastItem>) {
this.list.clear()
this.list.addAll(list)
notifyDataSetChanged()
}
fun add(podcastItem: PodcastItem) {
if (list.contains(podcastItem)) {
return
}
list.add(podcastItem)
notifyItemInserted(list.size - 1)
}
fun addAll(addition: ArrayList<PodcastItem>) {
val previousSize = list.size
list.addAll(addition)
notifyItemRangeInserted(previousSize, addition.size)
}
fun removeAll() {
val size = list.size
list.clear()
notifyItemRangeRemoved(0, size)
}
fun remove(podcastItem: PodcastItem) {
val indexOf = list.indexOf(podcastItem)
if (indexOf > -1) {
list.removeAt(indexOf)
notifyItemRemoved(indexOf)
}
}
override fun onClick(view: View) {
if (view is PodcastListItemView) {
clickListener?.invoke(view.podcastItem!!)
}
}
class ViewHolder : RecyclerView.ViewHolder {
constructor(view: View) : super(view)
fun view() : PodcastListItemView? = itemView as? PodcastListItemView
}
}
| apache-2.0 | 4c2d81ff1ea30106d8c517a43c7fb616 | 28.504 | 127 | 0.638829 | 4.771022 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/dismissedeventsstorage/DismissedEventAlertRecord.kt | 1 | 1682 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.dismissedeventsstorage
import com.github.quarck.calnotify.calendar.EventAlertRecord
enum class EventDismissType(val code: Int) {
ManuallyDismissedFromNotification(0),
ManuallyDismissedFromActivity(1),
AutoDismissedDueToCalendarMove(2),
EventMovedUsingApp(3);
companion object {
@JvmStatic
fun fromInt(v: Int) = values()[v]
}
val shouldKeep: Boolean
get() = true; // this != EventMovedUsingApp
val canBeRestored: Boolean
get() = this != AutoDismissedDueToCalendarMove && this != EventMovedUsingApp
}
data class DismissedEventAlertRecord(
val event: EventAlertRecord, // actual event that was dismissed
val dismissTime: Long, // when dismissal happened
val dismissType: EventDismissType // type of dismiss
) | gpl-3.0 | 3bf202f7137566beb854b17fc7b0e5bf | 35.586957 | 84 | 0.720571 | 4.205 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/object/Derived.kt | 1 | 2496 | package tutorial.`object`
import kotlin.properties.Delegates
import kotlin.reflect.KProperty
interface BaseForDerived1 {
fun printMessage()
fun printMessageLine()
}
class BaseForDerivedImpl1(val x: Int) : BaseForDerived1 {
override fun printMessage() {
print(x)
}
override fun printMessageLine() {
println(x)
}
}
class DerivedForBase1(b: BaseForDerived1) : BaseForDerived1 by b {
override fun printMessage() {
print("abc")
}
}
interface BaseForDerived2 {
val message: String
fun print()
}
class BaseForDerivedImpl2(val x: Int) : BaseForDerived2 {
override val message = "BaseImpl: x = $x"
override fun print() {
println(message)
}
}
class DerivedForBase2(b: BaseForDerived2) : BaseForDerived2 by b {
// 在 b 的 `print` 实现中不会访问到这个属性
override val message = "Message of Derived"
}
class Example {
var p: String by Delegate()
}
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name}' in $thisRef.")
}
}
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
class ObservableUser {
var name: String by Delegates.observable("<no name>") { prop, old, new ->
println("$old -> $new")
}
}
class MapUser(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
class MutableUser(val map: MutableMap<String, Any?>) {
var name: String by map
var age: Int by map
}
fun main() {
val b1 = BaseForDerivedImpl1(10)
DerivedForBase1(b1).printMessage() // abc
DerivedForBase1(b1).printMessageLine() // 10
val b2 = BaseForDerivedImpl2(10)
val derived2 = DerivedForBase2(b2)
derived2.print() // BaseImpl: x = 10
println(derived2.message) //Message of Derived
val e = Example()
println(e.p)
e.p = "NEW"
println(lazyValue) // hello
println(lazyValue) // hello
val user = ObservableUser()
user.name = "first" // <no name> -> first
user.name = "second" // first -> second
val mapUser = MapUser(
mapOf(
"name" to "John Doe",
"age" to 25
)
)
println(mapUser.name) // Prints "John Doe"
println(mapUser.age) // Prints 25
}
| bsd-2-clause | f66d221f80a9721a1bddf2fcc7de9567 | 21.234234 | 81 | 0.631686 | 3.592431 | false | false | false | false |
signed/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestStarter.kt | 1 | 4014 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.impl
import com.intellij.idea.IdeaApplication
import com.intellij.openapi.application.ApplicationStarter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.remote.JUnitClient
import org.junit.runner.JUnitCore
/**
* @author Sergey Karashevich
*/
class GuiTestStarter: IdeaApplication.IdeStarter(), ApplicationStarter {
private val LOG = Logger.getInstance(this.javaClass)
val GUI_TEST_PORT = "idea.gui.test.port"
val GUI_TEST_HOST = "idea.gui.test.host"
val GUI_TEST_LIST = "idea.gui.test.list"
val host: String by lazy {
System.getProperty(GUI_TEST_HOST)
}
val port: Int? by lazy {
val guiTestPort = System.getProperty(GUI_TEST_PORT)
if (guiTestPort == null || guiTestPort == PORT_UNDEFINED) null
else guiTestPort.toInt()
}
val guiTestList: List<Class<*>> by lazy {
val listOfTestNames = System.getProperty(GUI_TEST_LIST)?.split(",")!!
listOfTestNames.map { testName -> Class.forName(testName) }
}
private var myClient: JUnitClient? = null
private val guiTestThread: Thread by lazy {
object : Thread("GuiTest thread") {
override fun run() {
[email protected]()
}
}
}
override fun getCommandName() = "guitest"
private val PORT_UNDEFINED = "undefined"
private val HOST_LOCALHOST = "localhost"
override fun premain(args: Array<String>) {
processArgs(args)
runActivity(args)
super.premain(args)
}
override fun main(args: Array<String>) {
val myArgs = removeGuiTestArgs(args)
super.main(myArgs)
}
fun stopGuiTestThread() {
LOG.info("Stopping guiTestThread")
assert(Thread.currentThread() != guiTestThread)
guiTestThread.join()
if (myClient != null) myClient!!.stopClient()
}
fun runActivity(args: Array<String>) {
LOG.info("Starting GuiTest activity")
guiTestThread.start()
}
fun run() {
assert(myClient == null)
if (port != null) {
myClient = JUnitClient(host, port!!)
myClient!!.runTests(*guiTestList.toTypedArray())
} else {
val core = JUnitCore()
core.run(*guiTestList.toTypedArray())
}
}
/**
* We assume next argument string model: main.app -guitest testName1,testName2,testName3 host="localhost" port=5555
*/
private fun processArgs(args: Array<String>) {
val guiTestList = args[1].removeSurrounding("\"")
System.setProperty(GUI_TEST_LIST, guiTestList)
val hostArg : String? = args.find { arg -> arg.toLowerCase().startsWith("host") }?.substringAfter("host=") ?: HOST_LOCALHOST
System.setProperty(GUI_TEST_HOST, hostArg!!.removeSurrounding("\""))
val portArg : String? = args.find { arg -> arg.toLowerCase().startsWith("port") }?.substringAfter("port=") ?: PORT_UNDEFINED
if (portArg != null)
System.setProperty(GUI_TEST_PORT, portArg.removeSurrounding("\""))
else
System.setProperty(GUI_TEST_PORT, PORT_UNDEFINED)
LOG.info("Set GUI tests list: $guiTestList")
LOG.info("Set GUI tests host: $hostArg")
LOG.info("Set GUI tests port: $portArg")
}
private fun removeGuiTestArgs(args: Array<String>): Array<out String>? {
return args.sliceArray(2..args.lastIndex) //lets remove guitest keyword and list of guitests
.filterNot { arg -> arg.startsWith("port") || arg.startsWith("host") }//lets remove host and port from args
.toTypedArray()
}
}
| apache-2.0 | a672b92b3e194a661ccbd086a6d38153 | 31.112 | 129 | 0.694818 | 3.855908 | false | true | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/viewgroup/DYRecordView.kt | 1 | 21385 | package com.angcyo.uiview.viewgroup
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.support.v4.view.GestureDetectorCompat
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.LinearInterpolator
import com.angcyo.library.utils.L
import com.angcyo.uiview.R
import com.angcyo.uiview.RCrashHandler
import com.angcyo.uiview.kotlin.density
import com.angcyo.uiview.kotlin.getDrawCenterTextCx
import com.angcyo.uiview.kotlin.maxValue
import com.angcyo.uiview.kotlin.textHeight
import com.angcyo.uiview.resources.RAnimListener
import com.angcyo.uiview.skin.SkinHelper
import com.angcyo.uiview.utils.T_
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:模仿抖音视频录制按钮
* 创建人员:Robi
* 创建时间:2017/09/19 17:12
* 修改人员:Robi
* 修改时间:2017/09/19 17:12
* 修改备注:
* Version: 1.0.0
*/
class DYRecordView(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) {
companion object {
/**内圈呼吸的半径范围*/
var INNER_CIRCLE_MIN_R = 0.8f
var INNER_CIRCLE_MAX_R = 0.95f
/**录制模式, 长按录制*/
val RECORD_TYPE_LONG = 1
/**录制模式, 点击录制*/
val RECORD_TYPE_CLICK = 2
}
var showText = "按住拍"
var showTextSize = 20 * density
var showTextColor = Color.WHITE
/**圈圈的颜色(保留值属性)*/
var circleColor = Color.RED
/**圈圈的颜色(绘制专用)*/
var circleDrawColor = circleColor
get() {
return if (toLongAnimator != null && toLongAnimator!!.isStarted) {
SkinHelper.getTranColor(circleColor, 0x80)
} else {
field
}
}
/**默认时, 圈的半径*/
var circleDefaultRadius = 40 * density
/**开始录时, 圈允许放大到的倍数*/
var circleMaxScale = 1.5f
/**切换录制触发的方式*/
var recordType = RECORD_TYPE_LONG
set(value) {
if (field == value) {
return
} else {
endRecord()
}
field = value
if (field == RECORD_TYPE_LONG) {
circleInnerDrawScale = 0f
circleDrawColor = circleColor
circleMaxScale = 1.5f
animToRecordTypeLong()
} else {
circleMaxScale = 1.2f
circleInnerDrawScale = 0.85f
circleClickInnerDrawScale = circleInnerDrawScale - 0.08f
circleDrawClickInnerDrawScale = circleClickInnerDrawScale
circleDrawColor = SkinHelper.getTranColor(circleColor, 0x80)
animToRecordTypeClick()
}
}
/**切换录制模式*/
fun switchRecordType() {
recordType = if (recordType == RECORD_TYPE_LONG) {
RECORD_TYPE_CLICK
} else {
RECORD_TYPE_LONG
}
}
/**推荐使用 Match_parent*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
/**默认情况下, 距离底部的距离*/
var defaultCircleOffsetBottom = 30 * density
init {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.DYRecordView)
val string = typedArray.getString(R.styleable.DYRecordView_r_show_text)
if (string != null) {
showText = string
}
showTextSize = typedArray.getDimensionPixelOffset(R.styleable.DYRecordView_r_show_text_size, showTextSize.toInt()).toFloat()
showTextColor = typedArray.getColor(R.styleable.DYRecordView_r_show_text_color, showTextColor)
if (isInEditMode) {
circleColor = Color.RED
} else {
circleColor = SkinHelper.getSkin().themeSubColor
}
circleColor = typedArray.getColor(R.styleable.DYRecordView_r_circle_color, circleColor)
circleDrawColor = circleColor
circleDefaultRadius = typedArray.getDimensionPixelOffset(R.styleable.DYRecordView_r_circle_default_radius, circleDefaultRadius.toInt()).toFloat()
circleMaxScale = typedArray.getFloat(R.styleable.DYRecordView_r_circle_max_scale, circleMaxScale)
defaultCircleOffsetBottom = typedArray.getDimensionPixelOffset(R.styleable.DYRecordView_r_default_circle_offset_bottom, defaultCircleOffsetBottom.toInt()).toFloat()
typedArray.recycle()
}
private val paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL_AND_STROKE
}
}
private val textPaint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = showTextSize
color = showTextColor
}
}
//圈绘制时, 的x坐标
private val cx: Float
get() = ((measuredWidth - paddingLeft - paddingRight) / 2 + paddingLeft).toFloat()
//y坐标
private val cy: Float
get() = measuredHeight - paddingBottom - defaultCircleOffsetBottom - circleDefaultRadius
private var drawCX: Float = 0f
private var drawCY: Float = 0f
/*保存动画需要结束时的各项值*/
private var drawEndCX: Float = 0f
private var drawEndCY: Float = 0f
private var circleDrawEndRadius: Float = 0f
private var circleInnerDrawEndScale = 0f
private var showTextSizeDrawEnd = 0f
//绘制时, 圆圈的半径
private var circleDrawRadius: Float = circleDefaultRadius
private val circleRect by lazy {
RectF()
}
/*点击录制时, 暂停显示的矩形坐标*/
private val clickRecordRect by lazy {
RectF()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
drawCX = cx
drawCY = cy
circleDrawRadius = circleDefaultRadius
showTextSizeDraw = showTextSize
circleRect.set(cx - circleDefaultRadius, cy - circleDefaultRadius, cx + circleDefaultRadius, cy + circleDefaultRadius)
clickRecordRect.set(cx - circleDefaultRadius / 2, cy - circleDefaultRadius / 2,
cx + circleDefaultRadius / 2, cy + circleDefaultRadius / 2)
circleBitmap?.recycle()
if (measuredWidth != 0 && measuredHeight != 0) {
circleBitmap = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888)
circleCanvas = Canvas(circleBitmap)
}
}
private var circleCanvas: Canvas? = null
private var circleBitmap: Bitmap? = null
private var circleInnerDrawScale = 0f
private var circleClickInnerDrawScale = 0f
private var circleDrawClickInnerDrawScale = 0f
private var showTextSizeDraw = 0f
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (recordType == RECORD_TYPE_LONG && toLongAnimator != null && toLongAnimator!!.isStarted) {
drawTypeClick(canvas)
} else if (recordType == RECORD_TYPE_LONG) {
drawTypeLong(canvas)
} else if (recordType == RECORD_TYPE_CLICK) {
drawTypeClick(canvas)
}
recordingListener()
}
private fun drawTypeClick(canvas: Canvas) {
//绘制外圈透明圆
circleCanvas?.let {
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
it.drawPaint(paint)
paint.xfermode = null
paint.color = circleDrawColor
circleCanvas?.drawCircle(drawCX, drawCY, circleDrawRadius, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)
paint.color = Color.TRANSPARENT
circleCanvas?.drawCircle(drawCX, drawCY, circleDrawRadius * circleInnerDrawScale, paint)
paint.xfermode = null
canvas.drawBitmap(circleBitmap, 0f, 0f, null)
}
//绘制内部
paint.color = circleColor
if (isRecording) {
canvas.drawRoundRect(clickRecordRect, 6 * density, 6 * density, paint)
} else {
canvas.drawCircle(drawCX, drawCY, circleDefaultRadius * circleDrawClickInnerDrawScale, paint)
}
}
private fun drawTypeLong(canvas: Canvas) {
//绘制圆
circleCanvas?.let {
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
it.drawPaint(paint)
paint.xfermode = null
paint.color = circleDrawColor
circleCanvas?.drawCircle(drawCX, drawCY, circleDrawRadius, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)
paint.color = Color.TRANSPARENT
circleCanvas?.drawCircle(drawCX, drawCY, circleDrawRadius * circleInnerDrawScale, paint)
paint.xfermode = null
canvas.drawBitmap(circleBitmap, 0f, 0f, null)
}
canvas.save()
//绘制文本
textPaint.textSize = showTextSizeDraw
canvas.drawText(showText, getDrawCenterTextCx(textPaint, showText), cy + textHeight(textPaint) / 2 - textPaint.descent(), textPaint)
canvas.restore()
}
private var isTouchDown = true
override fun onTouchEvent(event: MotionEvent): Boolean {
//L.e("call: onTouchEvent -> ${isEnabled} $event")
if (isEnabled) {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
if (onRecordListener != null) {
if (onRecordListener!!.onTouchDown()) {
isTouchDown = false
return false
}
}
isTouchDown = true
}
}
//return super.onTouchEvent(event)
} else {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> isTouchDown = false
}
}
if (isTouchDown) {
when (event.actionMasked) {
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
if (recordType == RECORD_TYPE_LONG) {
endRecord()
}
}
}
return gestureCompat.onTouchEvent(event)
} else {
if (isEnabled && recordType == RECORD_TYPE_CLICK) {
return gestureCompat.onTouchEvent(event)
}
}
return true
}
/**调用此方法, 结束录制*/
fun endRecord(notify: Boolean = true) {
drawEndCX = drawCX
drawEndCY = drawCY
circleDrawEndRadius = circleDrawRadius
if (recordType == RECORD_TYPE_CLICK) {
circleInnerDrawEndScale = 0.85f
} else {
circleInnerDrawEndScale = 0f
}
showTextSizeDrawEnd = showTextSizeDraw
touchInAnimator?.cancel()
breathAnimator?.cancel()
reset()
if (notify) {
endRecordListener()
}
}
/**点击录制模式下的, 手动开始录制按钮*/
fun startRecordWidthClick() {
if (recordType == RECORD_TYPE_CLICK && !isRecording) {
startBreath()
}
}
/*手势松开, 恢复动画*/
private var resetAnimator: ValueAnimator? = null
private fun reset() {
if (resetAnimator == null) {
resetAnimator = ValueAnimator.ofFloat(1f, 0f).apply {
interpolator = AccelerateInterpolator()
duration = 200
addUpdateListener { animation ->
val animatedValue: Float = animation.animatedValue as Float
drawCX = cx + (drawEndCX - cx) * animatedValue
drawCY = cy + (drawEndCY - cy) * animatedValue
circleDrawRadius = circleDefaultRadius + (circleDrawEndRadius - circleDefaultRadius) * animatedValue
if (recordType == RECORD_TYPE_CLICK) {
circleInnerDrawScale = 0.85f
} else {
circleInnerDrawScale = (animatedValue).maxValue(circleInnerDrawEndScale)
}
showTextSizeDraw = showTextSizeDrawEnd + (showTextSize - showTextSizeDrawEnd) * (1 - animatedValue)
postInvalidate()
}
addListener(object : RAnimListener() {
override fun onAnimationFinish(animation: Animator?, cancel: Boolean) {
super.onAnimationFinish(animation, cancel)
resetAnimator = null
}
})
start()
}
}
}
/*控制手势事件*/
private val gestureCompat: GestureDetectorCompat by lazy {
GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onLongPress(event: MotionEvent) {
L.e("call: onLongPress -> ")
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
if (recordType == RECORD_TYPE_CLICK) {
return false
}
drawCX -= distanceX
drawCY -= distanceY
postInvalidate()
return true
}
override fun onDown(event: MotionEvent): Boolean {
val contains = circleRect.contains(event.x, event.y)
if (contains) {
onTouchInCircle()
}
return contains
}
}).apply {
setIsLongpressEnabled(false)
}
}
/*手势在圆圈内触发*/
private var touchInAnimator: ValueAnimator? = null
private fun onTouchInCircle() {
if (recordType == RECORD_TYPE_CLICK) {
if (isRecording) {
endRecord()
return
}
}
if (touchInAnimator == null) {
touchInAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
interpolator = AccelerateInterpolator()
duration = 200
addUpdateListener { animation ->
val animatedValue: Float = animation.animatedValue as Float
circleDrawRadius = circleDefaultRadius * (1 + (circleMaxScale - 1) * animatedValue)
circleInnerDrawScale = (animatedValue).maxValue(INNER_CIRCLE_MIN_R)
showTextSizeDraw = showTextSize * (1 - animatedValue)
postInvalidate()
}
addListener(object : RAnimListener() {
override fun onAnimationFinish(animation: Animator?, cancel: Boolean) {
super.onAnimationFinish(animation, cancel)
touchInAnimator = null
if (!cancel) {
startBreath()
}
}
})
start()
}
}
}
/*呼吸动画*/
private var breathAnimator: ValueAnimator? = null
private fun startBreath() {
if (breathAnimator == null) {
breathAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
interpolator = LinearInterpolator()
duration = 500
repeatMode = ValueAnimator.REVERSE
repeatCount = ValueAnimator.INFINITE
addUpdateListener { animation ->
val animatedValue: Float = animation.animatedValue as Float
circleInnerDrawScale = INNER_CIRCLE_MIN_R + (INNER_CIRCLE_MAX_R - INNER_CIRCLE_MIN_R) * animatedValue
postInvalidate()
}
addListener(object : RAnimListener() {
override fun onAnimationFinish(animation: Animator?, cancel: Boolean) {
super.onAnimationFinish(animation, cancel)
breathAnimator = null
}
})
start()
}
}
startRecordListener()
}
private var isRecording = false
private var startRecordTime = 0L
//开始录制
private fun startRecordListener() {
if (isRecording) {
return
}
isRecording = true
startRecordTime = System.currentTimeMillis()
onRecordListener?.onRecordStart()
}
//结束录制
private fun endRecordListener() {
if (isRecording) {
isRecording = false
val progress = getRecordProgress()
startRecordTime = 0L
onRecordListener?.onRecordEnd(progress[0], progress[1])
}
}
//录制中
private var recordProgress = -1
private fun recordingListener() {
if (isRecording) {
val progress = getRecordProgress()
if (recordProgress != progress[1]) {
recordProgress = progress[1]
onRecordListener?.onRecording(progress[0], progress[1])
}
}
}
private fun getRecordProgress(): IntArray {
val currentTimeMillis = System.currentTimeMillis()
return intArrayOf(((currentTimeMillis - startRecordTime) / 1000).toInt(), ((currentTimeMillis - startRecordTime).toInt()))
}
private var toClickAnimator: ValueAnimator? = null
private fun animToRecordTypeClick() {
if (toClickAnimator == null) {
toClickAnimator = ValueAnimator.ofFloat(1f, circleClickInnerDrawScale).apply {
interpolator = LinearInterpolator()
duration = 200
addUpdateListener { animation ->
val animatedValue: Float = animation.animatedValue as Float
circleDrawClickInnerDrawScale = animatedValue
postInvalidate()
}
addListener(object : RAnimListener() {
override fun onAnimationFinish(animation: Animator?, cancel: Boolean) {
super.onAnimationFinish(animation, cancel)
toClickAnimator = null
}
})
start()
}
}
}
private var toLongAnimator: ValueAnimator? = null
private fun animToRecordTypeLong() {
if (toLongAnimator == null) {
toLongAnimator = ValueAnimator.ofFloat(circleClickInnerDrawScale, 1f).apply {
interpolator = LinearInterpolator()
duration = 200
addUpdateListener { animation ->
val animatedValue: Float = animation.animatedValue as Float
circleDrawClickInnerDrawScale = animatedValue
postInvalidate()
}
addListener(object : RAnimListener() {
override fun onAnimationFinish(animation: Animator?, cancel: Boolean) {
super.onAnimationFinish(animation, cancel)
toLongAnimator = null
}
})
start()
}
}
}
var onRecordListener: OnRecordListener? = null
/**是否检查sd卡剩余空间*/
var checkSDAvailable = true
/**是否检查内存剩余空间*/
var checkMemoryInfo = true
public fun canRecord(): Boolean {
var result = true
if (checkSDAvailable) {
result = RCrashHandler.getAvailableExternalMemorySize() / 1024 / 1024 > 500
if (!result) {
T_.error("存储空间不足, 请清理.")
return result
}
}
if (checkMemoryInfo && result) {
val memoryInfo = RCrashHandler.getMemoryInfo(context)
if (memoryInfo.availMem / 1024 / 1024 < 100) {
result = false
T_.error("内存不足, 请清理.")
}
}
return result
}
abstract class OnRecordListener {
/**当手指按下的时候, 会回调此方法, 返回true, 表示拦截事件, 不处理录制*/
open fun onTouchDown(): Boolean {
return false
}
open fun onRecordStart() {
}
open fun onRecordEnd(second: Int, millisecond: Int) {
}
open fun onRecording(second: Int /*录制了多少秒*/, millisecond: Int /*毫秒单位*/) {
}
}
} | apache-2.0 | d1e315634fc853932b84e9dd77a371ba | 33.049153 | 172 | 0.556657 | 4.861745 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/helper/SoundHelper.kt | 1 | 3137 | package com.angcyo.uiview.helper
import com.angcyo.uiview.RApplication
import com.angcyo.uiview.helper.sound.*
import java.io.File
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:用来播放音效
* 创建人员:Robi
* 创建时间:2017/12/22 09:09
* 修改人员:Robi
* 修改时间:2017/12/22 09:09
* 修改备注:
* Version: 1.0.0
*/
class SoundHelper {
/*使用MediaPlayer播放*/
private val musicManager: MusicManager by lazy {
MusicManager()
}
/*使用SoundPool播放*/
private val soundManager: SoundManager by lazy {
SoundManager()
}
fun playMusiuc(pAssetPath: String): Music? {
var music: Music? = null
try {
music = MusicFactory.createMusicFromAsset(musicManager,
RApplication.getApp(),
pAssetPath)
music.play()
} catch (e: Exception) {
e.printStackTrace()
}
return music
}
fun playMusiuc(file: File): Music? {
var music: Music? = null
try {
music = MusicFactory.createMusicFromFile(musicManager,
file)
music.play()
} catch (e: Exception) {
e.printStackTrace()
}
return music
}
fun playMusiuc(resId: Int): Music? {
var music: Music? = null
try {
music = MusicFactory.createMusicFromResource(musicManager,
RApplication.getApp(),
resId)
music.play()
} catch (e: Exception) {
e.printStackTrace()
}
return music
}
fun releaseMusicAll() {
musicManager.releaseAll()
}
fun pauseMusicAll() {
musicManager.pause()
}
fun resumeMusicAll() {
musicManager.resume()
}
fun playSound(pAssetPath: String): Sound? {
var sound: Sound? = null
try {
sound = SoundFactory.createSoundFromAsset(soundManager,
RApplication.getApp(),
pAssetPath)
sound.play()
} catch (e: Exception) {
e.printStackTrace()
}
return sound
}
fun playSound(file: File): Sound? {
var sound: Sound? = null
try {
sound = SoundFactory.createSoundFromFile(soundManager,
file)
sound.play()
} catch (e: Exception) {
e.printStackTrace()
}
return sound
}
fun playSound(resId: Int): Sound? {
var sound: Sound? = null
try {
sound = SoundFactory.createSoundFromResource(soundManager,
RApplication.getApp(),
resId)
sound.play()
} catch (e: Exception) {
e.printStackTrace()
}
return sound
}
fun releaseSoundAll() {
soundManager.releaseAll()
}
} | apache-2.0 | a850bdb5d169749232ac086bc4bc3f5a | 22.680328 | 70 | 0.508475 | 4.58689 | false | false | false | false |
AlmasB/GroupNet | src/main/kotlin/icurves/diagram/curve/CircleCurve.kt | 1 | 2755 | package icurves.diagram.curve
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import icurves.diagram.Curve
import icurves.util.Converter
import icurves.util.Label
import javafx.geometry.Point2D
import javafx.scene.shape.Circle
import java.util.*
/**
* A curve whose shape is a circle.
*
* @author Almas Baimagambetov ([email protected])
*/
@JsonIgnoreProperties("polygon", "shape", "cachedPolygon", "cachedShape", "minX", "minY", "maxX", "maxY", "smallRadius", "bigRadius")
class CircleCurve(
label: Label,
var centerX: Double,
var centerY: Double,
var radius: Double) : Curve(label) {
private val nudge = 0.1
fun getSmallRadius() = radius - nudge
fun getBigRadius() = radius + nudge
fun shift(x: Double, y: Double) {
centerX += x
centerY += y
}
fun scaleAboutZero(scale: Double) {
centerX *= scale
centerY *= scale
radius *= scale
}
fun getMinX() = (centerX - radius).toInt()
fun getMaxX() = (centerX + radius).toInt() + 1
fun getMinY() = (centerY - radius).toInt()
fun getMaxY() = (centerY + radius).toInt() + 1
override fun computeShape() = Circle(centerX, centerY, getBigRadius())
override fun computePolygon() = Converter.circleToPolygon(this)
override fun copyWithNewLabel(newLabel: String): Curve {
val copy = CircleCurve(newLabel, centerX, centerY, radius)
copy.setLabelPositionX(getLabelPositionX())
copy.setLabelPositionY(getLabelPositionY())
return copy
}
override fun translate(translate: Point2D): Curve {
val copy = CircleCurve(label, centerX + translate.x, centerY + translate.y, radius)
copy.setLabelPositionX(getLabelPositionX() + translate.x)
copy.setLabelPositionY(getLabelPositionY() + translate.y)
return copy
}
override fun scale(scale: Double, pivot: Point2D): Curve {
val scaled = CircleCurve(label, centerX * scale + (1-scale) * pivot.x, centerY * scale + (1-scale) * pivot.y, radius * scale)
scaled.setLabelPositionX(getLabelPositionX() * scale + (1-scale) * pivot.x)
scaled.setLabelPositionY(getLabelPositionY() * scale + (1-scale) * pivot.y)
return scaled
}
override fun equals(other: Any?): Boolean {
if (other !is CircleCurve)
return false
return label == other.label &&
centerX == other.centerX &&
centerY == other.centerY &&
radius == other.radius
}
override fun hashCode(): Int {
return Objects.hash(label, centerX, centerY, radius)
}
override fun toDebugString(): String {
return "$this($centerX, $centerY, r=$radius)"
}
} | apache-2.0 | 9116461008781dd796ec55b53dfc25cf | 29.285714 | 133 | 0.639927 | 4.155354 | false | false | false | false |
chRyNaN/GuitarChords | android/src/main/java/com/chrynan/chords/util/ParcelableUtils.kt | 1 | 2257 | package com.chrynan.chords.util
import android.content.Intent
import android.os.Bundle
import android.os.Parcel
import com.chrynan.chords.model.*
import com.chrynan.chords.parcel.ChordAndChartParceler
import com.chrynan.chords.parcel.ChordChartParceler
import com.chrynan.chords.parcel.ChordParceler
// Bundle
fun Bundle.putChord(key: String, chord: Chord) = putParcelable(key, ParcelableChordWrapper(chord))
fun Bundle.putChordChart(key: String, chart: ChordChart) = putParcelable(key, ParcelableChartWrapper(chart))
fun Bundle.putChordAndChart(key: String, chordAndChart: ChordAndChart) = putParcelable(key, ParcelableChordAndChartWrapper(chordAndChart))
fun Bundle.getChord(key: String) = getParcelable<ParcelableChordWrapper>(key)?.chord
fun Bundle.getChordChart(key: String) = getParcelable<ParcelableChartWrapper>(key)?.chart
fun Bundle.getChordAndChart(key: String) = getParcelable<ParcelableChordAndChartWrapper>(key)?.chordAndChart
// Intent
fun Intent.putChordExtra(key: String, chord: Chord) = putExtra(key, ParcelableChordWrapper(chord))
fun Intent.putChordChartExtra(key: String, chart: ChordChart) = putExtra(key, ParcelableChartWrapper(chart))
fun Intent.putChordAndChartExtra(key: String, chordAndChart: ChordAndChart) = putExtra(key, ParcelableChordAndChartWrapper(chordAndChart))
fun Intent.getChordExtra(key: String) = getParcelableExtra<ParcelableChordWrapper>(key)?.chord
fun Intent.getChordChartExtra(key: String) = getParcelableExtra<ParcelableChartWrapper>(key)?.chart
fun Intent.getChordAndChartExtra(key: String) = getParcelableExtra<ParcelableChordAndChartWrapper>(key)?.chordAndChart
// Parcel
fun Parcel.writeChord(chord: Chord, flags: Int) = ChordParceler.apply { chord.write(this@writeChord, flags) }
fun Parcel.writeChordChart(chart: ChordChart, flags: Int) = ChordChartParceler.apply { chart.write(this@writeChordChart, flags) }
fun Parcel.writeChordAndChart(chordAndChart: ChordAndChart, flags: Int) = ChordAndChartParceler.apply { chordAndChart.write(this@writeChordAndChart, flags) }
fun Parcel.readChord(): Chord = ChordParceler.create(this)
fun Parcel.readChordChart(): ChordChart = ChordChartParceler.create(this)
fun Parcel.readChordAndChart(): ChordAndChart = ChordAndChartParceler.create(this) | apache-2.0 | eef0f4e1294c0715020b3445caa3e083 | 43.27451 | 157 | 0.819229 | 3.838435 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/multiblocks/structures/MultiblockOilHeater.kt | 2 | 3220 | package com.cout970.magneticraft.features.multiblocks.structures
import com.cout970.magneticraft.misc.vector.plus
import com.cout970.magneticraft.misc.vector.rotateBox
import com.cout970.magneticraft.misc.vector.times
import com.cout970.magneticraft.misc.vector.vec3Of
import com.cout970.magneticraft.systems.multiblocks.*
import com.cout970.magneticraft.systems.tilerenderers.PIXEL
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.AxisAlignedBB
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.util.text.ITextComponent
import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks
object MultiblockOilHeater : Multiblock() {
override val name: String = "oil_heater"
override val size: BlockPos = BlockPos(3, 3, 3)
override val scheme: List<MultiblockLayer>
override val center: BlockPos = BlockPos(1, 0, 0)
init {
val U = columnBlock(EnumFacing.UP)
val H = columnBlock(EnumFacing.NORTH)
val I = corrugatedIronBlock()
val M = mainBlockOf(controllerBlock)
scheme = yLayers(
zLayers(
listOf(U, U, U), // y = 2
listOf(I, I, I),
listOf(I, I, I)),
zLayers(
listOf(U, U, U), // y = 1
listOf(I, I, I),
listOf(I, I, I)),
zLayers(
listOf(U, M, U), // y = 0
listOf(H, H, H),
listOf(H, H, H))
)
}
override fun getControllerBlock() = Multiblocks.oilHeater
override fun getGlobalCollisionBoxes(): List<AxisAlignedBB> = hitboxes
val hitboxes = listOf(
Vec3d(0.000, 0.000, -32.000) * PIXEL to Vec3d(48.000, 16.000, 16.000) * PIXEL,
Vec3d(0.000, 16.000, 0.000) * PIXEL to Vec3d(48.000, 48.000, 16.000) * PIXEL,
Vec3d(2.000, 16.000, -30.000) * PIXEL to Vec3d(24.000, 46.000, 0.000) * PIXEL,
Vec3d(1.000, 41.000, -31.000) * PIXEL to Vec3d(2.000, 42.000, 0.000) * PIXEL,
Vec3d(1.000, 32.000, -31.000) * PIXEL to Vec3d(2.000, 33.000, 0.000) * PIXEL,
Vec3d(1.000, 23.000, -31.000) * PIXEL to Vec3d(2.000, 24.000, 0.000) * PIXEL,
Vec3d(24.000, 16.000, -30.000) * PIXEL to Vec3d(46.000, 46.000, 0.000) * PIXEL,
Vec3d(46.000, 41.000, -31.000) * PIXEL to Vec3d(47.000, 42.000, 0.000) * PIXEL,
Vec3d(46.000, 32.000, -31.000) * PIXEL to Vec3d(47.000, 33.000, 0.000) * PIXEL,
Vec3d(46.000, 23.000, -31.000) * PIXEL to Vec3d(47.000, 24.000, 0.000) * PIXEL,
Vec3d(2.000, 41.000, -31.000) * PIXEL to Vec3d(46.000, 42.000, -30.000) * PIXEL,
Vec3d(2.000, 32.000, -31.000) * PIXEL to Vec3d(46.000, 33.000, -30.000) * PIXEL,
Vec3d(2.000, 23.000, -31.000) * PIXEL to Vec3d(46.000, 24.000, -30.000) * PIXEL,
Vec3d(20.000, 20.000, -32.000) * PIXEL to Vec3d(28.000, 28.000, -30.000) * PIXEL,
Vec3d(20.000, 46.000, -12.000) * PIXEL to Vec3d(28.000, 48.000, -4.000) * PIXEL
).map { EnumFacing.SOUTH.rotateBox(vec3Of(0.5), it) + vec3Of(1, 0, 0) }
override fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> = emptyList()
} | gpl-2.0 | 61bd96afcc006b4e91bd91281f190c09 | 45.014286 | 133 | 0.626398 | 2.959559 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/facebook/FacebookAuthFlow.kt | 1 | 2626 | package com.baulsupp.okurl.services.facebook
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.NoToken
import com.baulsupp.okurl.kotlin.queryMap
import okhttp3.OkHttpClient
import okhttp3.Response
import java.net.URLEncoder
object FacebookAuthFlow {
val ALL_PERMISSIONS = listOf(
"public_profile",
"user_friends",
"email",
"user_about_me",
"user_actions.books",
"user_actions.fitness",
"user_actions.music",
"user_actions.news",
"user_actions.video",
"user_birthday",
"user_education_history",
"user_events",
"user_games_activity",
"user_hometown",
"user_likes",
"user_location",
"user_managed_groups",
"user_photos",
"user_posts",
"user_relationships",
"user_relationship_details",
"user_religion_politics",
"user_tagged_places",
"user_videos",
"user_website",
"user_work_history",
"read_custom_friendlists",
"read_insights",
"read_audience_network_insights",
"read_page_mailboxes",
"manage_pages",
"publish_pages",
"publish_actions",
"rsvp_event",
"pages_show_list",
"pages_manage_cta",
"pages_manage_instant_articles",
"ads_read",
"ads_management",
"pages_messaging",
"pages_messaging_phone_number"
)
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String,
scopes: List<String>
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val serverUri = s.redirectUri
val loginUrl =
"https://www.facebook.com/dialog/oauth?client_id=$clientId&redirect_uri=$serverUri&scope=" + URLEncoder.encode(
scopes.joinToString(","), "UTF-8"
)
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val tokenUrl =
"https://graph.facebook.com/v2.10/oauth/access_token?client_id=$clientId&redirect_uri=$serverUri&client_secret=$clientSecret&code=$code"
val map = client.queryMap<Any>(tokenUrl, NoToken)
val shortToken = map["access_token"] as String
val exchangeUrl =
"https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=$clientId&client_secret=$clientSecret&fb_exchange_token=$shortToken"
val longTokenBody = client.queryMap<Any>(
exchangeUrl,
NoToken
)
return Oauth2Token(longTokenBody["access_token"] as String, "", clientId, clientSecret)
}
}
}
| apache-2.0 | abdff8ea46575a89227f2efca3baeccb | 26.642105 | 162 | 0.673267 | 3.70904 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/BaseComposeFragment.kt | 1 | 4967 | /* 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/. */
@file:Suppress("UnusedMaterialScaffoldPaddingParameter")
package org.mozilla.focus.settings
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.fragment.app.Fragment
import com.google.accompanist.insets.LocalWindowInsets
import com.google.accompanist.insets.rememberInsetsPaddingValues
import com.google.accompanist.insets.ui.TopAppBar
import org.mozilla.focus.R
import org.mozilla.focus.activity.MainActivity
import org.mozilla.focus.ext.hideToolbar
import org.mozilla.focus.ui.theme.FocusTheme
import org.mozilla.focus.ui.theme.focusColors
import org.mozilla.focus.utils.StatusBarUtils
/**
* Fragment acting as a wrapper over a [Composable] which will be shown below a [TopAppBar].
*
* Useful for Fragments shown in otherwise fullscreen Activities such that they would be shown
* beneath the status bar not below it.
*
* Classes extending this are expected to provide the [Composable] content and a basic behavior
* for the toolbar: title and navigate up callback.
*/
abstract class BaseComposeFragment : Fragment() {
/**
* Screen title shown in toolbar.
*/
open val titleRes: Int? = null
open val titleText: String? = null
/**
* Callback for the up navigation button shown in toolbar.
*/
abstract fun onNavigateUp(): () -> Unit
/**
* content of the screen in compose. That will be shown below Toolbar
*/
@Composable
abstract fun Content()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
hideToolbar()
(requireActivity() as? MainActivity)?.hideStatusBarBackground()
return ComposeView(requireContext()).apply {
StatusBarUtils.getStatusBarHeight(this) { statusBarHeight ->
setContent {
var title = ""
titleRes?.let { title = getString(it) }
titleText?.let { title = it }
FocusTheme {
Scaffold {
Column {
CompositionLocalProvider {
TopAppBar(
title = {
Text(
text = title,
color = focusColors.toolbarColor,
)
},
contentPadding = rememberInsetsPaddingValues(
insets = LocalWindowInsets.current.statusBars,
additionalTop = LocalDensity.current.run {
(statusBarHeight - LocalWindowInsets.current.statusBars.top)
.toDp()
},
),
navigationIcon = {
IconButton(
onClick = onNavigateUp(),
) {
Icon(
painterResource(id = R.drawable.mozac_ic_back),
stringResource(R.string.go_back),
tint = focusColors.toolbarColor,
)
}
},
backgroundColor = colorResource(R.color.settings_background),
)
}
[email protected]()
}
}
}
}
}
isTransitionGroup = true
}
}
}
| mpl-2.0 | 031b682eebb321d09b819e2495f7feb8 | 40.391667 | 108 | 0.520435 | 6.154895 | false | false | false | false |
sys1yagi/goat-reader-2-android-prototype | app/src/main/kotlin/com/sys1yagi/goatreader/models/Item.kt | 1 | 1824 | package com.sys1yagi.goatreader.models
import com.activeandroid.annotation.Table
import com.activeandroid.Model
import com.activeandroid.annotation.Column
import java.util.Date
Table(name = Item.TABLE_NAME)
public class Item() : Model() {
class object {
val TABLE_NAME = "Items"
val FEED_ID = "feed_id"
val TITLE = "title"
val DESCRIPTION = "description"
val LINK = "link"
val IMAGE_LINK = "image_link"
val CREATED_AT = "creted_at"
val IS_READ = "is_read"
val IS_FAV = "is_fav"
val IS_BAD = "is_bad"
val TAG_IDS = "tag_ids"
fun create(feedId: Long, title: String, description: String, link: String, imageLink: String?): Item {
val date = Date()
val item: Item = Item()
item.feedId = feedId
item.title = title
item.description = description
item.link = link
item.imageLink = imageLink
item.createdAt = date
item.isRead = false
item.isFav = false
item.isBad = false
item.tagIds = null
return item
}
}
Column(name = FEED_ID)
var feedId: Long? = null
Column(name = TITLE)
var title: String? = null
Column(name = DESCRIPTION)
var description: String? = null
Column(name = LINK, unique = true, onUniqueConflict = Column.ConflictAction.IGNORE)
var link: String? = null
Column(name = IMAGE_LINK)
var imageLink: String? = null
Column(name = CREATED_AT)
var createdAt: Date? = null
Column(name = IS_READ)
var isRead: Boolean? = null
Column(name = IS_FAV)
var isFav: Boolean? = null
Column(name = IS_BAD)
var isBad: Boolean? = null
Column(name = TAG_IDS)
var tagIds: String? = null
}
| apache-2.0 | 10714e6b9ece1acc22850de5802f4983 | 29.915254 | 110 | 0.588816 | 3.848101 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/conversations/ConversationMembersEntity.kt | 1 | 670 | package com.waz.zclient.storage.db.conversations
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
@Entity(
tableName = "ConversationMembers",
primaryKeys = ["user_id", "conv_id"],
indices = [
Index(name = "ConversationMembers_conv", value = ["conv_id"]),
Index(name = "ConversationMembers_userid", value = ["user_id"])
]
)
data class ConversationMembersEntity(
@ColumnInfo(name = "user_id", defaultValue = "")
val userId: String,
@ColumnInfo(name = "conv_id", defaultValue = "")
val conversationId: String,
@ColumnInfo(name = "role", defaultValue = "")
val role: String
)
| gpl-3.0 | aa485d5821d639701b77a631a1fae49c | 26.916667 | 71 | 0.668657 | 3.941176 | false | false | false | false |
square/leakcanary | shark-android/src/main/java/shark/AndroidMetadataExtractor.kt | 2 | 4935 | package shark
import shark.GcRoot.ThreadObject
import shark.HeapObject.HeapClass
import shark.HeapObject.HeapInstance
import shark.HeapObject.HeapObjectArray
import shark.HeapObject.HeapPrimitiveArray
import shark.internal.friendly.mapNativeSizes
object AndroidMetadataExtractor : MetadataExtractor {
override fun extractMetadata(graph: HeapGraph): Map<String, String> {
val metadata = mutableMapOf<String, String>()
val build = AndroidBuildMirror.fromHeapGraph(graph)
metadata["Build.VERSION.SDK_INT"] = build.sdkInt.toString()
metadata["Build.MANUFACTURER"] = build.manufacturer
metadata["LeakCanary version"] = readLeakCanaryVersion(graph)
metadata["App process name"] = readProcessName(graph)
metadata["Class count"] = graph.classCount.toString()
metadata["Instance count"] = graph.instanceCount.toString()
metadata["Primitive array count"] = graph.primitiveArrayCount.toString()
metadata["Object array count"] = graph.objectArrayCount.toString()
metadata["Thread count"] = readThreadCount(graph).toString()
metadata["Heap total bytes"] = readHeapTotalBytes(graph).toString()
metadata.putBitmaps(graph)
metadata.putDbLabels(graph)
return metadata
}
private fun readHeapTotalBytes(graph: HeapGraph): Int {
return graph.objects.sumBy { heapObject ->
when(heapObject) {
is HeapInstance -> {
heapObject.byteSize
}
// This is probably way off but is a cheap approximation.
is HeapClass -> heapObject.recordSize
is HeapObjectArray -> heapObject.byteSize
is HeapPrimitiveArray -> heapObject.byteSize
}
}
}
private fun MutableMap<String, String>.putBitmaps(
graph: HeapGraph,
) {
val bitmapClass = graph.findClassByName("android.graphics.Bitmap") ?: return
val maxDisplayPixels =
graph.findClassByName("android.util.DisplayMetrics")?.directInstances?.map { instance ->
val width = instance["android.util.DisplayMetrics", "widthPixels"]?.value?.asInt ?: 0
val height = instance["android.util.DisplayMetrics", "heightPixels"]?.value?.asInt ?: 0
width * height
}?.max() ?: 0
val maxDisplayPixelsWithThreshold = (maxDisplayPixels * 1.1).toInt()
val sizeMap = graph.mapNativeSizes()
var sizeSum = 0
var count = 0
var largeBitmapCount = 0
var largeBitmapSizeSum = 0
bitmapClass.instances.forEach { bitmap ->
val width = bitmap["android.graphics.Bitmap", "mWidth"]?.value?.asInt ?: 0
val height = bitmap["android.graphics.Bitmap", "mHeight"]?.value?.asInt ?: 0
val size = sizeMap[bitmap.objectId] ?: 0
count++
sizeSum += size
if (maxDisplayPixelsWithThreshold > 0 && width * height > maxDisplayPixelsWithThreshold) {
largeBitmapCount++
largeBitmapSizeSum += size
}
}
this["Bitmap count"] = count.toString()
this["Bitmap total bytes"] = sizeSum.toString()
this["Large bitmap count"] = largeBitmapCount.toString()
this["Large bitmap total bytes"] = largeBitmapSizeSum.toString()
}
private fun readThreadCount(graph: HeapGraph): Int {
return graph.gcRoots.filterIsInstance<ThreadObject>().map { it.id }.toSet().size
}
private fun readLeakCanaryVersion(graph: HeapGraph): String {
val versionHolderClass = graph.findClassByName("leakcanary.internal.InternalLeakCanary")
return versionHolderClass?.get("version")?.value?.readAsJavaString() ?: "Unknown"
}
private fun readProcessName(graph: HeapGraph): String {
val activityThread = graph.findClassByName("android.app.ActivityThread")
?.get("sCurrentActivityThread")
?.valueAsInstance
val appBindData = activityThread?.get("android.app.ActivityThread", "mBoundApplication")
?.valueAsInstance
val appInfo = appBindData?.get("android.app.ActivityThread\$AppBindData", "appInfo")
?.valueAsInstance
return appInfo?.get(
"android.content.pm.ApplicationInfo", "processName"
)?.valueAsInstance?.readAsJavaString() ?: "Unknown"
}
private fun MutableMap<String, String>.putDbLabels(graph: HeapGraph) {
val dbClass = graph.findClassByName("android.database.sqlite.SQLiteDatabase") ?: return
val openDbLabels = dbClass.instances.mapNotNull { instance ->
val config =
instance["android.database.sqlite.SQLiteDatabase", "mConfigurationLocked"]?.valueAsInstance
?: return@mapNotNull null
val label =
config["android.database.sqlite.SQLiteDatabaseConfiguration", "label"]?.value?.readAsJavaString()
?: return@mapNotNull null
val open =
instance["android.database.sqlite.SQLiteDatabase", "mConnectionPoolLocked"]?.value?.isNonNullReference
?: return@mapNotNull null
label to open
}
openDbLabels.forEachIndexed { index, (label, open) ->
this["Db ${index + 1}"] = (if (open) "open " else "closed ") + label
}
}
}
| apache-2.0 | 59fbc4c77d487cb77c688e05abf06321 | 37.858268 | 110 | 0.701114 | 4.433962 | false | false | false | false |
square/leakcanary | leakcanary-android-instrumentation/src/androidTest/java/leakcanary/Profiler.kt | 2 | 3868 | package leakcanary
import android.os.Debug
import shark.SharkLog
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Helper class for working with Android Studio's Profiler
*/
internal object Profiler {
private const val SLEEP_TIME_MILLIS = 1000L
private const val SAMPLING_THREAD_NAME = "Sampling Profiler"
/**
* Wait until Profiler is attached and CPU Sampling is started.
* Calling this on main thread can lead to ANR if you try to interact with UI while it's waiting for
* profiler.
* Note: only works with 'Sample Java Methods' profiling, won't work with 'Trace Java Methods'!
*/
fun waitForSamplingStart() {
SharkLog.d { "Waiting for sampling to start. Go to Profiler -> CPU -> Record" }
sleepUntil { samplingThreadExists() }
Thread.sleep(SLEEP_TIME_MILLIS) //Wait a bit more to ensure profiler started sampling
SharkLog.d { "Sampling started! Proceeding..." }
}
/**
* Wait until CPU Sampling stops.
* Calling this on main thread can lead to ANR if you try to interact with UI while it's waiting for
* profiler.
*/
fun waitForSamplingStop() {
SharkLog.d { "Waiting for sampling to stop. Go to Profiler -> CPU -> Stop recording" }
sleepUntil { !samplingThreadExists() }
SharkLog.d { "Sampling stopped! Proceeding..." }
}
/**
* Executes the given function [block] with CPU sampling via Profiler and returns the result of
* the function execution.
* First, it awaits for Profiler to be attached at start of sampling, then executes [block]
* and finally waits for sampling to stop. See [waitForSamplingStart] and [waitForSamplingStop]
* for more details.
*/
fun <T> runWithProfilerSampling(block: () -> T): T {
waitForSamplingStart()
val result = block()
waitForSamplingStop()
return result
}
private const val TRACES_FOLDER = "/sdcard/traces/"
private const val TRACE_NAME_PATTERN = "yyyy-MM-dd_HH-mm-ss_SSS'.trace'"
private const val BUFFER_SIZE = 50 * 1024 * 1024
private const val TRACE_INTERVAL_US = 1000
/**
* Executes the given function [block] with method tracing to SD card and returns the result of
* the function execution.
* Tracing is performed with [Debug.startMethodTracingSampling] which uses sampling with
* [TRACE_INTERVAL_US] microseconds interval.
* Trace file will be stored in [TRACES_FOLDER] and can be pulled via `adb pull` command.
* See Logcat output for an exact command to retrieve trace file
*/
fun <T> runWithMethodTracing(block: () -> T): T {
java.io.File(TRACES_FOLDER).mkdirs()
val fileName = SimpleDateFormat(TRACE_NAME_PATTERN, Locale.US).format(Date())
Debug.startMethodTracingSampling(
"$TRACES_FOLDER$fileName",
BUFFER_SIZE,
TRACE_INTERVAL_US
)
val result = block()
Debug.stopMethodTracing()
SharkLog.d { "Method tracing complete! Run the following command to retrieve the trace:" }
SharkLog.d { "adb pull $TRACES_FOLDER$fileName ~/Downloads/ " }
return result
}
private inline fun sleepUntil(condition: () -> Boolean) {
while (true) {
if (condition()) return else Thread.sleep(SLEEP_TIME_MILLIS)
}
}
private fun samplingThreadExists() = findThread(SAMPLING_THREAD_NAME) != null
/**
* Utility to get thread by its name; in case of multiple matches first one will be returned.
*/
private fun findThread(threadName: String): Thread? {
// Based on https://stackoverflow.com/a/1323480
var rootGroup = Thread.currentThread().threadGroup
while (rootGroup.parent != null) rootGroup = rootGroup.parent
var threads = arrayOfNulls<Thread>(rootGroup.activeCount())
while (rootGroup.enumerate(threads, true) == threads.size) {
threads = arrayOfNulls(threads.size * 2)
}
return threads.firstOrNull { it?.name == threadName }
}
} | apache-2.0 | 6fb7954ac0579326782a3dde0e0bbd8b | 36.201923 | 102 | 0.701138 | 4.058762 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2021/Day10.kt | 1 | 1355 | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.util.ArrayDeque
/**
* --- Day 10: Syntax Scoring ---
* https://adventofcode.com/2021/day/10
*/
class Day10 : Solver {
override fun solve(lines: List<String>): Result {
val result = lines.map { scanLine(it) }
val partA = result.map { it.first }.sum()
val bLines = result.map { it.second }.filter { it != 0L }.sorted().toList()
val partB = bLines[(bLines.size / 2)]
return Result("$partA", "$partB")
}
private fun scanLine(line: String): Pair<Long, Long> {
val stack = ArrayDeque<Char>()
for (ch in line) {
if (ch == ']') {
if (stack.last() == '[') stack.removeLast() else return Pair(57, 0)
} else if (ch == ')') {
if (stack.last() == '(') stack.removeLast() else return Pair(3, 0)
} else if (ch == '}') {
if (stack.last() == '{') stack.removeLast() else return Pair(1197, 0)
} else if (ch == '>') {
if (stack.last() == '<') stack.removeLast() else return Pair(25137, 0)
} else {
stack.add(ch)
}
}
var result = 0L
for (ch in stack.reversed()) {
result *= 5
if (ch == '(') result += 1
if (ch == '[') result += 2
if (ch == '{') result += 3
if (ch == '<') result += 4
}
return Pair(0, result)
}
} | apache-2.0 | 6060f1c2223fccd48f22a9d9c27ceab2 | 29.133333 | 79 | 0.539483 | 3.296837 | false | false | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/rule/ScheduleRuleSchedule.kt | 1 | 7572 | package me.camsteffen.polite.rule
import android.content.Context
import android.content.res.Resources
import androidx.core.os.ConfigurationCompat.getLocales
import me.camsteffen.polite.R
import me.camsteffen.polite.util.daysAfter
import org.threeten.bp.DayOfWeek
import org.threeten.bp.Duration
import org.threeten.bp.Instant
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import org.threeten.bp.ZoneId
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.FormatStyle
import org.threeten.bp.format.TextStyle
import org.threeten.bp.temporal.TemporalAdjusters
import org.threeten.bp.temporal.WeekFields
import java.util.EnumSet
interface HasScheduleRuleTimes {
val beginTime: LocalTime
val endTime: LocalTime
val isOvernight: Boolean get() = beginTime >= endTime
/**
* Returns the duration of events in this schedule (in the absence of a timezone offset change)
*/
fun eventDuration(): Duration = Duration.between(beginTime, endTime)
.run { if (isOvernight) plusDays(1) else this }
fun eventDurationDisplay(resources: Resources): String {
var duration = eventDuration()
if (duration.isNegative) {
duration = duration.plusDays(1)
}
val minutes = duration.toMinutes()
return if (minutes < 60) {
resources.getString(R.string.duration_format_minutes, minutes)
} else {
resources.getString(R.string.duration_format, duration.toHours(), minutes % 60)
}
}
}
class ScheduleRuleTimes(
override val beginTime: LocalTime,
override val endTime: LocalTime
) : HasScheduleRuleTimes
/**
* A ScheduleRuleSchedule defines when a Schedule Rule is active based on a begin time, end time
* and a set of days of the week.
*
* Events begin on every day in [daysOfWeek] at [beginTime].
* Events end at the soonest occurrence of [endTime], which may be on the following day.
*/
data class ScheduleRuleSchedule(
override val beginTime: LocalTime,
override val endTime: LocalTime,
val daysOfWeek: Set<DayOfWeek>
) : HasScheduleRuleTimes {
constructor(
beginHour: Int,
beginMinute: Int,
endHour: Int,
endMinute: Int,
vararg days: DayOfWeek
) : this(
beginTime = LocalTime.of(beginHour, beginMinute),
endTime = LocalTime.of(endHour, endMinute),
daysOfWeek = if (days.isEmpty()) emptySet() else EnumSet.copyOf(days.asList())
)
data class Event(val begin: Instant, val end: Instant)
data class LocalEvent(val begin: LocalDateTime, val end: LocalDateTime) {
fun atZone(zone: ZoneId) = Event(
begin.atZone(zone).toInstant(),
end.atZone(zone).toInstant()
)
}
/**
* Finds an event occurrence that overlaps the specified date/time or null if none exists
*/
fun eventAt(target: LocalDateTime): LocalEvent? {
val date = target.toLocalDate()
val time = target.toLocalTime()
val dayOfWeek = target.dayOfWeek
if (isOvernight) {
if (daysOfWeek.contains(dayOfWeek) && time >= beginTime) {
return LocalEvent(date.atTime(beginTime), date.plusDays(1).atTime(endTime))
} else if (daysOfWeek.contains(dayOfWeek - 1) && time < endTime) {
return LocalEvent(date.minusDays(1).atTime(beginTime), date.atTime(endTime))
}
} else if (daysOfWeek.contains(dayOfWeek) && time >= beginTime && time < endTime) {
return LocalEvent(date.atTime(beginTime), date.atTime(endTime))
}
return null
}
/**
* Finds the first event that begins after the specified date/time
* or null if this schedule has no days
*/
fun firstEventAfter(target: LocalDateTime): LocalEvent? {
val soonestDate = target.toLocalDate().run {
if (target.toLocalTime() <= beginTime) this else plusDays(1)
}
val soonestDay = soonestDate.dayOfWeek
val dayOfWeek = daysOfWeek.asSequence().minBy { it.daysAfter(soonestDay) }
?: return null
val beginDate = soonestDate.with(TemporalAdjusters.nextOrSame(dayOfWeek))
val endDate = if (isOvernight) beginDate.plusDays(1) else beginDate
return LocalEvent(beginDate.atTime(beginTime), endDate.atTime(endTime))
}
/**
* Generates a lazy sequence of events that occur in the specified time range.
* Events that are partially in the time range are included.
*/
fun localEventSequence(begin: LocalDateTime, end: LocalDateTime): Sequence<LocalEvent> {
if (daysOfWeek.isEmpty()) return emptySequence()
var adjust = 0L
if (begin.toLocalTime() >= endTime) adjust++
if (isOvernight) adjust--
val soonestDate = begin.toLocalDate().plusDays(adjust)
val soonestDayOfWeek = soonestDate.dayOfWeek
val sortedDaysOfWeek = daysOfWeek.sortedBy { it.daysAfter(soonestDayOfWeek) }
var beginDate = soonestDate.minusDays(1)
return sequence {
for (dayOfWeek in generateSequence { sortedDaysOfWeek }.flatten()) {
beginDate = beginDate.with(TemporalAdjusters.next(dayOfWeek))
val beginDateTime = beginDate.atTime(beginTime)
if (beginDateTime >= end) return@sequence
val endDate = if (isOvernight) beginDate.plusDays(1) else beginDate
yield(LocalEvent(beginDateTime, endDate.atTime(endTime)))
}
}
}
/**
* Same as [localEventSequence] but with event times adjusted for the specified time zone
*/
fun eventSequence(begin: LocalDateTime, end: LocalDateTime, zone: ZoneId): Sequence<Event> {
return localEventSequence(begin, end)
.map { event -> event.atZone(zone) }
}
fun summary(context: Context): String {
val resources = context.resources
val locale = getLocales(resources.configuration)[0]
val firstDayOfWeek = WeekFields.of(locale).firstDayOfWeek
val timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale)
fun DayOfWeek.shortName() = getDisplayName(TextStyle.SHORT, locale)
fun DayRange.displayName(): String {
val separator = when (length) {
7 -> return resources.getString(R.string.every_day)
1 -> return start.shortName()
2 -> ", "
else -> " - "
}
val end = start + (length - 1).toLong()
return start.shortName() + separator + end.shortName()
}
val daysString = daysOfWeek.toDayRanges(firstDayOfWeek)
.joinToString(transform = DayRange::displayName)
return "$daysString ${beginTime.format(timeFormatter)} - ${endTime.format(timeFormatter)}"
}
}
private class DayRange(val start: DayOfWeek, val length: Int)
/** Returns a list of all day ranges within a set of days ordered by the number of
* days after the [firstDayOfWeek] */
private fun Set<DayOfWeek>.toDayRanges(firstDayOfWeek: DayOfWeek): Sequence<DayRange> {
return sequence {
val days = sortedBy { it.daysAfter(firstDayOfWeek) }
var begin = 0
while (begin < days.size) {
var end = (begin + 1 until days.size).asSequence()
.takeWhile { i -> days[i] == days[i - 1] + 1 }
.lastOrNull() ?: begin
end++
yield(DayRange(days[begin], end - begin))
begin = end
}
}
}
| mpl-2.0 | 1351da452e998519fcd7e51f196648bc | 37.632653 | 99 | 0.65346 | 4.422897 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/kotlinpermissions/src/main/java/io/vrinda/kotlinpermissions/DeviceInfo.kt | 1 | 47050 | package io.vrinda.kotlinpermissions
import android.Manifest
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.webkit.WebView
import java.net.Inet4Address
import java.net.NetworkInterface
import java.util.*
public class DeviceInfo {
companion object {
@JvmStatic fun getAndroidID(context: Context): String? {
var result: String? = null
try {
result = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
} catch (exception: Exception) {
exception.printStackTrace();
}
return result
}
/**
* Gets model.
* @return the model
*/
@JvmStatic fun getModel(): String {
var result: String? = null
try {
result = Build.MODEL
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
@JvmStatic fun handleIllegalCharacterInResult(result: String): String {
var result = result
if (result.indexOf(" ") > 0) {
result = result.replace(" ".toRegex(), "_")
}
return result
}
/**
* Gets build brand.
* @return the build brand
*/
@JvmStatic fun getBuildBrand(): String {
var result: String? = null
try {
result = Build.BRAND
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets build host.
* @return the build host
*/
@JvmStatic fun getBuildHost(): String {
var result: String? = null
try {
result = Build.HOST
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets build tags.
* @return the build tags
*/
@JvmStatic fun getBuildTags(): String {
var result: String? = null
try {
result = Build.TAGS
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets build time.
* @return the build time
*/
@JvmStatic fun getBuildTime(): Long {
var result: Long = 0
try {
result = Build.TIME
} catch (e: Exception) {
e.printStackTrace()
}
return result.toLong()
}
/**
* Gets build user.
* @return the build user
*/
@JvmStatic fun getBuildUser(): String {
var result: String? = null
try {
result = Build.USER
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
///////////////////////
@JvmStatic fun getBuildVersionRelease(): String {
var result: String? = null
try {
result = Build.VERSION.RELEASE
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets screen display id.
* @return the screen display id
*/
//TODO getScreenDisplayID
@JvmStatic fun getScreenDisplayID(context: Context): String {
var result: String? = null
try {
val display = context.getSystemService(Context.WINDOW_SERVICE) as Display
result = display.displayId.toString()
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets build version codename.
* @return the build version codename
*/
@JvmStatic fun getBuildVersionCodename(): String {
var result: String? = null
try {
result = Build.VERSION.CODENAME
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets build version incremental.
* @return the build version incremental
*/
@JvmStatic fun getBuildVersionIncremental(): String {
var result: String? = null
try {
result = Build.VERSION.INCREMENTAL
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets build version sdk.
* @return the build version sdk
*/
@JvmStatic fun getBuildVersionSDK(): Int {
var result = 0
try {
result = Build.VERSION.SDK_INT
} catch (e: Exception) {
e.printStackTrace()
}
return result
}
/**
* Gets build id.
* @return the build id
*/
@JvmStatic fun getBuildID(): String {
var result: String? = null
try {
result = Build.ID
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Get supported abis string [ ].
* @return the string [ ]
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@JvmStatic fun getSupportedABIS(): Array<String> {
var result: Array<String>? = arrayOf("-")
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
result = Build.SUPPORTED_ABIS
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.size == 0) {
result = arrayOf("-")
}
return result
}
/**
* Gets string supported abis.
* @return the string supported abis
*/
//TODO
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@JvmStatic fun getStringSupportedABIS(): String {
var result: String? = null
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val supportedABIS = Build.SUPPORTED_ABIS
val supportedABIString = StringBuilder()
if (supportedABIS.size > 0) {
for (abis in supportedABIS) {
supportedABIString.append(abis).append("_")
}
supportedABIString.deleteCharAt(supportedABIString.lastIndexOf("_"))
} else {
supportedABIString.append("")
}
result = supportedABIString.toString()
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets string supported 32 bit abis.
* @return the string supported 32 bit abis
*/
@JvmStatic fun getStringSupported32bitABIS(): String {
var result: String? = null
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val supportedABIS = Build.SUPPORTED_32_BIT_ABIS
val supportedABIString = StringBuilder()
if (supportedABIS.size > 0) {
for (abis in supportedABIS) {
supportedABIString.append(abis).append("_")
}
supportedABIString.deleteCharAt(supportedABIString.lastIndexOf("_"))
} else {
supportedABIString.append("")
}
result = supportedABIString.toString()
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets string supported 64 bit abis.
* @return the string supported 64 bit abis
*/
@JvmStatic @TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun getStringSupported64bitABIS(): String {
var result: String? = null
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val supportedABIS = Build.SUPPORTED_64_BIT_ABIS
val supportedABIString = StringBuilder()
if (supportedABIS.size > 0) {
for (abis in supportedABIS) {
supportedABIString.append(abis).append("_")
}
supportedABIString.deleteCharAt(supportedABIString.lastIndexOf("_"))
} else {
supportedABIString.append("")
}
result = supportedABIString.toString()
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult("")
}
/**
* Get supported 32 bit abis string [ ].
* @return the string [ ]
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@JvmStatic fun getSupported32bitABIS(): Array<String> {
var result: Array<String>? = arrayOf("-")
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
result = Build.SUPPORTED_32_BIT_ABIS
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.size == 0) {
result = arrayOf("-")
}
return result
}
/**
* Get supported 64 bit abis string [ ].
* @return the string [ ]
*/
@JvmStatic @TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun getSupported64bitABIS(): Array<String> {
var result: Array<String>? = arrayOf("-")
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
result = Build.SUPPORTED_64_BIT_ABIS
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.size == 0) {
result = arrayOf("-")
}
return result
}
/**
* Gets manufacturer.
* @return the manufacturer
*/
@JvmStatic fun getManufacturer(): String {
var result: String? = null
try {
result = Build.MANUFACTURER
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets resolution.
* @return the resolution
*/
//TODO
@JvmStatic fun getResolution(context: Context): String {
var result: String = ""
try {
val display = context.getSystemService(Context.WINDOW_SERVICE) as Display
val metrics = DisplayMetrics()
display.getMetrics(metrics)
result = "${metrics.heightPixels} x ${metrics.widthPixels}"
} catch (e: Exception) {
e.printStackTrace()
}
if (result.length == 0) {
result = ""
}
return result
}
/**
* Gets carrier.
* @return the carrier
*/
//TODO
@JvmStatic fun getCarrier(context: Context): String {
var result: String = ""
try {
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
result = tm.getNetworkOperatorName().toLowerCase(Locale.getDefault())
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result.length == 0) {
result = ""
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets device.
* @return the device
*/
@JvmStatic fun getDevice(): String {
var result: String? = null
try {
result = Build.DEVICE
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets bootloader.
* @return the bootloader
*/
@JvmStatic fun getBootloader(): String {
var result: String? = null
try {
result = Build.BOOTLOADER
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets board.
* @return the board
*/
@JvmStatic fun getBoard(): String {
var result: String? = ""
try {
result = Build.BOARD
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets display version.
* @return the display version
*/
@JvmStatic fun getDisplayVersion(): String {
var result: String? = null
try {
result = Build.DISPLAY
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets language.
* @return the language
*/
@JvmStatic fun getLanguage(): String {
var result: String? = null
try {
result = Locale.getDefault().language
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets country.
* @return the country
*/
@JvmStatic fun getCountry(context: Context): String {
var result: String? = ""
try {
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
result = tm.getSimCountryIso().toLowerCase(Locale.getDefault())
} else {
val locale = Locale.getDefault()
result = locale.country.toLowerCase(locale)
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result?.length == 0) {
result = ""
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets network type.
* @return the network type
*/
//TODO
@SuppressLint("ServiceCast")
@JvmStatic fun getNetworkType(context: Context): String {
val networkStatePermission = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)
var result: String? = null
if (networkStatePermission == PackageManager.PERMISSION_GRANTED) {
try {
val activeNetwork = context.getSystemService(Context.CONNECTIVITY_SERVICE) as NetworkInfo
if (activeNetwork == null) {
result = "Unknown"
} else if (activeNetwork.type == ConnectivityManager.TYPE_WIFI || activeNetwork.type == ConnectivityManager.TYPE_WIMAX) {
result = "Wifi/WifiMax"
} else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) {
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (tm.simState == TelephonyManager.SIM_STATE_READY) {
when (tm.networkType) {
// Unknown
TelephonyManager.NETWORK_TYPE_UNKNOWN -> result = "Cellular - Unknown"
// Cellular Data–2G
TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_IDEN, TelephonyManager.NETWORK_TYPE_1xRTT -> result = "Cellular - 2G"
// Cellular Data–3G
TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_EVDO_B -> result = "Cellular - 3G"
// Cellular Data–4G
TelephonyManager.NETWORK_TYPE_LTE -> result = "Cellular - 4G"
// Cellular Data–Unknown Generation
else -> result = "Cellular - Unknown Generation"
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
if (result?.length == 0) {
result = null
}
return handleIllegalCharacterInResult(result.toString())
}
/**
* Gets os codename.
* @return the os codename
*/
@JvmStatic fun getOSCodename(): String {
var codename: String? = null
when (Build.VERSION.SDK_INT) {
Build.VERSION_CODES.BASE -> codename = "First Android Version. Yay !"
Build.VERSION_CODES.BASE_1_1 -> codename = "Base Android 1.1"
Build.VERSION_CODES.CUPCAKE -> codename = "Cupcake"
Build.VERSION_CODES.DONUT -> codename = "Donut"
Build.VERSION_CODES.ECLAIR, Build.VERSION_CODES.ECLAIR_0_1, Build.VERSION_CODES.ECLAIR_MR1 ->
codename = "Eclair"
Build.VERSION_CODES.FROYO -> codename = "Froyo"
Build.VERSION_CODES.GINGERBREAD, Build.VERSION_CODES.GINGERBREAD_MR1 -> codename = "Gingerbread"
Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR1, Build.VERSION_CODES.HONEYCOMB_MR2 -> codename = "Honeycomb"
Build.VERSION_CODES.ICE_CREAM_SANDWICH, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 -> codename = "Ice Cream Sandwich"
Build.VERSION_CODES.JELLY_BEAN, Build.VERSION_CODES.JELLY_BEAN_MR1, Build.VERSION_CODES.JELLY_BEAN_MR2 -> codename = "Jelly Bean"
Build.VERSION_CODES.KITKAT -> codename = "Kitkat"
Build.VERSION_CODES.KITKAT_WATCH -> codename = "Kitkat Watch"
Build.VERSION_CODES.LOLLIPOP, Build.VERSION_CODES.LOLLIPOP_MR1 -> codename = "Lollipop"
Build.VERSION_CODES.M -> codename = "Marshmallow"
}
return codename.toString()
}
/**
* Gets os version.
* @return the os version
*/
@JvmStatic fun getOSVersion(): String {
var result: String? = null
try {
result = Build.VERSION.RELEASE
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets wifi mac.
* @return the wifi mac
*/
@JvmStatic @SuppressWarnings("MissingPermission") fun getWifiMAC(context: Context): String {
var result: String? = null
try {
if (context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED) {
val wifiManager: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
result = wifiManager.connectionInfo.macAddress
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets imei.
* @return the imei
*/
@JvmStatic fun getIMEI(context: Context): String {
var result: String? = null
val hasReadPhoneStatePermission = context.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
try {
if (hasReadPhoneStatePermission) result = tm.getDeviceId()
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets imsi.
* @return the imsi
*/
@JvmStatic fun getIMSI(context: Context): String {
var result: String? = null
val hasReadPhoneStatePermission = context.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
try {
if (hasReadPhoneStatePermission) result = tm.getSubscriberId()
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets serial.
* @return the serial
*/
@JvmStatic fun getSerial(): String {
var result: String? = null
try {
result = Build.SERIAL
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets sim serial.
* @return the sim serial
*/
@JvmStatic fun getSIMSerial(context: Context): String {
var result: String? = null
try {
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
result = tm.getSimSerialNumber()
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets gsfid.
* @return the gsfid
*/
@JvmStatic fun getGSFID(context: Context): String? {
val URI = Uri.parse("content://com.google.android.gsf.gservices")
val ID_KEY = "android_id"
val params = arrayOf(ID_KEY)
val c = context.getContentResolver().query(URI, null, null, params, null)
if (!c.moveToFirst() || c!!.getColumnCount() < 2) {
c.close()
return null
}
try {
val gsfID = java.lang.Long.toHexString(java.lang.Long.parseLong(c.getString(1)))
c.close()
return gsfID
} catch (e: NumberFormatException) {
c.close()
return null
}
}
/**
* Gets bluetooth mac.
* @return the bluetooth mac
*/
@JvmStatic @SuppressWarnings("MissingPermission") fun getBluetoothMAC(context: Context): String {
var result: String? = null
try {
if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED) {
val bta = BluetoothAdapter.getDefaultAdapter()
result = bta.address
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets psuedo unique id.
* @return the psuedo unique id
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@JvmStatic fun getPsuedoUniqueID(): String {
// If all else fails, if the user does have lower than API 9 (lower
// than Gingerbread), has reset their phone or 'Secure.ANDROID_ID'
// returns 'null', then simply the ID returned will be solely based
// off their Android device information. This is where the collisions
// can happen.
// Try not to use DISPLAY, HOST or ID - these items could change.
// If there are collisions, there will be overlapping data
var devIDShort = "35" +
Build.BOARD.length % 10 + Build.BRAND.length % 10
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
devIDShort += Build.SUPPORTED_ABIS[0].length % 10
} else {
devIDShort += Build.CPU_ABI.length % 10
}
devIDShort += Build.DEVICE.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10
// Only devices with API >= 9 have android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// If a user upgrades software or roots their phone, there will be a duplicate entry
var serial: String
try {
serial = Build::class.java.getField("SERIAL").get(null).toString()
// Go ahead and return the serial for api => 9
return UUID(devIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
} catch (e: Exception) {
// String needs to be initialized
serial = "ESYDV000" // some value
}
// Finally, combine the values we have found by using the UUID class to create a unique identifier
return UUID(devIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
}
/**
* Gets phone no.
* @return the phone no
*/
@JvmStatic fun getPhoneNo(context: Context): String {
var result: String? = null
try {
val tm: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (tm.getLine1Number() != null) {
result = tm.getLine1Number()
if (result == "") {
result = null
}
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result?.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets product.
* @return the product
*/
@JvmStatic fun getProduct(): String {
var result: String? = null
try {
result = Build.PRODUCT
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets fingerprint.
* @return the fingerprint
*/
@JvmStatic fun getFingerprint(): String {
var result: String? = null
try {
result = Build.FINGERPRINT
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets hardware.
* @return the hardware
*/
@JvmStatic fun getHardware(): String {
var result: String? = null
try {
result = Build.HARDWARE
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets radio ver.
* @return the radio ver
*/
@JvmStatic fun getRadioVer(): String {
var result: String? = null
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
result = Build.getRadioVersion()
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets ip address.
* @param useIPv4 the use i pv 4
* *
* @return the ip address
*/
@JvmStatic fun getIPAddress(useIPv4: Boolean): String {
var result: String? = null
try {
val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
val addrs = Collections.list(intf.inetAddresses)
for (addr in addrs) {
if (!addr.isLoopbackAddress) {
val sAddr = addr.hostAddress.toUpperCase(Locale.getDefault())
val isIPv4 = addr is Inet4Address
if (useIPv4) {
if (isIPv4) result = sAddr
} else {
if (!isIPv4) {
val delim = sAddr.indexOf('%') // drop ip6 port suffix
result = if (delim < 0) sAddr else sAddr.substring(0, delim)
}
}
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets ua.
* @return the ua
*/
//TODO
@JvmStatic fun getUA(context: Context): String {
val system_ua = System.getProperty("http.agent")
var result: String? = system_ua
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
result = WebView(context).settings.userAgentString +
"__" + system_ua
} else {
result = WebView(context).settings.userAgentString +
"__" + system_ua
}
} catch (e: Exception) {
e.printStackTrace()
}
if (result!!.length < 0 || result == null) {
result = system_ua
}
return result.toString()
}
/**
* Get lat long double [ ].
* @return the double [ ]
*/
//TODO
@SuppressWarnings("MissingPermission")
@TargetApi(Build.VERSION_CODES.M)
@JvmStatic fun getLatLong(context: Context): DoubleArray {
val hasFineLocationPermission = if (context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
true
else
false
val isGPSEnabled: Boolean
val isNetworkEnabled: Boolean
val gps = DoubleArray(2)
gps[0] = 0.0
gps[1] = 0.0
if (hasFineLocationPermission) {
try {
val locationManger: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
isGPSEnabled = locationManger.isProviderEnabled(LocationManager.GPS_PROVIDER)
isNetworkEnabled = locationManger.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
var net_loc: Location? = null
var gps_loc: Location? = null
var final_loc: Location? = null
if (isGPSEnabled) {
gps_loc = locationManger.getLastKnownLocation(LocationManager.GPS_PROVIDER)
}
if (isNetworkEnabled) {
net_loc = locationManger.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
if (gps_loc != null && net_loc != null) {
if (gps_loc.accuracy >= net_loc.accuracy) {
final_loc = gps_loc
} else {
final_loc = net_loc
}
} else {
if (gps_loc != null) {
final_loc = gps_loc
} else if (net_loc != null) {
final_loc = net_loc
} else {
// GPS and Network both are null so try passive
final_loc = locationManger.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
}
}
if (final_loc != null) {
gps[0] = final_loc.latitude
gps[1] = final_loc.longitude
}
return gps
} catch (e: Exception) {
e.printStackTrace()
}
}
return gps
}
/**
* Get display xy coordinates int [ ].
* @param event the event
* *
* @return the int [ ]
*/
@JvmStatic fun getDisplayXYCoordinates(event: MotionEvent): IntArray {
val coordinates = IntArray(2)
coordinates[0] = 0
coordinates[1] = 0
try {
if (event.action == MotionEvent.ACTION_DOWN) {
coordinates[0] = event.x.toInt() // X Coordinates
coordinates[1] = event.y.toInt() // Y Coordinates
}
} catch (e: Exception) {
e.printStackTrace()
}
return coordinates
}
/**
* Gets time.
* @return the time
*/
@JvmStatic fun getTime(): Long {
return System.currentTimeMillis()
}
/**
* Gets formated time.
* @return the formated time
*/
@JvmStatic fun getFormatedTime(): String {
val cal = Calendar.getInstance()
cal.timeInMillis = System.currentTimeMillis()
return "${cal.get(Calendar.HOUR_OF_DAY)} : ${cal.get(Calendar.MINUTE)} :${cal.get(Calendar.SECOND)}"
/* return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(
Calendar.SECOND)*/
}
/**
* Gets app name.
* @return the app name
*/
@JvmStatic fun getAppName(context: Context): String {
val result: String
val pm = context.getPackageManager()
var ai: ApplicationInfo?
try {
ai = pm.getApplicationInfo(context.getPackageName(), 0)
} catch (e: PackageManager.NameNotFoundException) {
ai = null
e.printStackTrace()
}
result = (if (ai != null) pm.getApplicationLabel(ai) else null) as String
return result
}
/**
* Gets app version.
* @return the app version
*/
@JvmStatic fun getAppVersion(context: Context): String {
var result: String? = null
try {
result = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets app version code.
* @return the app version code
*/
@JvmStatic fun getAppVersionCode(context: Context): String {
var result: String? = null
try {
result = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode.toString()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
if (result?.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets activity name.
* @return the activity name
*/
@JvmStatic fun getActivityName(context: Context): String {
var result: String? = null
try {
result = context.javaClass.getSimpleName()
} catch (e: Exception) {
e.printStackTrace()
}
if (result?.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets package name.
* @return the package name
*/
@JvmStatic fun getPackageName(context: Context): String {
var result: String? = null
try {
result = context.getPackageName()
} catch (e: Exception) {
e.printStackTrace()
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets store.
* @return the store
*/
@JvmStatic fun getStore(context: Context): String {
var result: String? = null
if (Build.VERSION.SDK_INT >= 3) {
try {
result = context.getPackageManager().getInstallerPackageName(context.getPackageName())
} catch (e: Exception) {
Log.i("TAG", "Can't get Installer package")
}
}
if (result == null || result.length == 0) {
result = null
}
return result.toString()
}
/**
* Gets density.
* @return the density
*/
@JvmStatic fun getDensity(context: Context): String {
var densityStr: String? = null
val density = context.getResources().getDisplayMetrics().densityDpi
when (density) {
DisplayMetrics.DENSITY_LOW -> densityStr = "LDPI"
DisplayMetrics.DENSITY_MEDIUM -> densityStr = "MDPI"
DisplayMetrics.DENSITY_TV -> densityStr = "TVDPI"
DisplayMetrics.DENSITY_HIGH -> densityStr = "HDPI"
DisplayMetrics.DENSITY_XHIGH -> densityStr = "XHDPI"
DisplayMetrics.DENSITY_400 -> densityStr = "XMHDPI"
DisplayMetrics.DENSITY_XXHIGH -> densityStr = "XXHDPI"
DisplayMetrics.DENSITY_XXXHIGH -> densityStr = "XXXHDPI"
}
return densityStr.toString()
}
/**
* Get accounts string [ ].
* @return the string [ ]
*/
@JvmStatic @SuppressWarnings("MissingPermission") fun getAccounts(context: Context): Array<String?>? {
try {
if (context.checkCallingOrSelfPermission(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {
val accounts = AccountManager.get(context).getAccountsByType("com.google")
val result = arrayOfNulls<String>(accounts.size)
for (i in accounts.indices) {
result[i] = accounts[i].name
}
return result
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
/**
* Is network available boolean.
* @return the boolean
*/
//TODO
@JvmStatic fun isNetworkAvailable(context: Context): Boolean {
if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED && context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED) {
val netInfo: NetworkInfo = context.getSystemService(Context.CONNECTIVITY_SERVICE) as NetworkInfo
return netInfo != null && netInfo.isConnected
}
return false
}
/**
* Is running on emulator boolean.
* @return the boolean
*/
@JvmStatic fun isRunningOnEmulator(): Boolean {
return Build.BRAND.contains("generic")
|| Build.DEVICE.contains("generic")
|| Build.PRODUCT.contains("sdk")
|| Build.HARDWARE.contains("goldfish")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.PRODUCT.contains("vbox86p")
|| Build.DEVICE.contains("vbox86p")
|| Build.HARDWARE.contains("vbox86")
}
}
/**
* Gets android ad id.
*
* @param callback the callback
*/
/*public void getAndroidAdId(final AdIdentifierCallback callback) {
new Thread(new Runnable() {
@Override public void run() {
AdvertisingIdClient.Info adInfo;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
String androidAdId = adInfo.getId();
boolean adDoNotTrack = adInfo.isLimitAdTrackingEnabled();
if (androidAdId == null) {
androidAdId = "NA";
}
//Send Data to callback
callback.onSuccess(androidAdId, (adDoNotTrack && adDoNotTrack));
} catch (IOException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
// Google Play services is not available entirely.
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
}
}
}).start();
}*/
/**
* The interface Ad identifier callback.
*/
interface AdIdentifierCallback {
/**
* On success.
* @param adIdentifier the ad identifier
* *
* @param adDonotTrack the ad donot track
*/
fun onSuccess(adIdentifier: String, adDonotTrack: Boolean)
}
} | mit | 8e601c2a2dc0020e4ffa9eab0765950b | 31.736952 | 355 | 0.485439 | 5.236198 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/shared/src/main/java/com/supercilex/robotscouter/shared/Ui.kt | 1 | 3259 | package com.supercilex.robotscouter.shared
import android.app.Activity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.NavUtils
import androidx.core.app.TaskStackBuilder
import androidx.core.provider.FontRequest
import androidx.emoji.text.EmojiCompat
import androidx.emoji.text.FontRequestEmojiCompatConfig
import com.firebase.ui.auth.AuthUI
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidUserException
import com.supercilex.robotscouter.core.RobotScouter
import com.supercilex.robotscouter.core.data.ACTION_FROM_DEEP_LINK
import com.supercilex.robotscouter.core.data.ChangeEventListenerBase
import com.supercilex.robotscouter.core.data.cleanup
import com.supercilex.robotscouter.core.data.nightMode
import com.supercilex.robotscouter.core.data.prefs
import com.supercilex.robotscouter.core.logBreadcrumb
import com.supercilex.robotscouter.core.longToast
import com.supercilex.robotscouter.shared.client.idpSignOut
import com.supercilex.robotscouter.shared.client.onSignedIn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
fun initUi() {
GlobalScope.launch {
// Disk I/O sometimes occurs in these
AuthUI.getInstance()
GoogleSignIn.getLastSignedInAccount(RobotScouter)
onSignedIn()
}
FirebaseAuth.getInstance().addAuthStateListener {
it.currentUser?.reload()?.addOnFailureListener f@{
if (
it !is FirebaseAuthInvalidUserException ||
it.errorCode != "ERROR_USER_NOT_FOUND" && it.errorCode != "ERROR_USER_DISABLED"
) return@f
logBreadcrumb("User deleted or disabled. Re-initializing Robot Scouter.")
GlobalScope.launch {
cleanup()
idpSignOut()
onSignedIn()
Dispatchers.Main {
longToast("User account deleted due to inactivity. Starting a fresh session.")
}
}
}
}
AppCompatDelegate.setDefaultNightMode(nightMode)
prefs.addChangeEventListener(object : ChangeEventListenerBase {
override fun onDataChanged() {
AppCompatDelegate.setDefaultNightMode(nightMode)
}
})
EmojiCompat.init(FontRequestEmojiCompatConfig(
RobotScouter,
FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Noto Color Emoji Compat",
R.array.com_google_android_gms_fonts_certs)).registerInitCallback(
object : EmojiCompat.InitCallback() {
override fun onFailed(t: Throwable?) =
logBreadcrumb("EmojiCompat failed to initialize with error: $t")
}))
}
fun Activity.handleUpNavigation() = if (
NavUtils.shouldUpRecreateTask(this, checkNotNull(NavUtils.getParentActivityIntent(this))) ||
intent.action == ACTION_FROM_DEEP_LINK
) {
TaskStackBuilder.create(this).addParentStack(this).startActivities()
finish()
} else {
NavUtils.navigateUpFromSameTask(this)
}
| gpl-3.0 | 83933b9c190421ff4f613dd58080355a | 37.341176 | 98 | 0.705124 | 4.821006 | false | false | false | false |
dragbone/slacking-pizzabot | src/main/kotlin/com/dragbone/slackbot/SlackBot.kt | 1 | 4339 | package com.dragbone.slackbot
import com.dragbone.IDisposeable
import com.dragbone.choose
import com.ullink.slack.simpleslackapi.SlackPreparedMessage
import com.ullink.slack.simpleslackapi.SlackSession
import com.ullink.slack.simpleslackapi.events.SlackMessagePosted
import com.ullink.slack.simpleslackapi.listeners.SlackMessagePostedListener
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class SlackBot(private val session: SlackSession,
val channelName: String,
commands: Iterable<ICommand>,
private val cronCommands: Iterable<ICronTask>)
: SlackMessagePostedListener, IDisposeable {
val commandIndicator = "!"
val commandMap: Map<String, ICommand> = commands.associateBy { it.name }
val botState: BotState
val stateName: String = "$channelName.bot.json"
val slackChannel = session.channels.single { it.name == channelName }!!
private val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
init {
if (commandMap.count() != commands.count()) {
val duplicates = commands.groupBy { it.name }.filter { it.value.count() > 1 }.keys.joinToString()
throw IllegalArgumentException("Commands with identical names added: $duplicates")
}
botState = StateStore().getOrCreate(stateName) { BotState() }
executor.scheduleAtFixedRate({
cronCommands
.flatMap { it.run(slackChannel) }
.forEach { session.sendMessage(slackChannel, it) }
// Save state after command execution
StateStore().save(stateName, botState)
}, 10, 60, TimeUnit.SECONDS)
}
override fun onEvent(event: SlackMessagePosted, session: SlackSession) {
val messageContent = event.messageContent
val channel = event.channel
val sender = event.sender
println("Received message in channel ${channel.name} from ${event.sender.id}, filtering for $channelName")
if (messageContent.isEmpty() || sender.isBot || channelName != channel.name)
return
val firstWord = messageContent.substringBefore(' ')
// Check if message is a command
if (firstWord.startsWith(commandIndicator)) {
// Find command
val commandName = firstWord.removePrefix(commandIndicator)
println("Command: $commandName")
try {
if (!commandMap.containsKey(commandName))
throw CommandNotFoundException(commandName)
val command = commandMap[commandName]!!
if (command.requiresAdmin && !botState.admins.contains(event.sender.id)) {
session.sendMessage(channel, "Command $commandName requires admin rights.")
throw Exception("Command $commandName requires admin rights.")
}
// Execute
val messages = command.execute(messageContent.substringAfter(' '), channel, sender)
println("Going to send messages: $messages")
// Send messages
session.sendMessage(channel, messages.joinToString("\n"))
} catch (ue: IUserException) {
val message = SlackPreparedMessage.Builder()
.withMessage(ue.userMessage)
.withLinkNames(true)
.build()
session.sendMessage(channel, message)
} catch (e: Exception) {
println("Exception while executing command $commandName: $e")
e.printStackTrace()
}
// Save state after command execution
StateStore().save(stateName, botState)
}
}
val shutdownMessages = listOf(
"Shutting down. Tell my :pizza: I love her...",
"Bye bye. It was nice knowing you.",
"I'm going to sleep now... pizZzZzZz...")
override fun dispose() {
session.sendMessage(slackChannel, shutdownMessages.choose())
executor.shutdown()
}
}
class BotState {
val admins = mutableSetOf<String>()
}
class CommandNotFoundException(commandName: String) : Exception("Could not find command '$commandName'.") | apache-2.0 | 4ef402b3ab4a59850d2acdf63741ff52 | 40.333333 | 114 | 0.635169 | 4.970218 | false | false | false | false |
Ekito/koin | koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/utils/SavedStateHandleUtils.kt | 1 | 1562 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.utils
import android.os.Bundle
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
/**
* Return a [MutableState] that will automatically be saved in a [SavedStateHandle].
*
* This can be used from ViewModels to create a compose-observable value that survives rotation. It
* supports arbitrary types with manual conversion to a [Bundle].
*
* @param save convert [T] to a [Bundle] for saving
* @param restore restore a [T] from a [Bundle]
*/
fun <T> SavedStateHandle.getMutableStateOf(
key: String,
default: T,
save: (T) -> Bundle,
restore: (Bundle) -> T
): MutableState<T> {
val bundle: Bundle? = get(key)
val initial = if (bundle == null) { default } else { restore(bundle) }
val state = mutableStateOf(initial)
setSavedStateProvider(key) {
save(state.value)
}
return state
}
| apache-2.0 | 9304acd785c046ded1b2ae33fa7fa10e | 32.956522 | 99 | 0.722791 | 4.078329 | false | false | false | false |
Kotlin/dokka | plugins/templating/src/main/kotlin/templates/TemplateProcessor.kt | 1 | 3857 | package org.jetbrains.dokka.templates
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import org.jetbrains.dokka.DokkaConfiguration.DokkaModuleDescription
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.templating.Command
import org.jetbrains.dokka.model.withDescendants
import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.plugin
import org.jetbrains.dokka.plugability.query
import org.jetbrains.dokka.plugability.querySingle
import org.jsoup.nodes.Node
import java.io.File
interface TemplateProcessor
interface SubmoduleTemplateProcessor : TemplateProcessor {
fun process(modules: List<DokkaModuleDescription>): TemplatingResult
}
interface MultiModuleTemplateProcessor : TemplateProcessor {
fun process(generatedPagesTree: RootPageNode)
}
interface TemplateProcessingStrategy {
fun process(input: File, output: File, moduleContext: DokkaModuleDescription?): Boolean
fun finish(output: File) {}
}
class DefaultSubmoduleTemplateProcessor(
private val context: DokkaContext,
) : SubmoduleTemplateProcessor {
private val strategies: List<TemplateProcessingStrategy> =
context.plugin<TemplatingPlugin>().query { templateProcessingStrategy }
private val configuredModulesPaths =
context.configuration.modules.associate { it.sourceOutputDirectory.absolutePath to it.name }
override fun process(modules: List<DokkaModuleDescription>) =
runBlocking(Dispatchers.Default) {
coroutineScope {
modules.fold(TemplatingResult()) { acc, module ->
acc + module.sourceOutputDirectory.visit(context.configuration.outputDir.resolve(module.relativePathToOutputDirectory), module)
}
}
}
private suspend fun File.visit(target: File, module: DokkaModuleDescription, acc: TemplatingResult = TemplatingResult()): TemplatingResult =
coroutineScope {
val source = this@visit
if (source.isDirectory) {
target.mkdir()
val files = source.list().orEmpty()
val accWithSelf = configuredModulesPaths[source.absolutePath]
?.takeIf { files.firstOrNull { !it.startsWith(".") } != null }
?.let { acc.copy(modules = acc.modules + it) }
?: acc
files.fold(accWithSelf) { acc, path ->
source.resolve(path).visit(target.resolve(path), module, acc)
}
} else {
strategies.first { it.process(source, target, module) }
acc
}
}
}
class DefaultMultiModuleTemplateProcessor(
val context: DokkaContext,
) : MultiModuleTemplateProcessor {
private val strategies: List<TemplateProcessingStrategy> =
context.plugin<TemplatingPlugin>().query { templateProcessingStrategy }
private val locationProviderFactory = context.plugin<DokkaBase>().querySingle { locationProviderFactory }
override fun process(generatedPagesTree: RootPageNode) {
val locationProvider = locationProviderFactory.getLocationProvider(generatedPagesTree)
generatedPagesTree.withDescendants().mapNotNull { pageNode -> locationProvider.resolve(pageNode)?.let { File(it) } }
.forEach { location -> strategies.first { it.process(location, location, null) } }
}
}
data class TemplatingContext<out T : Command>(
val input: File,
val output: File,
val body: List<Node>,
val command: T,
)
data class TemplatingResult(val modules: List<String> = emptyList()) {
operator fun plus(rhs: TemplatingResult): TemplatingResult = TemplatingResult((modules + rhs.modules).distinct())
}
| apache-2.0 | e3dec1f6baf6e6f0a1f8157921aac859 | 38.762887 | 147 | 0.708841 | 4.957584 | false | true | false | false |
SergeyLukashevich/elektrum-lv-unofficial-api | api/src/main/kotlin/lv/sergluka/elektrum/inner/Parser.kt | 1 | 2476 | package lv.sergluka.elektrum.inner
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import org.slf4j.LoggerFactory
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
class Parser {
class ParsingError(message: String?, e: Throwable? = null) : Exception(message, e)
companion object {
private val log = LoggerFactory.getLogger(Parser::class.java)
}
internal fun parse(content: String, formatter: DateTimeFormatter): Map<LocalDateTime, Double?> {
try {
val jsonObject = JsonParser().parse(content).asJsonObject
val dataRef = jsonObject.get("data")
if (dataRef == null || (dataRef.isJsonArray && dataRef.asJsonArray.size() == 0)) {
log.debug("No data")
return mapOf()
}
val data = jsonObject.get("data").asJsonObject
val amounts = data.get("A+").asJsonArray
val dates = jsonObject.get("texts").asJsonObject
.get("tooltips").asJsonObject
.get("A+").asJsonObject
.entrySet().first().value.asJsonArray
val zipped = dates.zip(amounts)
if (zipped.count() != dates.count() || zipped.count() != amounts.count()) {
throw Exception("Amounts and dates counts are different")
}
return zipped.map { joinDateAndAmount(it, formatter) }.toMap()
} catch (e: Exception) {
throw ParsingError("Content parsing error", e)
}
}
private fun joinDateAndAmount(pair: Pair<JsonElement, JsonElement>, formatter: DateTimeFormatter):
Pair<LocalDateTime, Double?> {
val date_str = pair.first.asString
val amount: Double?
try {
val amountObj = pair.second.asJsonObject.entrySet().last().value
val amountStr = if (!amountObj.isJsonNull) amountObj.asString else null
amount = if (!amountStr.isNullOrEmpty()) amountStr!!.toDouble() else null
} catch (e: Exception) {
throw ParsingError("Fail to get amount object from: $pair", e)
}
val date: LocalDateTime
try {
date = LocalDateTime.parse(date_str, formatter)
} catch (e: DateTimeParseException) {
throw ParsingError("Fail to parse date '$date_str'", e)
}
return Pair(date, amount)
}
}
| apache-2.0 | 8288d18aaa11d1bf75b27e01e3c2f873 | 35.411765 | 102 | 0.608239 | 4.628037 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/adapter/UserAdapter.kt | 2 | 3012 | package com.commit451.gitlab.adapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.User
import com.commit451.gitlab.viewHolder.LoadingFooterViewHolder
import com.commit451.gitlab.viewHolder.UserViewHolder
import java.util.*
/**
* Adapter for a list of users
*/
class UserAdapter(private val listener: Listener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val FOOTER_COUNT = 1
private const val TYPE_ITEM = 0
private const val TYPE_FOOTER = 1
}
private val values: ArrayList<User> = ArrayList()
private var loading: Boolean = false
val spanSizeLookup: GridLayoutManager.SpanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val viewType = getItemViewType(position)
return if (viewType == TYPE_FOOTER) {
2
} else {
1
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
TYPE_ITEM -> {
val holder = UserViewHolder.inflate(parent)
holder.itemView.setOnClickListener { v ->
val position = v.getTag(R.id.list_position) as Int
listener.onUserClicked(getUser(position), holder)
}
return holder
}
TYPE_FOOTER -> return LoadingFooterViewHolder.inflate(parent)
}
throw IllegalStateException("No known viewholder for type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is UserViewHolder) {
holder.bind(values[position])
holder.itemView.setTag(R.id.list_position, position)
} else if (holder is LoadingFooterViewHolder) {
holder.bind(loading)
}
}
override fun getItemViewType(position: Int): Int {
return if (position == values.size) {
TYPE_FOOTER
} else {
TYPE_ITEM
}
}
override fun getItemCount(): Int {
return values.size + FOOTER_COUNT
}
fun setData(users: Collection<User>?) {
values.clear()
addData(users)
}
fun addData(users: Collection<User>?) {
if (users != null) {
values.addAll(users)
}
notifyDataSetChanged()
}
fun clearData() {
values.clear()
notifyDataSetChanged()
}
fun setLoading(loading: Boolean) {
this.loading = loading
notifyItemChanged(values.size)
}
private fun getUser(position: Int): User {
return values[position]
}
interface Listener {
fun onUserClicked(user: User, userViewHolder: UserViewHolder)
}
}
| apache-2.0 | be247696db31f73f805f2f668ab0c894 | 27.961538 | 104 | 0.619854 | 4.842444 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/activity/SearchActivity.kt | 2 | 2879 | package com.commit451.gitlab.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.widget.addTextChangedListener
import com.commit451.gitlab.R
import com.commit451.gitlab.adapter.SearchPagerAdapter
import com.commit451.jounce.Debouncer
import com.commit451.teleprinter.Teleprinter
import kotlinx.android.synthetic.main.activity_search.*
import timber.log.Timber
/**
* Search for :allthethings:
*/
class SearchActivity : BaseActivity() {
companion object {
fun newIntent(context: Context): Intent {
return Intent(context, SearchActivity::class.java)
}
}
private lateinit var adapterSearch: SearchPagerAdapter
private lateinit var teleprinter: Teleprinter
private val debouncer = object : Debouncer<CharSequence>() {
override fun onValueSet(value: CharSequence) {
search()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
teleprinter = Teleprinter(this)
toolbar.setNavigationIcon(R.drawable.ic_back_24dp)
toolbar.setNavigationOnClickListener { onBackPressed() }
adapterSearch = SearchPagerAdapter(this, supportFragmentManager)
viewPager.adapter = adapterSearch
tabLayout.setupWithViewPager(viewPager)
textSearch.requestFocus()
buttonClear.setOnClickListener {
buttonClear.animate().alpha(0.0f).withEndAction { buttonClear.visibility = View.GONE }
textSearch.text.clear()
teleprinter.showKeyboard(textSearch)
debouncer.cancel()
}
textSearch.setOnEditorActionListener { _, _, _ ->
if (textSearch.text.isNullOrEmpty()) {
textSearch.setText("labcoat")
}
search()
teleprinter.hideKeyboard()
false
}
textSearch.addTextChangedListener(onTextChanged = { s, _, before, count ->
if (s.isNullOrEmpty()) {
buttonClear.animate().alpha(0.0f).withEndAction { buttonClear.visibility = View.GONE }
} else if (count == 1) {
buttonClear.visibility = View.VISIBLE
buttonClear.animate().alpha(1.0f)
}
if (s != null && s.length > 3) {
Timber.d("Posting new future search")
debouncer.value = s
}
//This means they are backspacing
if (before > count) {
Timber.d("Removing future search")
debouncer.cancel()
}
}
)
}
private fun search() {
val query = textSearch.text.toString()
Timber.d("Searching $query")
adapterSearch.searchQuery(query)
}
}
| apache-2.0 | a3bbb3b26ac840f3d1dcbcf32f1b2f4e | 32.476744 | 102 | 0.629733 | 4.758678 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/androidTest/java/com/garpr/android/features/setRegion/SetRegionViewModelTest.kt | 1 | 8826 | package com.garpr.android.features.setRegion
import com.garpr.android.data.models.Endpoint
import com.garpr.android.data.models.Region
import com.garpr.android.data.models.RegionsBundle
import com.garpr.android.features.common.viewModels.BaseViewModelTest
import com.garpr.android.features.setRegion.SetRegionViewModel.ListItem
import com.garpr.android.features.setRegion.SetRegionViewModel.SaveIconStatus
import com.garpr.android.misc.Schedulers
import com.garpr.android.misc.Timber
import com.garpr.android.repositories.RegionRepository
import com.garpr.android.repositories.RegionsRepository
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.koin.core.inject
class SetRegionViewModelTest : BaseViewModelTest() {
private val regionsRepository = RegionsRepositoryOverride()
private lateinit var viewModel: SetRegionViewModel
protected val regionRepository: RegionRepository by inject()
protected val schedulers: Schedulers by inject()
protected val timber: Timber by inject()
companion object {
private val CHICAGO = Region(
displayName = "Chicago",
id = "chicago",
endpoint = Endpoint.NOT_GAR_PR
)
private val GOOGLE_MTV = Region(
displayName = "Google MTV",
id = "googlemtv",
endpoint = Endpoint.GAR_PR
)
private val NORCAL = Region(
displayName = "Norcal",
id = "norcal",
endpoint = Endpoint.GAR_PR
)
private val NEW_YORK_CITY = Region(
displayName = "New York City",
id = "nyc",
endpoint = Endpoint.NOT_GAR_PR
)
private val ALL_REGIONS_BUNDLE = RegionsBundle(
regions = listOf(CHICAGO, GOOGLE_MTV, NORCAL, NEW_YORK_CITY)
)
private val EMPTY_REGIONS_BUNDLE = RegionsBundle()
private val GAR_PR_REGIONS_BUNDLE = RegionsBundle(
regions = listOf(GOOGLE_MTV, NORCAL)
)
private val NOT_GAR_PR_REGIONS_BUNDLE = RegionsBundle(
regions = listOf(CHICAGO, NEW_YORK_CITY)
)
}
@Before
override fun setUp() {
super.setUp()
viewModel = SetRegionViewModel(regionRepository, regionsRepository, schedulers, timber)
}
@Test
fun testListWithAllRegionsBundle() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
regionsRepository.regionsBundle = ALL_REGIONS_BUNDLE
viewModel.fetchRegions()
assertNotNull(state?.list)
assertEquals(6, state?.list?.size)
var endpoint = state?.list?.get(0) as ListItem.Endpoint
assertEquals(Endpoint.GAR_PR, endpoint.endpoint)
var region = state?.list?.get(1) as ListItem.Region
assertEquals(GOOGLE_MTV.id, region.region.id)
region = state?.list?.get(2) as ListItem.Region
assertEquals(NORCAL.id, region.region.id)
endpoint = state?.list?.get(3) as ListItem.Endpoint
assertEquals(Endpoint.NOT_GAR_PR, endpoint.endpoint)
region = state?.list?.get(4) as ListItem.Region
assertEquals(CHICAGO.id, region.region.id)
region = state?.list?.get(5) as ListItem.Region
assertEquals(NEW_YORK_CITY.id, region.region.id)
}
@Test
fun testListWithGarPrRegionsBundle() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
regionsRepository.regionsBundle = GAR_PR_REGIONS_BUNDLE
viewModel.fetchRegions()
assertNotNull(state?.list)
assertEquals(5, state?.list?.size)
var endpoint = state?.list?.get(0) as ListItem.Endpoint
assertEquals(Endpoint.GAR_PR, endpoint.endpoint)
var region = state?.list?.get(1) as ListItem.Region
assertEquals(GOOGLE_MTV.id, region.region.id)
region = state?.list?.get(2) as ListItem.Region
assertEquals(NORCAL.id, region.region.id)
endpoint = state?.list?.get(3) as ListItem.Endpoint
assertEquals(Endpoint.NOT_GAR_PR, endpoint.endpoint)
val error = state?.list?.get(4) as ListItem.EndpointError
assertEquals(Endpoint.NOT_GAR_PR, error.endpoint)
}
@Test
fun testListWithNotGarPrRegionsBundle() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
regionsRepository.regionsBundle = NOT_GAR_PR_REGIONS_BUNDLE
viewModel.fetchRegions()
assertNotNull(state?.list)
assertEquals(5, state?.list?.size)
var endpoint = state?.list?.get(0) as ListItem.Endpoint
assertEquals(Endpoint.NOT_GAR_PR, endpoint.endpoint)
var region = state?.list?.get(1) as ListItem.Region
assertEquals(CHICAGO.id, region.region.id)
region = state?.list?.get(2) as ListItem.Region
assertEquals(NEW_YORK_CITY.id, region.region.id)
endpoint = state?.list?.get(3) as ListItem.Endpoint
assertEquals(Endpoint.GAR_PR, endpoint.endpoint)
val error = state?.list?.get(4) as ListItem.EndpointError
assertEquals(Endpoint.GAR_PR, error.endpoint)
}
@Test
fun testSaveIconStatus() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
assertTrue(state == null || state?.saveIconStatus == SaveIconStatus.GONE)
viewModel.fetchRegions()
assertEquals(SaveIconStatus.DISABLED, state?.saveIconStatus)
viewModel.selectedRegion = GOOGLE_MTV
assertEquals(SaveIconStatus.ENABLED, state?.saveIconStatus)
viewModel.selectedRegion = CHICAGO
assertEquals(SaveIconStatus.ENABLED, state?.saveIconStatus)
viewModel.selectedRegion = NORCAL
assertEquals(SaveIconStatus.DISABLED, state?.saveIconStatus)
}
@Test
fun testSaveSelectedRegion() {
viewModel.fetchRegions()
viewModel.selectedRegion = CHICAGO
var throwable: Throwable? = null
try {
viewModel.saveSelectedRegion()
} catch (t: Throwable) {
throwable = t
}
assertNull(throwable)
assertEquals(CHICAGO, regionRepository.region)
}
@Test
fun testSaveSelectedRegionThrowsExceptionIfNoRegionSelected() {
viewModel.fetchRegions()
var throwable: Throwable? = null
try {
viewModel.saveSelectedRegion()
} catch (t: Throwable) {
throwable = t
}
assertNotNull(throwable)
}
@Test
fun testStateWithEmptyRegionsBundle() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
regionsRepository.regionsBundle = EMPTY_REGIONS_BUNDLE
viewModel.fetchRegions()
assertEquals(true, state?.hasError)
assertTrue(state?.list.isNullOrEmpty())
}
@Test
fun testStateWithNullRegionsBundle() {
var state: SetRegionViewModel.State? = null
viewModel.stateLiveData.observeForever {
state = it
}
regionsRepository.regionsBundle = null
viewModel.fetchRegions()
assertEquals(true, state?.hasError)
assertEquals(false, state?.isFetching)
assertEquals(true, state?.isRefreshEnabled)
assertNull(state?.list)
assertNull(state?.selectedRegion)
assertEquals(SaveIconStatus.GONE, state?.saveIconStatus)
}
@Test
fun testWarnBeforeClose() {
assertFalse(viewModel.warnBeforeClose)
viewModel.fetchRegions()
assertFalse(viewModel.warnBeforeClose)
viewModel.selectedRegion = NEW_YORK_CITY
assertTrue(viewModel.warnBeforeClose)
viewModel.selectedRegion = regionRepository.region
assertFalse(viewModel.warnBeforeClose)
viewModel.selectedRegion = GOOGLE_MTV
assertTrue(viewModel.warnBeforeClose)
}
private class RegionsRepositoryOverride(
internal var regionsBundle: RegionsBundle? = ALL_REGIONS_BUNDLE
) : RegionsRepository {
override fun getRegions(): Single<RegionsBundle> {
val regionsBundle = this.regionsBundle
return if (regionsBundle == null) {
Single.error(NullPointerException())
} else {
Single.just(regionsBundle)
}
}
}
}
| unlicense | c95380ead667c1b7bc46e380e900ade0 | 29.226027 | 95 | 0.651258 | 4.489318 | false | true | false | false |
roylanceMichael/yaorm | buildSrc/src/main/java/utilities/InitUtilities.kt | 1 | 2749 | package utilities
object InitUtilities {
const val OsNameProperty = "os.name"
const val DpkgDeb = "dpkg-deb"
const val Chmod = "chmod"
const val ChmodExecutable = "755"
const val RemoveDirectory = "rm"
const val Find = "find"
const val Move = "mv"
const val Bash = "bash"
const val Curl = "curl"
const val Gradle = "gradle"
const val Maven = "mvn"
const val Nuget = "nuget"
const val DotNet = "dotnet"
const val Python = "python"
const val Pip = "pip"
const val XCodeBuild = "xcodebuild"
const val Carthage = "carthage"
const val TypeScriptCompiler = "tsc"
const val NPM = "npm"
const val Protoc = "protoc"
const val Separator = """---------------------------------------------------------------------------------------------------------"""
const val MinimumRequiredErrorMessage = """Minimum requirements to run Yaclib not met. Please ensure the following requirements are met:
OS is OSX/MacOS or Linux
protoc, mvn, gradle, python, tsc, npm can all be located with "which"
optional: dotnet and nuget can be located with "which"
MAKE SURE THAT ~/.bashrc or ~/.bash_profile PATH contains references to the folder these apps are located in!
"""
fun hasMinimumRequired(): Boolean {
return isNotWindows() &&
hasNPM() &&
hasTypeScriptCompiler() &&
hasPython() &&
hasGradle() &&
hasProtoc() &&
hasMaven()
}
fun hasCSharp(): Boolean {
return hasDotNet() && hasNuget()
}
fun hasProtoc(): Boolean {
return FileProcessUtilities.getActualLocation(Protoc).isNotEmpty()
}
fun hasGradle(): Boolean {
return FileProcessUtilities.getActualLocation(Gradle).isNotEmpty()
}
fun hasMaven(): Boolean {
return FileProcessUtilities.getActualLocation(Maven).isNotEmpty()
}
fun hasDotNet(): Boolean {
return FileProcessUtilities.getActualLocation(DotNet).isNotEmpty()
}
fun hasNuget(): Boolean {
return FileProcessUtilities.getActualLocation(Nuget).isNotEmpty()
}
fun hasPython(): Boolean {
return FileProcessUtilities.getActualLocation(Python).isNotEmpty()
}
fun hasTypeScriptCompiler(): Boolean {
return FileProcessUtilities.getActualLocation(TypeScriptCompiler).isNotEmpty()
}
fun hasNPM(): Boolean {
return FileProcessUtilities.getActualLocation(NPM).isNotEmpty()
}
fun isNotWindows(): Boolean {
return !System.getProperty(OsNameProperty).toLowerCase().startsWith("window")
}
fun buildPhaseMessage(message: String): String {
return """$Separator
$message
$Separator"""
}
} | mit | 8cc132a9140de708233445a0e4796df3 | 27.350515 | 140 | 0.622408 | 4.67517 | false | false | false | false |
gameover-fwk/gameover-fwk | src/main/kotlin/gameover/fwk/math/MathUtils.kt | 1 | 2742 | package gameover.fwk.math
import com.badlogic.gdx.math.GridPoint2
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import gameover.fwk.pool.Vector2Pool
object MathUtils {
/**
* Compute the distance for a list of points.
* For example, if we give three points a, b and c, it
* will compute two distances: from a to b and from b to c
* @param pathPoints the path point
* @return a list of distances
*/
fun distance(pathPoints: List<GridPoint2>?) : List<Double>?
= if (pathPoints != null) pathPoints.mapIndexed { i, p -> if (i == 0) 0.0 else distance(p, pathPoints[i - 1]) } else null
fun floorAsInt(x: Float): Int {
return MathUtils.floor(x)
}
fun floor(x: Float): Float {
return floorAsInt(x).toFloat()
}
/**
* Compute the sum of all distances for a list of points.
* For example, if we give three points a, b and c, it
* will compute two distances: from a to b and from b to c, then it will sum this two distances
* @param pathPoints the path point
* @return a distance
*/
fun distanceSum(pathPoints: List<GridPoint2>?) : Double = distance(pathPoints)?.reduceRight { v, acc -> v + acc } ?: 0.0
fun distance(a: GridPoint2, b: GridPoint2) : Double = Math.sqrt(Math.pow((b.x - a.x).toDouble(), 2.0) + Math.pow((b.y - a.y).toDouble(), 2.0))
fun computeAngle(x1: Float, y1: Float, x2: Float, y2: Float): Float = computeAngle(x2 - x1, y2 - y1)
fun computeAngle(dx: Float, dy: Float): Float {
val dv: Vector2 = Vector2Pool.obtain(dx, dy)
try {
return dv.angle()
} finally {
Vector2Pool.free(dv)
}
}
/**
* Find directions to reach a point from a point.
*/
fun directions(x: Float, y: Float, tx: Float, ty: Float) : Directions {
val diffX = Math.signum(tx - x)
val diffY = Math.signum(ty - y)
return Directions(diffY > 0f, diffY < 0f, diffX < 0f, diffX > 0f)
}
/**
* Return all edges
*/
fun edges(area: Rectangle) : List<Pair<Float, Float>> =
listOf(Pair(area.x, area.y), Pair(area.x + area.width, area.y), Pair(area.x, area.y + area.height), Pair(area.x + area.width, area.y + area.height))
/**
* Return all edges sorted from the closest to farest
*/
fun nearestEdges(x: Float, y: Float, area: Rectangle) : List<Pair<Float, Float>> {
return edges(area).sortedBy {
(tx, ty) -> Math.pow((tx - x).toDouble(), 2.0) + Math.pow((ty - y).toDouble(), 2.0)
}
}
}
data class Directions(val top: Boolean, val bottom: Boolean, val left: Boolean, val right: Boolean)
| mit | 90eef85b65c4f0cea5608d47c02698b8 | 33.708861 | 156 | 0.612327 | 3.38937 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/home/more/appcoins/EarnAppcListFragment.kt | 1 | 9343 | package cm.aptoide.pt.home.more.appcoins
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import cm.aptoide.aptoideviews.recyclerview.GridRecyclerView
import cm.aptoide.pt.R
import cm.aptoide.pt.app.DownloadModel
import cm.aptoide.pt.home.bundles.apps.RewardApp
import cm.aptoide.pt.home.more.base.ListAppsFragment
import cm.aptoide.pt.promotions.WalletApp
import cm.aptoide.pt.store.view.StoreTabGridRecyclerFragment
import cm.aptoide.pt.themes.ThemeManager
import cm.aptoide.pt.utils.GenericDialogs
import com.jakewharton.rxbinding.view.RxView
import kotlinx.android.synthetic.main.earn_appcoins_wallet_install_layout.*
import kotlinx.android.synthetic.main.wallet_install_cardview.*
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.exceptions.OnErrorNotImplementedException
import java.text.DecimalFormat
import javax.inject.Inject
class EarnAppcListFragment : ListAppsFragment<RewardApp, EarnAppcListViewHolder>(),
EarnAppcListView {
@Inject
lateinit var presenter: EarnAppcListPresenter
@Inject
lateinit var themeManager: ThemeManager
private var errorMessageSubscription: Subscription? = null
private val oneDecimalFormatter = DecimalFormat("0.0")
companion object {
fun newInstance(title: String, tag: String): EarnAppcListFragment {
val fragment = EarnAppcListFragment()
val config = Bundle()
config.putString(StoreTabGridRecyclerFragment.BundleCons.TITLE, title)
config.putString(StoreTabGridRecyclerFragment.BundleCons.TAG, tag)
fragment.arguments = config
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getFragmentComponent(savedInstanceState).inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val listAppsLayout = super.onCreateView(inflater, container, savedInstanceState) as ViewGroup
inflater.inflate(R.layout.earn_appcoins_wallet_install_layout, listAppsLayout)
return listAppsLayout
}
override fun onDestroy() {
errorMessageSubscription?.also { errorSubscription ->
if (!errorSubscription.isUnsubscribed) {
errorSubscription.unsubscribe()
}
}
super.onDestroy()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.present()
}
override fun setupWallet(walletApp: WalletApp) {
if (!walletApp.isInstalled) {
app_cardview_layout.startAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_up))
app_cardview_layout.visibility = View.VISIBLE
wallet_app_title_textview.text = walletApp.appName
rating_label.text = oneDecimalFormatter.format(walletApp.rating)
}
}
override fun hideWalletArea() {
val animation = AnimationUtils.loadAnimation(context, R.anim.slide_down)
animation.fillAfter = true
app_cardview_layout.startAnimation(animation)
}
override fun updateState(walletApp: WalletApp) {
walletApp.downloadModel?.also { downloadModel ->
if (downloadModel.isDownloadingOrInstalling) {
appview_transfer_info.visibility = View.VISIBLE
install_group.visibility = View.GONE
setDownloadState(downloadModel.progress, downloadModel.downloadState)
} else if (!walletApp.isInstalled) {
appview_transfer_info.visibility = View.GONE
install_group.visibility = View.VISIBLE
}
}
}
override fun showDownloadError(walletApp: WalletApp) {
walletApp.downloadModel?.also { downloadModel ->
if (downloadModel.hasError()) {
handleDownloadError(downloadModel.downloadState)
}
}
}
private fun handleDownloadError(downloadState: DownloadModel.DownloadState?) {
if (downloadState == DownloadModel.DownloadState.ERROR) {
showErrorDialog("",
requireContext().getString(R.string.error_occured))
}
}
private fun showErrorDialog(title: String, message: String) {
errorMessageSubscription = GenericDialogs.createGenericOkMessage(context, title, message,
themeManager.getAttributeForTheme(R.attr.dialogsTheme).resourceId)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe({ }, { error -> OnErrorNotImplementedException(error) })
}
private fun setDownloadState(progress: Int, downloadState: DownloadModel.DownloadState?) {
val pauseShowing = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, 4f)
val pauseHidden = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, 2f)
when (downloadState) {
DownloadModel.DownloadState.ACTIVE -> {
appview_download_progress_bar.isIndeterminate = false
appview_download_progress_bar.progress = progress
appview_download_progress_number.text = "$progress%"
appview_download_pause_download.visibility = View.VISIBLE
appview_download_cancel_button.visibility = View.GONE
appview_download_resume_download.visibility = View.GONE
install_controls_layout.layoutParams = pauseShowing
appview_download_download_state.text = getString(R.string.appview_short_downloading)
}
DownloadModel.DownloadState.INDETERMINATE -> {
appview_download_progress_bar.isIndeterminate = true
appview_download_pause_download.visibility = View.VISIBLE
appview_download_cancel_button.visibility = View.GONE
appview_download_resume_download.visibility = View.GONE
install_controls_layout.layoutParams = pauseShowing
appview_download_download_state.text = getString(R.string.appview_short_downloading)
}
DownloadModel.DownloadState.PAUSE -> {
appview_download_progress_bar.isIndeterminate = false
appview_download_progress_bar.progress = progress
appview_download_progress_number.text = "$progress%"
appview_download_pause_download.visibility = View.GONE
appview_download_cancel_button.visibility = View.VISIBLE
appview_download_resume_download.visibility = View.VISIBLE
install_controls_layout.layoutParams = pauseHidden
appview_download_download_state.text = getString(R.string.appview_short_downloading)
}
DownloadModel.DownloadState.COMPLETE -> {
appview_download_progress_bar.isIndeterminate = true
appview_download_pause_download.visibility = View.VISIBLE
appview_download_cancel_button.visibility = View.GONE
appview_download_resume_download.visibility = View.GONE
install_controls_layout.layoutParams = pauseShowing
appview_download_download_state.text = getString(R.string.appview_short_downloading)
}
DownloadModel.DownloadState.INSTALLING -> {
appview_download_progress_bar.isIndeterminate = true
appview_download_pause_download.visibility = View.GONE
appview_download_cancel_button.visibility = View.GONE
appview_download_resume_download.visibility = View.GONE
install_controls_layout.layoutParams = pauseHidden
appview_download_download_state.text = getString(R.string.appview_short_installing)
}
DownloadModel.DownloadState.ERROR -> showErrorDialog("",
requireContext().getString(R.string.error_occured))
DownloadModel.DownloadState.NOT_ENOUGH_STORAGE_ERROR -> showErrorDialog(
requireContext().getString(R.string.out_of_space_dialog_title),
requireContext().getString(R.string.out_of_space_dialog_message))
}
}
override fun resumeDownload(): Observable<Void> {
return RxView.clicks(appview_download_resume_download)
}
override fun pauseDownload(): Observable<Void> {
return RxView.clicks(appview_download_pause_download)
}
override fun cancelDownload(): Observable<Void> {
return RxView.clicks(appview_download_cancel_button)
}
override fun showRootInstallWarningPopup(): Observable<Boolean> {
return GenericDialogs.createGenericYesNoCancelMessage(requireContext(), null,
resources.getString(R.string.root_access_dialog),
themeManager.getAttributeForTheme(R.attr.dialogsTheme).resourceId)
.map { response -> response.equals(GenericDialogs.EResponse.YES) }
}
override fun onWalletInstallClick(): Observable<Void> {
return RxView.clicks(wallet_install_button)
}
override fun getItemSizeWidth(): Int {
return 168
}
override fun getItemSizeHeight(): Int {
return 158
}
override fun getAdapterStrategy(): GridRecyclerView.AdaptStrategy {
return GridRecyclerView.AdaptStrategy.SCALE_KEEP_ASPECT_RATIO
}
override fun getContainerPaddingDp(): Rect {
return Rect(8, 8, 8, 118)
}
override fun createViewHolder(): (ViewGroup, Int) -> EarnAppcListViewHolder {
return { parent, viewType ->
EarnAppcListViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.earn_appcoins_item_more, parent,
false), DecimalFormat("0.00"))
}
}
} | gpl-3.0 | 026c19871461279df2a0dc053ff6fbe7 | 38.59322 | 97 | 0.741197 | 4.50917 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/wallet/WalletInstallPresenter.kt | 1 | 6886 | package cm.aptoide.pt.wallet
import android.os.Build
import cm.aptoide.pt.actions.PermissionManager
import cm.aptoide.pt.actions.PermissionService
import cm.aptoide.pt.ads.MoPubAdsManager
import cm.aptoide.pt.ads.WalletAdsOfferManager
import cm.aptoide.pt.app.DownloadModel
import cm.aptoide.pt.presenter.Presenter
import cm.aptoide.pt.presenter.View
import cm.aptoide.pt.promotions.WalletApp
import rx.Completable
import rx.Observable
import rx.Scheduler
import rx.schedulers.Schedulers
class WalletInstallPresenter(val view: WalletInstallView,
val walletInstallManager: WalletInstallManager,
val navigator: WalletInstallNavigator,
val permissionManager: PermissionManager,
val permissionService: PermissionService,
val viewScheduler: Scheduler,
val io: Scheduler,
val configuration: WalletInstallConfiguration,
val walletInstallAnalytics: WalletInstallAnalytics,
val moPubAdsManager: MoPubAdsManager) : Presenter {
override fun present() {
loadWalletInstall()
handleCloseButtonClick()
handleCancelDownloadButton()
handleAnalyticsContextSetup()
}
private fun handleAnalyticsContextSetup() {
view.lifecycleEvent
.filter { lifecycleEvent -> View.LifecycleEvent.CREATE == lifecycleEvent }
.doOnNext { walletInstallManager.setupAnalyticsHistoryTracker() }
.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY))
.subscribe({}, {
it.printStackTrace()
view.dismissDialog()
})
}
private fun handleCancelDownloadButton() {
view.lifecycleEvent
.filter { lifecycleEvent -> View.LifecycleEvent.CREATE == lifecycleEvent }
.flatMap { view.cancelDownloadButtonClicked() }
.flatMap { walletInstallManager.getWallet() }.first()
.doOnNext { walletApp -> walletInstallManager.removeDownload(walletApp) }
.observeOn(viewScheduler)
.doOnCompleted {
view.dismissDialog()
}
.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY))
.subscribe({}, {
it.printStackTrace()
view.dismissDialog()
})
}
private fun handleWalletInstallation(): Observable<Boolean> {
return walletInstallManager.onWalletInstalled().first()
.observeOn(viewScheduler)
.doOnNext { view.showInstallationSuccessView() }
}
private fun loadWalletInstall() {
view.lifecycleEvent
.filter { lifecycleEvent -> View.LifecycleEvent.CREATE == lifecycleEvent }
.doOnNext {
if (!hasMinimumSdk())
view.showSdkErrorView()
}
.filter { hasMinimumSdk() }
.flatMap {
showWalletInitialState()
}
.filter { walletInitialState -> !walletInitialState.second.isInstalled }
.observeOn(viewScheduler)
.doOnNext { view.showIndeterminateDownload() }
.flatMap { walletInitialState ->
startWalletDownload(walletInitialState.second).andThen(
Observable.merge(handleWalletInstallation(),
observeDownloadProgress(walletInitialState.second),
handleInstallDialogCancelButtonPress()))
}
.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY))
.subscribe({}, {
it.printStackTrace()
view.dismissDialog()
})
}
private fun observeDownloadProgress(walletApp: WalletApp): Observable<WalletApp> {
return walletInstallManager.loadDownloadModel(walletApp)
.flatMap { downloadModel -> verifyNotEnoughSpaceError(downloadModel, walletApp) }
.observeOn(viewScheduler)
.doOnNext { view.showDownloadState(it) }.map { walletApp }
}
private fun verifyNotEnoughSpaceError(downloadModel: DownloadModel,
walletApp: WalletApp): Observable<DownloadModel> {
if (downloadModel.downloadState == DownloadModel.DownloadState.NOT_ENOUGH_STORAGE_ERROR) {
moPubAdsManager.getAdsVisibilityStatus()
.doOnSuccess { offerResponseStatus: WalletAdsOfferManager.OfferResponseStatus? ->
val action = downloadModel.action
walletInstallAnalytics.sendNotEnoughSpaceErrorEvent(walletApp.packageName,
walletApp.versionCode, downloadModel.action,
offerResponseStatus,
action != null && action == DownloadModel.Action.MIGRATE,
walletApp.splits.isNotEmpty(), true,
walletApp.trustedBadge, walletApp.storeName, false)
}
.toObservable()
.map { downloadModel }
}
return Observable.just(downloadModel)
}
private fun startWalletDownload(walletApp: WalletApp): Completable {
return Observable.defer {
if (walletInstallManager.shouldShowRootInstallWarningPopup()) {
view.showRootInstallWarningPopup()
?.doOnNext { answer -> walletInstallManager.allowRootInstall(answer) }
}
Observable.just(walletApp)
}.observeOn(viewScheduler)
.flatMap {
permissionManager.requestDownloadAllowingMobileData(permissionService)
.flatMap {
permissionManager.requestExternalStoragePermission(permissionService)
}
.observeOn(Schedulers.io())
.flatMapCompletable {
walletInstallManager.downloadApp(walletApp)
}
}.toCompletable()
}
private fun showWalletInitialState(): Observable<Pair<String?, WalletApp>>? {
return Observable.zip(walletInstallManager.getAppIcon(configuration.appPackageName),
walletInstallManager.getWallet()) { appIcon, walletApp ->
Pair<String?, WalletApp>(appIcon, walletApp)
}.first().observeOn(viewScheduler)
.doOnNext { pair ->
if (pair.second.isInstalled) {
view.showWalletInstalledAlreadyView()
} else {
view.showWalletInstallationView(pair.first, pair.second)
}
}
}
private fun hasMinimumSdk(): Boolean {
return Build.VERSION.SDK_INT >= 21
}
private fun handleCloseButtonClick() {
view.lifecycleEvent
.filter { lifecycleEvent -> View.LifecycleEvent.CREATE == lifecycleEvent }
.flatMap { view.closeButtonClicked() }
.doOnNext { view.dismissDialog() }
.compose(view.bindUntilEvent(View.LifecycleEvent.DESTROY))
.subscribe({}, { error ->
error.printStackTrace()
view.dismissDialog()
})
}
private fun handleInstallDialogCancelButtonPress(): Observable<Boolean> {
return walletInstallManager.onWalletInstallationCanceled().first()
.doOnNext { view.dismissDialog() }
}
} | gpl-3.0 | 9d2b9625c9690ab19f29c7467dd3f868 | 37.909605 | 94 | 0.657421 | 5.329721 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/datatablelistfragment/DataTableListFragment.kt | 1 | 12656 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.datatablelistfragment
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.*
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import butterknife.BindView
import butterknife.ButterKnife
import com.mifos.exceptions.RequiredFieldException
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.formwidgets.*
import com.mifos.mifosxdroid.online.ClientActivity
import com.mifos.mifosxdroid.online.datatablelistfragment.DataTableListFragment
import com.mifos.objects.client.Client
import com.mifos.objects.client.ClientPayload
import com.mifos.objects.noncore.DataTable
import com.mifos.objects.noncore.DataTablePayload
import com.mifos.services.data.GroupLoanPayload
import com.mifos.services.data.LoansPayload
import com.mifos.utils.Constants
import com.mifos.utils.MifosResponseHandler
import com.mifos.utils.PrefManager
import com.mifos.utils.SafeUIBlockingUtility
import java.util.*
import javax.inject.Inject
/**
* A generic fragment to show the DataTables at the runtime.
*
* It receives the list of DataTables, the corresponding LoanPayload (client/center/group)
* and an identifier int that states the type of entity generating the request for datatables.
*
* It differs from the other DatatableDialogFragments in the sense that -
* 1. it does NOT query for the datatables i.e. it does not fetch the datatable from the endpoint.
* 2. it shows all the datatables (from datatable array) unlike in the other fragments which show
* a single datatable.
*/
class DataTableListFragment : Fragment(), DataTableListMvpView {
private val LOG_TAG = javaClass.simpleName
@JvmField
@BindView(R.id.ll_data_table_entry_form)
var linearLayout: LinearLayout? = null
@JvmField
@Inject
var mDataTableListPresenter: DataTableListPresenter? = null
private var dataTables: List<DataTable>? = null
private var dataTablePayloadElements: ArrayList<DataTablePayload>? = null
private var clientLoansPayload: LoansPayload? = null
private var groupLoanPayload: GroupLoanPayload? = null
private var clientPayload: ClientPayload? = null
private var requestType = 0
private lateinit var rootView: View
private var safeUIBlockingUtility: SafeUIBlockingUtility? = null
private val listFormWidgets: MutableList<List<FormWidget>> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
rootView = inflater.inflate(R.layout.dialog_fragment_add_entry_to_datatable, container,
false)
ButterKnife.bind(this, rootView)
mDataTableListPresenter!!.attachView(this)
requireActivity().title = requireActivity().resources.getString(
R.string.associated_datatables)
safeUIBlockingUtility = SafeUIBlockingUtility(this@DataTableListFragment
.activity, getString(R.string.create_client_loading_message))
for (datatable in dataTables!!) {
createForm(datatable)
}
addSaveButton()
return rootView
}
fun createForm(table: DataTable) {
val tableName = TextView(requireActivity().applicationContext)
tableName.text = table.registeredTableName
tableName.gravity = Gravity.CENTER_HORIZONTAL
tableName.setTypeface(null, Typeface.BOLD)
tableName.setTextColor(requireActivity().resources.getColor(R.color.black))
tableName.setTextSize(TypedValue.COMPLEX_UNIT_SP,
requireActivity().resources.getDimension(R.dimen.datatable_name_heading))
linearLayout!!.addView(tableName)
val formWidgets: MutableList<FormWidget> = ArrayList()
for (columnHeader in table.columnHeaderData) {
if (!columnHeader.columnPrimaryKey) {
if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_STRING || columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_TEXT) {
val formEditText = FormEditText(activity, columnHeader
.columnName)
formWidgets.add(formEditText)
linearLayout!!.addView(formEditText.view)
} else if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_INT) {
val formNumericEditText = FormNumericEditText(activity, columnHeader.columnName)
formNumericEditText.returnType = FormWidget.SCHEMA_KEY_INT
formWidgets.add(formNumericEditText)
linearLayout!!.addView(formNumericEditText.view)
} else if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_DECIMAL) {
val formNumericEditText = FormNumericEditText(activity, columnHeader.columnName)
formNumericEditText.returnType = FormWidget.SCHEMA_KEY_DECIMAL
formWidgets.add(formNumericEditText)
linearLayout!!.addView(formNumericEditText.view)
} else if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_CODELOOKUP || columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_CODEVALUE) {
if (columnHeader.columnValues.size > 0) {
val columnValueStrings: MutableList<String> = ArrayList()
val columnValueIds: MutableList<Int> = ArrayList()
for (columnValue in columnHeader.columnValues) {
columnValueStrings.add(columnValue.value)
columnValueIds.add(columnValue.id)
}
val formSpinner = FormSpinner(activity, columnHeader
.columnName, columnValueStrings, columnValueIds)
formSpinner.returnType = FormWidget.SCHEMA_KEY_CODEVALUE
formWidgets.add(formSpinner)
linearLayout!!.addView(formSpinner.view)
}
} else if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_DATE) {
val formEditText = FormEditText(activity, columnHeader
.columnName)
formEditText.setIsDateField(true, requireActivity().supportFragmentManager)
formWidgets.add(formEditText)
linearLayout!!.addView(formEditText.view)
} else if (columnHeader.columnDisplayType == FormWidget.SCHEMA_KEY_BOOL) {
val formToggleButton = FormToggleButton(activity,
columnHeader.columnName)
formWidgets.add(formToggleButton)
linearLayout!!.addView(formToggleButton.view)
}
}
}
listFormWidgets.add(formWidgets)
}
private fun addSaveButton() {
val bt_processForm = Button(activity)
bt_processForm.layoutParams = FormWidget.defaultLayoutParams
bt_processForm.text = getString(R.string.save)
bt_processForm.setBackgroundColor(requireActivity().resources.getColor(R.color.blue_dark))
linearLayout!!.addView(bt_processForm)
bt_processForm.setOnClickListener {
try {
onSaveActionRequested()
} catch (e: RequiredFieldException) {
Log.d(LOG_TAG, e.message.toString())
}
}
}
@Throws(RequiredFieldException::class)
fun onSaveActionRequested() {
dataTablePayloadElements = ArrayList()
for (i in dataTables!!.indices) {
val dataTablePayload = DataTablePayload()
dataTablePayload.registeredTableName = dataTables!![i].registeredTableName
dataTablePayload.data = addDataTableInput(i)
dataTablePayloadElements!!.add(dataTablePayload)
}
when (requestType) {
Constants.CLIENT_LOAN -> {
clientLoansPayload!!.dataTables = dataTablePayloadElements
mDataTableListPresenter!!.createLoansAccount(clientLoansPayload)
}
Constants.GROUP_LOAN -> //Add Datatables in GroupLoan Payload and then add them here.
mDataTableListPresenter!!.createGroupLoanAccount(groupLoanPayload)
Constants.CREATE_CLIENT -> {
clientPayload!!.datatables = dataTablePayloadElements
mDataTableListPresenter!!.createClient(clientPayload)
}
}
}
fun addDataTableInput(index: Int): HashMap<String, Any> {
val formWidgets = listFormWidgets[index]
val payload = HashMap<String, Any>()
payload[Constants.DATE_FORMAT] = "dd-mm-YYYY"
payload[Constants.LOCALE] = "en"
for (formWidget in formWidgets) {
if (formWidget.returnType == FormWidget.SCHEMA_KEY_INT) {
payload[formWidget.propertyName] = if (formWidget.value
== "") "0" else formWidget.value.toInt()
} else if (formWidget.returnType == FormWidget.SCHEMA_KEY_DECIMAL) {
payload[formWidget.propertyName] = if (formWidget.value == "") "0.0" else formWidget.value.toDouble()
} else if (formWidget.returnType == FormWidget.SCHEMA_KEY_CODEVALUE) {
val formSpinner = formWidget as FormSpinner
payload[formWidget.getPropertyName()] = formSpinner.getIdOfSelectedItem(formWidget.getValue())
} else {
payload[formWidget.propertyName] = formWidget.value
}
}
return payload
}
override fun showMessage(messageId: Int) {
Toaster.show(rootView, getString(messageId))
requireActivity().supportFragmentManager.popBackStackImmediate()
}
override fun showMessage(message: String?) {
Toaster.show(rootView, message)
requireActivity().supportFragmentManager.popBackStackImmediate()
}
override fun showClientCreatedSuccessfully(client: Client) {
requireActivity().supportFragmentManager.popBackStack()
requireActivity().supportFragmentManager.popBackStack()
Toast.makeText(activity, getString(R.string.client) +
MifosResponseHandler.getResponse(), Toast.LENGTH_SHORT).show()
if (PrefManager.getUserStatus() == Constants.USER_ONLINE) {
val clientActivityIntent = Intent(activity, ClientActivity::class.java)
clientActivityIntent.putExtra(Constants.CLIENT_ID, client.clientId)
startActivity(clientActivityIntent)
}
}
override fun showWaitingForCheckerApproval(message: Int) {
requireActivity().supportFragmentManager.popBackStack()
Toaster.show(rootView, message, Toast.LENGTH_SHORT)
}
override fun showProgressbar(b: Boolean) {
if (b) {
safeUIBlockingUtility!!.safelyBlockUI()
} else {
safeUIBlockingUtility!!.safelyUnBlockUI()
}
}
override fun onDestroyView() {
super.onDestroyView()
mDataTableListPresenter!!.detachView()
}
companion object {
@JvmStatic
fun newInstance(dataTables: List<DataTable>?,
payload: Any?, type: Int): DataTableListFragment {
val dataTableListFragment = DataTableListFragment()
val args = Bundle()
dataTableListFragment.dataTables = dataTables
dataTableListFragment.requestType = type
when (type) {
Constants.CLIENT_LOAN -> dataTableListFragment.clientLoansPayload = payload as LoansPayload?
Constants.GROUP_LOAN -> dataTableListFragment.groupLoanPayload = payload as GroupLoanPayload?
Constants.CREATE_CLIENT -> dataTableListFragment.clientPayload = payload as ClientPayload?
}
dataTableListFragment.arguments = args
return dataTableListFragment
}
}
} | mpl-2.0 | c7a6b908c94eefee58c71b864261d0b6 | 46.582707 | 165 | 0.66909 | 5.030207 | false | false | false | false |
EvidentSolutions/apina | apina-core/src/main/kotlin/fi/evident/apina/model/DiscriminatedUnionDefinition.kt | 1 | 616 | package fi.evident.apina.model
import fi.evident.apina.model.type.ApiTypeName
import java.util.*
class DiscriminatedUnionDefinition(
val type: ApiTypeName,
val discriminator: String) {
private val _types = TreeMap<String, ClassDefinition>()
val types: SortedMap<String, ClassDefinition>
get() = _types
fun addType(discriminator: String, type: ClassDefinition) {
val old = types.putIfAbsent(discriminator, type)
check(old == null) { "Tried to add duplicated case '$discriminator' to discriminated union '$type" }
}
override fun toString() = type.toString()
}
| mit | a9545a17facfebce30987be0782e2dd1 | 28.333333 | 108 | 0.702922 | 4.219178 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/controls/TeamModeDialog.kt | 1 | 2869 | package de.westnordost.streetcomplete.controls
import android.content.Context
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.controls.TeamModeColorCircleView.Companion.MAX_TEAM_SIZE
import de.westnordost.streetcomplete.databinding.DialogTeamModeBinding
/** Shows a dialog containing the team mode settings */
class TeamModeDialog(
context: Context,
onEnableTeamMode: (Int, Int) -> Unit
) : AlertDialog(context, R.style.Theme_Bubble_Dialog) {
private var selectedTeamSize: Int? = null
private var selectedIndexInTeam: Int? = null
private val binding = DialogTeamModeBinding.inflate(LayoutInflater.from(context))
init {
val adapter = TeamModeIndexSelectAdapter()
adapter.listeners.add(object : TeamModeIndexSelectAdapter.OnSelectedIndexChangedListener {
override fun onSelectedIndexChanged(index: Int?) {
selectedIndexInTeam = index
updateOkButtonEnablement()
}
})
binding.colorCircles.adapter = adapter
binding.colorCircles.layoutManager = GridLayoutManager(context, 3)
binding.teamSizeInput.addTextChangedListener { editable ->
selectedTeamSize = parseTeamSize(editable.toString())
updateOkButtonEnablement()
if (selectedTeamSize == null) {
binding.introText.isGone = false
binding.teamSizeHint.isGone = false
binding.colorHint.isGone = true
binding.colorCircles.isGone = true
} else {
binding.introText.isGone = true
binding.teamSizeHint.isGone = true
binding.colorHint.isGone = false
binding.colorCircles.isGone = false
adapter.count = selectedTeamSize!!
}
}
setButton(BUTTON_POSITIVE, context.resources.getText(android.R.string.ok)) { _, _ ->
onEnableTeamMode(selectedTeamSize!!, selectedIndexInTeam!!)
dismiss()
}
setOnShowListener { updateOkButtonEnablement() }
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
setView(binding.root)
}
private fun updateOkButtonEnablement() {
getButton(BUTTON_POSITIVE)?.isEnabled = selectedTeamSize != null && selectedIndexInTeam != null
}
private fun parseTeamSize(string: String): Int? {
return try {
val number = Integer.parseInt(string)
if (number in 2..MAX_TEAM_SIZE) number else null
} catch (e: NumberFormatException) { null }
}
}
| gpl-3.0 | a19b65f67db73b1ebfb9be4134ec7b0f | 36.75 | 103 | 0.679679 | 4.938038 | false | false | false | false |
the-obsidian/DiscourseGroupSync | src/main/kotlin/gg/obsidian/discoursegroupsync/UUIDHelper.kt | 1 | 708 | package gg.obsidian.discoursegroupsync
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import org.json.JSONObject
import java.util.*
object UUIDHelper {
val PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"
val httpClient = OkHttpClient()
fun uuidToUsername(uuid: UUID): String {
val url = PROFILE_URL + uuid.toString().replace("-", "")
val request = Request.Builder().url(url).get().build();
val response = httpClient.newCall(request).execute()
val body = JSONObject(response.body().string())
if (body.has("error")) {
return ""
}
return body.getString("name")
}
}
| mit | bfe140b1229a3fc9e460157fe6554bc8 | 27.32 | 83 | 0.65678 | 4.140351 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/viewModel/ViewPopularUsersViewModel.kt | 1 | 2487 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.viewModel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.toshi.R
import com.toshi.manager.RecipientManager
import com.toshi.model.local.User
import com.toshi.model.network.user.UserType
import com.toshi.util.SingleLiveEvent
import com.toshi.view.BaseApplication
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
class ViewPopularUsersViewModel(
userType: UserType,
searchQuery: String?,
private val recipientManager: RecipientManager = BaseApplication.get().recipientManager
) : ViewModel() {
private val subscriptions by lazy { CompositeSubscription() }
val popularUsers by lazy { MutableLiveData<List<User>>() }
val error by lazy { SingleLiveEvent<Int>() }
val isLoading by lazy { MutableLiveData<Boolean>() }
init {
getPopularUsers(userType, searchQuery)
}
private fun getPopularUsers(userType: UserType, searchQuery: String?) {
val searchPopularUsers = if (searchQuery != null) recipientManager.searchForUsersWithQuery(searchQuery)
else recipientManager.searchForUsersWithType(userType.name.toLowerCase())
val sub = searchPopularUsers
.map { it.results }
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isLoading.value = true }
.doAfterTerminate { isLoading.value = false }
.subscribe(
{ popularUsers.value = it },
{ error.value = R.string.error_fetching_users }
)
subscriptions.add(sub)
}
override fun onCleared() {
super.onCleared()
subscriptions.clear()
}
} | gpl-3.0 | 409c7c8e5075f14d1adcd2b2ada40ca1 | 36.134328 | 111 | 0.687977 | 4.657303 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCProductReviewModel.kt | 2 | 3169 | package org.wordpress.android.fluxc.model
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.RawConstraints
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.persistence.WellSqlConfig
@Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE)
@RawConstraints(
"FOREIGN KEY(LOCAL_SITE_ID) REFERENCES SiteModel(_id) ON DELETE CASCADE",
"UNIQUE (REMOTE_PRODUCT_REVIEW_ID, REMOTE_PRODUCT_ID, LOCAL_SITE_ID) ON CONFLICT REPLACE"
)
data class WCProductReviewModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
companion object {
private val json by lazy { Gson() }
}
@Column var localSiteId = 0
/**
* Remote unique identifier for this product review
*/
@Column var remoteProductReviewId = 0L // The unique ID for this product review on the server
/**
* Unique identifier for the product this review belongs to
*/
@Column var remoteProductId = 0L
/**
* The date the review was created, in UTC, ISO8601 formatted
*/
@Column var dateCreated = ""
/**
* Status of the review. Options: approved, hold, spam, unspam, trash, and untrash.
*/
@Column var status = ""
/**
* Name of the reviewer
*/
@SerializedName("reviewer")
@Column var reviewerName = ""
/**
* Reviewer email address
*/
@Column var reviewerEmail = ""
/**
* The content of the review
*/
@Column var review = ""
/**
* Review rating (0 to 5)
*/
@Column var rating = 0
/**
* True if the reviewer purchased the product being reviewed, else false
*/
@Column var verified = false
@SerializedName("reviewer_avatar_urls")
@Column var reviewerAvatarsJson = ""
/**
* A mapping of reviewer avatar URL's by their size:
* <ul>
* <li>SMALL = 24</li>
* <li>MEDIUM = 48</li>
* <li>LARGE = 95</li>
* </ul>
*/
val reviewerAvatarUrlBySize: Map<AvatarSize, String> by lazy {
val result = mutableMapOf<AvatarSize, String>()
if (reviewerAvatarsJson.isNotEmpty()) {
json.fromJson(reviewerAvatarsJson, JsonElement::class.java).asJsonObject.entrySet().forEach {
result[AvatarSize.getAvatarSizeForValue(it.key.toInt())] = it.value.asString
}
}
result
}
override fun setId(id: Int) {
this.id = id
}
override fun getId() = this.id
enum class AvatarSize(val size: Int) {
SMALL(24), MEDIUM(48), LARGE(96);
companion object {
fun getAvatarSizeForValue(size: Int): AvatarSize {
return when (size) {
SMALL.size -> SMALL
MEDIUM.size -> MEDIUM
LARGE.size -> LARGE
else -> MEDIUM
}
}
}
}
}
| gpl-2.0 | 4bc2781e47fbb03b92f6f6f55ef0d458 | 27.294643 | 105 | 0.617861 | 4.329235 | false | false | false | false |
aCoder2013/general | general-gossip/src/main/java/com/song/general/gossip/net/handler/GossipDigestSynMessageHandler.kt | 1 | 1348 | package com.song.general.gossip.net.handler
import com.song.general.gossip.Gossip
import com.song.general.gossip.GossipAction
import com.song.general.gossip.message.GossipDigestSynMessage
import com.song.general.gossip.net.Message
import com.song.general.gossip.utils.GsonUtils
import org.slf4j.LoggerFactory
/**
* Created by song on 2017/9/3.
*/
class GossipDigestSynMessageHandler(g: Gossip) : AbstractMessageHandler(g) {
override fun handleMessage(message: Message) {
logger.trace("Received message ${GsonUtils.toJson(message)}")
val from = message.from
if (gossip.localSocketAddress == from) {
logger.warn("Ignore message {${GsonUtils.toJson(message)}} sending from itself.")
return
}
if (message.createTime < gossip.firstSynSendAt) {
logger.warn("Ignore message received before startup.")
return
}
val digestSynMessage = message.payload as GossipDigestSynMessage
val gossipDigestAckMessage = gossip.mergeDigest(digestSynMessage.gossipDigests)
val msg = Message(gossip.localSocketAddress, GossipAction.GOSSIP_ACK, gossipDigestAckMessage)
gossip.messageClient.sendOneWay(from, msg)
}
companion object {
private val logger = LoggerFactory.getLogger(GossipDigestSynMessage::class.java)
}
} | apache-2.0 | 8fd09fb0f9f5b7f47f57595b56cc1d95 | 37.542857 | 101 | 0.718843 | 4.048048 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/util/Container.kt | 1 | 543 | package nl.hannahsten.texifyidea.util
/**
* @author Hannah Schellekens
*/
open class Container<T> @JvmOverloads constructor(
/**
* The item that is contained in the container (Duh).
*/
var item: T? = null
) {
override fun toString() = "Container[$item]"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Container<*>) return false
if (item != other.item) return false
return true
}
override fun hashCode() = item?.hashCode() ?: 0
} | mit | 46d3b7e5b72461bf920bf854165b0b16 | 22.652174 | 57 | 0.609576 | 4.176923 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/AnticipatedShowsFragment.kt | 1 | 5368 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.suggestions.shows
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.fragment.SwipeRefreshRecyclerFragment
import net.simonvt.cathode.entity.Show
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import net.simonvt.cathode.ui.ShowsNavigationListener
import net.simonvt.cathode.ui.lists.ListDialog
import net.simonvt.cathode.ui.shows.ShowDescriptionAdapter
import javax.inject.Inject
class AnticipatedShowsFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val showScheduler: ShowTaskScheduler
) : SwipeRefreshRecyclerFragment<ShowDescriptionAdapter.ViewHolder>(),
ListDialog.Callback, ShowDescriptionAdapter.ShowCallbacks {
private lateinit var viewModel: AnticipatedShowsViewModel
private var showsAdapter: ShowDescriptionAdapter? = null
private lateinit var navigationListener: ShowsNavigationListener
private lateinit var sortBy: SortBy
private var columnCount: Int = 0
private var scrollToTop: Boolean = false
enum class SortBy(val key: String, val sortOrder: String) {
ANTICIPATED("anticipated", Shows.SORT_ANTICIPATED), TITLE("title", Shows.SORT_TITLE);
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: ANTICIPATED
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
sortBy = SortBy.fromValue(
Settings.get(requireContext())
.getString(Settings.Sort.SHOW_ANTICIPATED, SortBy.ANTICIPATED.key)!!
)
columnCount = resources.getInteger(R.integer.showsColumns)
setTitle(R.string.title_shows_anticipated)
setEmptyText(R.string.shows_loading_anticipated)
viewModel =
ViewModelProviders.of(this, viewModelFactory).get(AnticipatedShowsViewModel::class.java)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.anticipated.observe(this, Observer { shows -> setShows(shows) })
}
override fun getColumnCount(): Int {
return columnCount
}
override fun onRefresh() {
viewModel.refresh()
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort_by -> {
val items = arrayListOf<ListDialog.Item>()
items.add(ListDialog.Item(R.id.sort_anticipated, R.string.sort_anticipated))
items.add(ListDialog.Item(R.id.sort_title, R.string.sort_title))
ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this)
.show(requireFragmentManager(), DIALOG_SORT)
return true
}
else -> return super.onMenuItemClick(item)
}
}
override fun onItemSelected(id: Int) {
when (id) {
R.id.sort_viewers -> if (sortBy != SortBy.ANTICIPATED) {
sortBy = SortBy.ANTICIPATED
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_ANTICIPATED, SortBy.ANTICIPATED.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
R.id.sort_title -> if (sortBy != SortBy.TITLE) {
sortBy = SortBy.TITLE
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_ANTICIPATED, SortBy.TITLE.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
}
}
override fun onShowClick(showId: Long, title: String?, overview: String?) {
navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED)
}
override fun setIsInWatchlist(showId: Long, inWatchlist: Boolean) {
showScheduler.setIsInWatchlist(showId, inWatchlist)
}
private fun setShows(shows: List<Show>) {
if (showsAdapter == null) {
showsAdapter = ShowDescriptionAdapter(requireContext(), this, false)
adapter = showsAdapter
return
}
showsAdapter!!.setList(shows)
if (scrollToTop) {
recyclerView.scrollToPosition(0)
scrollToTop = false
}
}
companion object {
private const val DIALOG_SORT =
"net.simonvt.cathode.ui.suggestions.shows.AnticipatedShowsFragment.sortDialog"
}
}
| apache-2.0 | 2cf3a3f6e95b0a93ce28d89254a5f52b | 31.731707 | 94 | 0.725596 | 4.315113 | false | false | false | false |
google/modernstorage | permissions/src/main/java/com/google/modernstorage/permissions/StoragePermissions.kt | 1 | 9148 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.modernstorage.permissions
import android.Manifest.permission.MANAGE_EXTERNAL_STORAGE
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import androidx.core.content.ContextCompat
class StoragePermissions(private val context: Context) {
companion object {
private const val READ_EXTERNAL_STORAGE_MASK = 0b0001
private const val WRITE_EXTERNAL_STORAGE_MASK = 0b0011
private const val SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK = 0b0100
private const val MANAGE_EXTERNAL_STORAGE_MASK = 0b1111
private fun getPermissionMask(
action: Action,
types: List<FileType>,
createdBy: CreatedBy
): Int {
var permissionMask = 0
when (createdBy) {
CreatedBy.Self -> {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
permissionMask = when (action) {
Action.READ -> permissionMask or READ_EXTERNAL_STORAGE_MASK
Action.READ_AND_WRITE -> permissionMask or WRITE_EXTERNAL_STORAGE_MASK
}
}
}
CreatedBy.AllApps -> {
if (types.contains(FileType.Image)) {
permissionMask = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
permissionMask or SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK
}
else -> {
when (action) {
Action.READ -> permissionMask or READ_EXTERNAL_STORAGE_MASK
Action.READ_AND_WRITE -> permissionMask or WRITE_EXTERNAL_STORAGE_MASK
}
}
}
}
if (types.contains(FileType.Video)) {
permissionMask = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
permissionMask or SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK
}
else -> {
when (action) {
Action.READ -> permissionMask or READ_EXTERNAL_STORAGE_MASK
Action.READ_AND_WRITE -> permissionMask or WRITE_EXTERNAL_STORAGE_MASK
}
}
}
}
if (types.contains(FileType.Audio)) {
permissionMask = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
permissionMask or SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK
}
else -> {
when (action) {
Action.READ -> permissionMask or READ_EXTERNAL_STORAGE_MASK
Action.READ_AND_WRITE -> permissionMask or WRITE_EXTERNAL_STORAGE_MASK
}
}
}
}
if (types.contains(FileType.Document)) {
permissionMask = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
permissionMask or MANAGE_EXTERNAL_STORAGE_MASK
}
else -> {
when (action) {
Action.READ -> permissionMask or READ_EXTERNAL_STORAGE_MASK
Action.READ_AND_WRITE -> permissionMask or WRITE_EXTERNAL_STORAGE_MASK
}
}
}
}
}
}
return permissionMask
}
/**
* Get list of required permissions for given usage
*/
@JvmStatic
fun getPermissions(
action: Action,
types: List<FileType>,
createdBy: CreatedBy
): List<String> {
val permissionMask = getPermissionMask(action, types, createdBy)
val requiredPermissions = mutableListOf<String>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && permissionMask and MANAGE_EXTERNAL_STORAGE_MASK == MANAGE_EXTERNAL_STORAGE_MASK) {
requiredPermissions.add(MANAGE_EXTERNAL_STORAGE)
} else {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && permissionMask and MANAGE_EXTERNAL_STORAGE_MASK == MANAGE_EXTERNAL_STORAGE_MASK -> requiredPermissions.add(
MANAGE_EXTERNAL_STORAGE
)
permissionMask and SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK == SCOPED_STORAGE_READ_EXTERNAL_STORAGE_MASK -> requiredPermissions.add(
READ_EXTERNAL_STORAGE
)
permissionMask and WRITE_EXTERNAL_STORAGE_MASK == WRITE_EXTERNAL_STORAGE_MASK -> requiredPermissions.add(
WRITE_EXTERNAL_STORAGE
)
permissionMask and READ_EXTERNAL_STORAGE_MASK == READ_EXTERNAL_STORAGE_MASK -> requiredPermissions.add(
READ_EXTERNAL_STORAGE
)
}
}
return requiredPermissions
}
/**
* Get list of required permissions for given read usage
*/
@Deprecated(
"Use the new getPermissions() method",
ReplaceWith("getPermissions(Action.READ, types, createdBy)"),
DeprecationLevel.WARNING
)
fun getReadFilesPermissions(types: List<FileType>, createdBy: CreatedBy): List<String> {
return getPermissions(Action.READ, types, createdBy)
}
/**
* Get list of required permissions for given read usage
*/
@Deprecated(
"Use the new getPermissions() method",
ReplaceWith("getPermissions(Action.READ_AND_WRITE, types, createdBy)"),
DeprecationLevel.WARNING
)
fun getReadAndWriteFilesPermissions(
types: List<FileType>,
createdBy: CreatedBy
): List<String> {
return getPermissions(Action.READ_AND_WRITE, types, createdBy)
}
}
/**
* Type of files
*/
enum class FileType {
Image, Video, Audio, Document
}
/**
* Type of file ownership
*/
enum class CreatedBy {
Self, AllApps
}
/**
* Type of file actions
*/
enum class Action {
READ, READ_AND_WRITE
}
private fun hasPermission(permission: String): Boolean {
return ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
}
/**
* Check if app can access shared files
*/
fun hasAccess(action: Action, types: List<FileType>, createdBy: CreatedBy): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager()) {
return true
}
return getPermissions(action, types, createdBy).all { hasPermission(it) }
}
/**
* Check if app can read shared files
*/
@Deprecated(
"Use the new hasAccess() method",
ReplaceWith("hasAccess(Action.READ, types, createdBy)"),
DeprecationLevel.WARNING
)
fun canReadFiles(types: List<FileType>, createdBy: CreatedBy): Boolean {
return hasAccess(Action.READ, types, createdBy)
}
/**
* Check if app can read and write shared files
*/
@Deprecated(
"Use the new hasAccess() method",
ReplaceWith("hasAccess(Action.READ_AND_WRITE, types, createdBy)"),
DeprecationLevel.WARNING
)
fun canReadAndWriteFiles(types: List<FileType>, createdBy: CreatedBy): Boolean {
return hasAccess(Action.READ_AND_WRITE, types, createdBy)
}
}
| apache-2.0 | 90c5e3bcb80b1333c54cb67312638a76 | 37.762712 | 177 | 0.52711 | 5.419431 | false | false | false | false |
hartwigmedical/hmftools | teal/src/main/kotlin/com/hartwig/hmftools/teal/breakend/BreakEndEvidenceFilter.kt | 1 | 3353 | package com.hartwig.hmftools.teal.breakend
import kotlin.math.min
object BreakEndEvidenceFilter
{
const val MAX_GERMLINE_SUPPORT_COUNT = 5
const val MAX_GERMLINE_SUPPORT_RATIO = 0.02
const val MIN_TELOMERIC_LENGTH = 20
const val MIN_ANCHOR_LENGTH = 50
const val MIN_SPLIT_READ_COUNT = 3
const val MIN_DISCORDANT_PAIR_COUNT = 1
const val MAX_COHORT_FREQ = 1000000
const val MIN_TUMOR_MAPQ = 300
private val supportSplitReadTypes = arrayOf(
Pair(Fragment.AlignedReadType.SPLIT_READ_TELOMERIC, Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC),
Pair(Fragment.AlignedReadType.SPLIT_READ_TELOMERIC, Fragment.PairedReadType.DISCORDANT_PAIR_NOT_TELOMERIC),
Pair(Fragment.AlignedReadType.SPLIT_READ_TELOMERIC, Fragment.PairedReadType.NOT_DISCORDANT),
Pair(Fragment.AlignedReadType.SPLIT_READ_NOT_TELOMERIC, Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC))
private val supportDiscordantPairTypes = arrayOf(
Pair(Fragment.AlignedReadType.DISCORDANT_PAIR, Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC),
Pair(Fragment.AlignedReadType.SPLIT_READ_TELOMERIC, Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC),
Pair(Fragment.AlignedReadType.SPLIT_READ_NOT_TELOMERIC, Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC))
fun getFilterReasons(evidence: TelomericBreakEndEvidence) : List<String>
{
val filterList = ArrayList<String>()
if (evidence.tumorSupport != null)
{
if (evidence.tumorSupport.key.isDuplicate)
{
filterList.add("duplicate")
}
if (evidence.tumorSupport.longestTelomereSegment == null ||
evidence.tumorSupport.longestTelomereSegment!!.length < MIN_TELOMERIC_LENGTH)
{
filterList.add("minTelomericLength")
}
if (evidence.tumorSupport.longestSplitReadAlignLength < MIN_ANCHOR_LENGTH)
{
filterList.add("minAnchorLength")
}
if (evidence.tumorSupport.fragmentCount({ f -> supportSplitReadTypes.contains(Pair(f.alignedReadType, f.pairedReadType)) }) < MIN_SPLIT_READ_COUNT)
{
filterList.add("minSplitReads")
}
if (evidence.tumorSupport.fragmentCount({ f -> supportDiscordantPairTypes.contains(Pair(f.alignedReadType, f.pairedReadType)) }) < MIN_DISCORDANT_PAIR_COUNT)
{
filterList.add("minDiscordantPairs")
}
if (evidence.tumorSupport.sumMapQ({ f -> Pair(f.alignedReadType, f.pairedReadType) in Fragment.supportFragTypes }) < MIN_TUMOR_MAPQ)
{
filterList.add("minTumorMAPQ")
}
}
else
{
filterList.add("notInTumor")
}
if (evidence.germlineSupport != null)
{
val tumorSupportFragCount = evidence.tumorSupport?.supportFragmentCount() ?: 0
if (evidence.germlineSupport.supportFragmentCount() >
min(MAX_GERMLINE_SUPPORT_COUNT.toDouble(), tumorSupportFragCount * MAX_GERMLINE_SUPPORT_RATIO))
{
filterList.add("maxGermlineSupport")
}
}
if (filterList.isEmpty())
filterList.add("PASS")
return filterList
}
}
| gpl-3.0 | f390a43cb606a5e6eb7d2c5b4735422f | 38.916667 | 169 | 0.651357 | 3.742188 | false | false | false | false |
FHannes/intellij-community | python/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt | 3 | 4854 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.typing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.packaging.PyPIPackageUtil
import com.jetbrains.python.packaging.PyPackageManagers
import com.jetbrains.python.packaging.PyPackageUtil
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.PythonSdkType
import java.io.File
/**
* Utilities for managing the local copy of the typeshed repository.
*
* The original Git repo is located [here](https://github.com/JetBrains/typeshed).
*
* @author vlan
*/
object PyTypeShed {
private val ONLY_SUPPORTED_PY2_MINOR = 7
private val SUPPORTED_PY3_MINORS = 2..6
// TODO: Warn about unresolved `import typing` but still resolve it internally for type inference
val WHITE_LIST = setOf("typing", "six", "__builtin__", "builtins", "exceptions", "types", "datetime")
private val BLACK_LIST = setOf<String>()
/**
* Returns true if we allow to search typeshed for a stub for [name].
*/
fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean {
val topLevelPackage = name.firstComponent ?: return false
if (topLevelPackage in BLACK_LIST) {
return false
}
if (topLevelPackage !in WHITE_LIST) {
return false
}
if (isInStandardLibrary(root)) {
return true
}
if (isInThirdPartyLibraries(root)) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val pyPIPackage = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: topLevelPackage
val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true
return PyPackageUtil.findPackage(packages, pyPIPackage) != null
}
return false
}
/**
* Returns the list of roots in typeshed for the Python language level of [sdk].
*/
fun findRootsForSdk(sdk: Sdk): List<VirtualFile> {
val level = PythonSdkType.getLanguageLevelForSdk(sdk)
val dir = directory ?: return emptyList()
return findRootsForLanguageLevel(level)
.asSequence()
.map { dir.findFileByRelativePath(it) }
.filterNotNull()
.toList()
}
/**
* Returns the list of roots in typeshed for the specified Python language [level].
*/
fun findRootsForLanguageLevel(level: LanguageLevel): List<String> {
val minors = when (level.major) {
2 -> listOf(ONLY_SUPPORTED_PY2_MINOR)
3 -> SUPPORTED_PY3_MINORS.reversed().filter { it <= level.minor }
else -> return emptyList()
}
return minors.map { "stdlib/${level.major}.$it" } +
listOf("stdlib/${level.major}",
"stdlib/2and3",
"third_party/${level.major}",
"third_party/2and3")
}
/**
* Checks if the [file] is located inside the typeshed directory.
*/
fun isInside(file: VirtualFile): Boolean {
val dir = directory
return dir != null && VfsUtilCore.isAncestor(dir, file, true)
}
/**
* The actual typeshed directory.
*/
val directory: VirtualFile? by lazy {
val path = directoryPath ?: return@lazy null
StandardFileSystems.local().findFileByPath(path)
}
val directoryPath: String?
get() {
val paths = listOf("${PathManager.getConfigPath()}/typeshed",
"${PathManager.getConfigPath()}/../typeshed",
PythonHelpersLocator.getHelperPath("typeshed"))
return paths.asSequence()
.filter { File(it).exists() }
.firstOrNull()
}
/**
* A shallow check for a [file] being located inside the typeshed third-party stubs.
*/
fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path
fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path
private val LanguageLevel.major: Int
get() = this.version / 10
private val LanguageLevel.minor: Int
get() = this.version % 10
}
| apache-2.0 | c7186fc995cb8a01574515324fc4a390 | 33.920863 | 103 | 0.693655 | 4.333929 | false | false | false | false |
FHannes/intellij-community | java/java-impl/src/com/intellij/codeInspection/javaDoc/JavadocHtmlLintAnnotator.kt | 6 | 8094 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.javaDoc
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.intention.EmptyIntentionAction
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.SimpleJavaParameters
import com.intellij.execution.util.ExecUtil
import com.intellij.lang.annotation.Annotation
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.JdkUtil
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.util.PsiTreeUtil
import com.sun.tools.doclint.DocLint
import java.io.File
class JavadocHtmlLintAnnotator : ExternalAnnotator<JavadocHtmlLintAnnotator.Info, JavadocHtmlLintAnnotator.Result>() {
data class Info(val file: PsiFile)
data class Anno(val row: Int, val col: Int, val error: Boolean, val message: String)
data class Result(val annotations: List<Anno>)
override fun getPairedBatchInspectionShortName() = JavadocHtmlLintInspection.SHORT_NAME
override fun collectInformation(file: PsiFile): Info? =
if (isJava8SourceFile(file) && "/**" in file.text) Info(file) else null
override fun doAnnotate(collectedInfo: Info): Result? {
val file = collectedInfo.file.virtualFile!!
val copy = createTempFile(collectedInfo.file.text.toByteArray(file.charset))
try {
val command = toolCommand(file, collectedInfo.file.project, copy)
val output = ExecUtil.execAndGetOutput(command)
if (output.exitCode != 0) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
if (log.isDebugEnabled) log.debug("${file}: ${output.exitCode}, ${output.stderr}")
return null
}
val annotations = parse(output.stdoutLines)
return if (annotations.isNotEmpty()) Result(annotations) else null
}
catch (e: Exception) {
val log = Logger.getInstance(JavadocHtmlLintAnnotator::class.java)
log.debug(file.path, e)
return null
}
finally {
FileUtil.delete(copy)
}
}
override fun apply(file: PsiFile, annotationResult: Result, holder: AnnotationHolder) {
val text = file.text
val offsets = text.foldIndexed(mutableListOf(0)) { i, offsets, c -> if (c == '\n') offsets += (i + 1); offsets }
for ((row, col, error, message) in annotationResult.annotations) {
if (row < offsets.size) {
val offset = offsets[row] + col
val element = file.findElementAt(offset)
if (element != null && PsiTreeUtil.getParentOfType(element, PsiDocComment::class.java) != null) {
val range = adjust(element, text, offset)
val description = StringUtil.capitalize(message)
val annotation = if (error) holder.createErrorAnnotation(range, description) else holder.createWarningAnnotation(range, description)
registerFix(annotation)
}
}
}
}
//<editor-fold desc="Helpers">
private val key = lazy { HighlightDisplayKey.find(JavadocHtmlLintInspection.SHORT_NAME) }
private val lintOptions = "${DocLint.XMSGS_CUSTOM_PREFIX}html/private,accessibility/private"
private val lintPattern = "^.+:(\\d+):\\s+(error|warning):\\s+(.+)$".toPattern()
private fun isJava8SourceFile(file: PsiFile) =
file is PsiJavaFile && file.languageLevel.isAtLeast(LanguageLevel.JDK_1_8) &&
file.virtualFile != null && ProjectFileIndex.SERVICE.getInstance(file.project).isInSourceContent(file.virtualFile)
private fun createTempFile(bytes: ByteArray): File {
val tempFile = FileUtil.createTempFile(File(PathManager.getTempPath()), "javadocHtmlLint", ".java")
tempFile.writeBytes(bytes)
return tempFile
}
private fun toolCommand(file: VirtualFile, project: Project, copy: File): GeneralCommandLine {
val parameters = SimpleJavaParameters()
val jdk = findJdk(file, project)
parameters.jdk = jdk
if (!JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_9)) {
val toolsJar = FileUtil.findFirstThatExist("${jdk.homePath}/lib/tools.jar", "${jdk.homePath}/../lib/tools.jar")
if (toolsJar != null) parameters.classPath.add(toolsJar.path)
}
parameters.charset = file.charset
parameters.vmParametersList.addProperty("user.language", "en")
parameters.mainClass = DocLint::class.qualifiedName
parameters.programParametersList.add(lintOptions)
parameters.programParametersList.add(copy.path)
return parameters.toCommandLine()
}
private fun findJdk(file: VirtualFile, project: Project): Sdk {
val rootManager = ProjectRootManager.getInstance(project)
val module = rootManager.fileIndex.getModuleForFile(file)
if (module != null) {
val sdk = ModuleRootManager.getInstance(module).sdk
if (isJdk8(sdk)) return sdk!!
}
val sdk = rootManager.projectSdk
if (isJdk8(sdk)) return sdk!!
return JavaAwareProjectJdkTableImpl.getInstanceEx().internalJdk
}
private fun isJdk8(sdk: Sdk?) =
sdk != null && JavaSdkUtil.isJdkAtLeast(sdk, JavaSdkVersion.JDK_1_8) && JdkUtil.checkForJre(sdk.homePath!!)
private fun parse(lines: List<String>): List<Anno> {
val result = mutableListOf<Anno>()
val i = lines.iterator()
while (i.hasNext()) {
val line = i.next()
val matcher = lintPattern.matcher(line)
if (matcher.matches() && i.hasNext() && !i.next().isEmpty() && i.hasNext()) {
val row = matcher.group(1).toInt() - 1
val col = i.next().indexOf('^')
val error = matcher.group(2) == "error"
val message = matcher.group(3)
result += Anno(row, col, error, message)
}
}
return result
}
private fun adjust(element: PsiElement, text: String, offset: Int): TextRange {
val range = element.textRange
if (text[offset] == '<') {
val right = text.indexOf('>', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset] == '&') {
val right = text.indexOf(';', offset)
if (right > 0) return TextRange(offset, Integer.min(right + 1, range.endOffset))
}
else if (text[offset].isLetter() && !text[offset - 1].isLetter()) {
var right = offset + 1
while (text[right].isLetter() && right <= range.endOffset) right++
return TextRange(offset, right)
}
return range
}
private fun registerFix(annotation: Annotation) =
annotation.registerFix(EmptyIntentionAction(InspectionsBundle.message("inspection.javadoc.lint.display.name")), null, key.value)
//</editor-fold>
} | apache-2.0 | 2f3c5ed26aad45b4d0b2bb983c6fb9be | 38.681373 | 142 | 0.722881 | 4.170015 | false | false | false | false |
vsouhrada/kotlin-anko-demo | app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/app/FiboApp.kt | 1 | 1607 | package com.vsouhrada.kotlin.android.anko.fibo.app
import android.app.Application
import com.vsouhrada.apps.fibo.core.db.bl.IUserBL
import com.vsouhrada.apps.fibo.injection.module.ApplicationModule
import com.vsouhrada.kotlin.android.anko.fibo.core.session.ISessionManager
import com.vsouhrada.kotlin.android.anko.fibo.core.session.model.UserInfoPrefModel
import com.vsouhrada.kotlin.android.anko.fibo.injection.component.ApplicationComponent
import com.vsouhrada.kotlin.android.anko.fibo.injection.component.DaggerApplicationComponent
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import javax.inject.Inject
/**
* @author vsouhrada
* @since 0.1.0
*/
class FiboApp : Application(), AnkoLogger {
@Inject lateinit var sessionManager: ISessionManager
@Inject lateinit var userBL: IUserBL
companion object {
@JvmStatic lateinit var applicationComponent: ApplicationComponent
private var instance: Application? = null
fun instance() = instance!!
}
override fun onCreate() {
super.onCreate()
instance = this
initDaggerComponent()
val storedUserId = UserInfoPrefModel.userId
if (storedUserId != -1) {
val user = userBL.getUserById(UserInfoPrefModel.userId)
if (user != null) {
sessionManager.putUserOnSession(user)
} else {
error { "User with id=$storedUserId not found in database!!!" }
}
}
}
private fun initDaggerComponent() {
applicationComponent = DaggerApplicationComponent.builder().applicationModule(ApplicationModule((this))).build()
applicationComponent.inject(this)
}
} | apache-2.0 | d43285b15c874e0054a1b91dab01f0bc | 31.16 | 116 | 0.757934 | 4.296791 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/octo/config/OctoRtpSender.kt | 1 | 4633 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.octo.config
import org.jitsi.nlj.Event
import org.jitsi.nlj.Features
import org.jitsi.nlj.PacketHandler
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.RtpSender
import org.jitsi.nlj.rtcp.KeyframeRequester
import org.jitsi.nlj.rtp.TransportCcEngine
import org.jitsi.nlj.rtp.bandwidthestimation.BandwidthEstimator
import org.jitsi.nlj.srtp.SrtpTransformers
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.stats.PacketStreamStats
import org.jitsi.nlj.transform.NodeStatsVisitor
import org.jitsi.nlj.transform.node.ConsumerNode
import org.jitsi.nlj.transform.node.outgoing.OutgoingStatisticsSnapshot
import org.jitsi.nlj.util.ReadOnlyStreamInformationStore
import org.jitsi.nlj.util.bps
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.createChildLogger
import org.jitsi.videobridge.util.ByteBufferPool
import java.util.concurrent.atomic.AtomicBoolean
/**
* An [RtpSender] for all data we want to send out over the Octo link(s).
*/
class OctoRtpSender(
readOnlyStreamInformationStore: ReadOnlyStreamInformationStore,
parentLogger: Logger
) : RtpSender() {
private val logger = createChildLogger(parentLogger)
private val running = AtomicBoolean(true)
/**
* A handler for packets to be sent out onto the network
*/
private var outgoingPacketHandler: PacketHandler? = null
private val outputPipelineTerminationNode = object : ConsumerNode("Octo sender termination node") {
override fun consume(packetInfo: PacketInfo) {
outgoingPacketHandler?.processPacket(packetInfo) ?: packetDiscarded(packetInfo)
}
override fun trace(f: () -> Unit) = f.invoke()
}
/**
* The [KeyframeRequester] used for all remote Octo endpoints
*/
private val keyframeRequester = KeyframeRequester(readOnlyStreamInformationStore, logger).apply {
attach(outputPipelineTerminationNode)
}
/**
* Add a handler to handle outgoing Octo packets
*/
override fun onOutgoingPacket(handler: PacketHandler) {
outgoingPacketHandler = handler
}
override fun doProcessPacket(packetInfo: PacketInfo) {
if (running.get()) {
outgoingPacketHandler?.processPacket(packetInfo)
} else {
ByteBufferPool.returnBuffer(packetInfo.packet.buffer)
}
}
private fun doSend(packetInfo: PacketInfo): Boolean {
outgoingPacketHandler?.processPacket(packetInfo)
return true
}
override fun requestKeyframe(mediaSsrc: Long?) {
keyframeRequester.requestKeyframe(mediaSsrc)
}
override fun sendProbing(mediaSsrcs: Collection<Long>, numBytes: Int): Int = 0
override fun setSrtpTransformers(srtpTransformers: SrtpTransformers) {}
override fun stop() {
running.set(false)
}
override fun tearDown() {
}
override val bandwidthEstimator: BandwidthEstimator
get() = TODO("Not implemented")
override fun handleEvent(event: Event) {}
override fun onRttUpdate(newRttMs: Double) {}
override fun isFeatureEnabled(feature: Features): Boolean {
TODO("Not yet implemented")
}
override fun setFeature(feature: Features, enabled: Boolean) {
TODO("Not yet implemented")
}
override fun getPacketStreamStats(): PacketStreamStats.Snapshot = PacketStreamStats.Snapshot(0.bps, 0, 0, 0)
override fun getTransportCcEngineStats(): TransportCcEngine.StatisticsSnapshot =
TransportCcEngine.StatisticsSnapshot(0, 0, 0, 0, 0, 0)
override fun getStreamStats(): OutgoingStatisticsSnapshot = OutgoingStatisticsSnapshot(mapOf())
override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock("Octo sender").apply {
addBlock(super.getNodeStats())
NodeStatsVisitor(this).reverseVisit(outputPipelineTerminationNode)
}
fun getDebugState(): OrderedJsonObject = OrderedJsonObject().apply {
putAll(getNodeStats().toJson())
}
}
| apache-2.0 | 9347c0e26047393fb332027e9368d305 | 32.817518 | 112 | 0.732355 | 4.416587 | false | false | false | false |
didi/DoraemonKit | Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/event/Position.kt | 1 | 414 | package com.didichuxing.doraemonkit.kit.test.event
/**
* didi Create on 2022/4/13 .
*
* Copyright (c) 2022/4/13 by didiglobal.com.
*
* @author <a href="[email protected]">zhangjun</a>
* @version 1.0
* @Date 2022/4/13 3:07 下午
* @Description 用一句话说明文件功能
*/
data class Position(
val width: Long = -1,
val height: Long = -1,
val top: Long = -1,
val left: Long = -1
)
| apache-2.0 | df24ef9857f74dba0757757e051132ab | 20.666667 | 53 | 0.628205 | 2.910448 | false | true | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/command/service/DefaultCardService.kt | 1 | 4083 | package com.flexpoker.table.command.service
import com.flexpoker.table.command.Card
import com.flexpoker.table.command.CardRank
import com.flexpoker.table.command.CardSuit
import com.flexpoker.table.command.CardsUsedInHand
import com.flexpoker.table.command.FlopCards
import com.flexpoker.table.command.PocketCards
import com.flexpoker.table.command.RiverCard
import com.flexpoker.table.command.TurnCard
import org.springframework.stereotype.Service
@Service
class DefaultCardService : CardService {
override fun createShuffledDeck(): List<Card> {
return deckOfCards.shuffled()
}
override fun createCardsUsedInHand(cards: List<Card>, numberOfPlayers: Int): CardsUsedInHand {
val flopCardsIndex = numberOfPlayers * 2 + 1
val flopCards = FlopCards(cards[flopCardsIndex], cards[flopCardsIndex + 1], cards[flopCardsIndex + 2])
val turnCard = TurnCard(cards[flopCardsIndex + 4])
val riverCard = RiverCard(cards[flopCardsIndex + 6])
val pocketCards = (0 until numberOfPlayers).map { PocketCards(cards[it], cards[it + numberOfPlayers]) }
return CardsUsedInHand(flopCards, turnCard, riverCard, pocketCards)
}
companion object {
private val deckOfCards: List<Card> = listOf(
Card(0, CardRank.TWO, CardSuit.HEARTS),
Card(1, CardRank.THREE, CardSuit.HEARTS),
Card(2, CardRank.FOUR, CardSuit.HEARTS),
Card(3, CardRank.FIVE, CardSuit.HEARTS),
Card(4, CardRank.SIX, CardSuit.HEARTS),
Card(5, CardRank.SEVEN, CardSuit.HEARTS),
Card(6, CardRank.EIGHT, CardSuit.HEARTS),
Card(7, CardRank.NINE, CardSuit.HEARTS),
Card(8, CardRank.TEN, CardSuit.HEARTS),
Card(9, CardRank.JACK, CardSuit.HEARTS),
Card(10, CardRank.QUEEN, CardSuit.HEARTS),
Card(11, CardRank.KING, CardSuit.HEARTS),
Card(12, CardRank.ACE, CardSuit.HEARTS),
Card(13, CardRank.TWO, CardSuit.SPADES),
Card(14, CardRank.THREE, CardSuit.SPADES),
Card(15, CardRank.FOUR, CardSuit.SPADES),
Card(16, CardRank.FIVE, CardSuit.SPADES),
Card(17, CardRank.SIX, CardSuit.SPADES),
Card(18, CardRank.SEVEN, CardSuit.SPADES),
Card(19, CardRank.EIGHT, CardSuit.SPADES),
Card(20, CardRank.NINE, CardSuit.SPADES),
Card(21, CardRank.TEN, CardSuit.SPADES),
Card(22, CardRank.JACK, CardSuit.SPADES),
Card(23, CardRank.QUEEN, CardSuit.SPADES),
Card(24, CardRank.KING, CardSuit.SPADES),
Card(25, CardRank.ACE, CardSuit.SPADES),
Card(26, CardRank.TWO, CardSuit.DIAMONDS),
Card(27, CardRank.THREE, CardSuit.DIAMONDS),
Card(28, CardRank.FOUR, CardSuit.DIAMONDS),
Card(29, CardRank.FIVE, CardSuit.DIAMONDS),
Card(30, CardRank.SIX, CardSuit.DIAMONDS),
Card(31, CardRank.SEVEN, CardSuit.DIAMONDS),
Card(32, CardRank.EIGHT, CardSuit.DIAMONDS),
Card(33, CardRank.NINE, CardSuit.DIAMONDS),
Card(34, CardRank.TEN, CardSuit.DIAMONDS),
Card(35, CardRank.JACK, CardSuit.DIAMONDS),
Card(36, CardRank.QUEEN, CardSuit.DIAMONDS),
Card(37, CardRank.KING, CardSuit.DIAMONDS),
Card(38, CardRank.ACE, CardSuit.DIAMONDS),
Card(39, CardRank.TWO, CardSuit.CLUBS),
Card(40, CardRank.THREE, CardSuit.CLUBS),
Card(41, CardRank.FOUR, CardSuit.CLUBS),
Card(42, CardRank.FIVE, CardSuit.CLUBS),
Card(43, CardRank.SIX, CardSuit.CLUBS),
Card(44, CardRank.SEVEN, CardSuit.CLUBS),
Card(45, CardRank.EIGHT, CardSuit.CLUBS),
Card(46, CardRank.NINE, CardSuit.CLUBS),
Card(47, CardRank.TEN, CardSuit.CLUBS),
Card(48, CardRank.JACK, CardSuit.CLUBS),
Card(49, CardRank.QUEEN, CardSuit.CLUBS),
Card(50, CardRank.KING, CardSuit.CLUBS),
Card(51, CardRank.ACE, CardSuit.CLUBS)
)
}
} | gpl-2.0 | 43c23dbcb016e6a3e95c04335b62afb3 | 46.488372 | 111 | 0.64144 | 3.45724 | false | false | false | false |
demmonic/KInject | src/main/java/info/demmonic/kinject/preprocessor/PreProcessorTag.kt | 1 | 538 | package info.demmonic.kinject.preprocessor
import info.demmonic.kinject.Transformer
/**
* @author Demmonic
*/
class PreProcessorTag : Transformer {
var identifier: String? = ""
var replacement: String? = ""
constructor() {
}
constructor(identifier: String, replacement: String) {
this.identifier = identifier
this.replacement = replacement
}
fun replace(input: String): String {
val tmp = replacement ?: return input
return input.replace("@{$identifier}", tmp)
}
} | mit | d3c67ccaf6a53d76a4ac8ab5612b6570 | 18.962963 | 58 | 0.648699 | 4.23622 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/information/StatusViewModel.kt | 1 | 7520 | package org.tvheadend.tvhclient.ui.features.information
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import org.tvheadend.data.entity.Channel
import org.tvheadend.data.entity.Input
import org.tvheadend.data.entity.ServerStatus
import org.tvheadend.data.entity.Subscription
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.service.ConnectionService
import org.tvheadend.tvhclient.ui.base.BaseViewModel
import timber.log.Timber
class StatusViewModel(application: Application) : BaseViewModel(application), SharedPreferences.OnSharedPreferenceChangeListener {
val serverStatusLiveData: LiveData<ServerStatus> = appRepository.serverStatusData.liveDataActiveItem
val channelCount: LiveData<Int> = appRepository.channelData.getLiveDataItemCount()
val programCount: LiveData<Int> = appRepository.programData.getLiveDataItemCount()
val timerRecordingCount: LiveData<Int> = appRepository.timerRecordingData.getLiveDataItemCount()
val seriesRecordingCount: LiveData<Int> = appRepository.seriesRecordingData.getLiveDataItemCount()
val completedRecordingCount: LiveData<Int> = appRepository.recordingData.getLiveDataCountByType("completed")
val scheduledRecordingCount: LiveData<Int> = appRepository.recordingData.getLiveDataCountByType("scheduled")
val failedRecordingCount: LiveData<Int> = appRepository.recordingData.getLiveDataCountByType("failed")
val removedRecordingCount: LiveData<Int> = appRepository.recordingData.getLiveDataCountByType("removed")
val showRunningRecordingCount = MediatorLiveData<Boolean>()
val showLowStorageSpace = MediatorLiveData<Boolean>()
var runningRecordingCount = 0
var availableStorageSpace = 0
val subscriptions: LiveData<List<Subscription>> = appRepository.subscriptionData.getLiveDataItems()
val inputs: LiveData<List<Input>> = appRepository.inputData.getLiveDataItems()
private lateinit var discSpaceUpdateTask: Runnable
private val diskSpaceUpdateHandler = Handler(Looper.getMainLooper())
private val defaultNotifyRunningRecordingCount = application.applicationContext.resources.getBoolean(R.bool.pref_default_notify_running_recording_count_enabled)
private val defaultNotifyLowStorageSpace = application.applicationContext.resources.getBoolean(R.bool.pref_default_notify_low_storage_space_enabled)
private val defaultNotifyLowStorageSpaceThreshold = application.applicationContext.resources.getString(R.string.pref_default_low_storage_space_threshold)
init {
Timber.d("Initializing")
// Listen to changes of the recording count. If the count changes to zero or the setting
// to show notifications is disabled, set the value to false to remove any notification
showRunningRecordingCount.addSource(appRepository.recordingData.getLiveDataCountByType("running")) { count ->
Timber.d("Running recording count has changed, checking if notification shall be shown")
runningRecordingCount = count
val enabled = sharedPreferences.getBoolean("notify_running_recording_count_enabled", defaultNotifyRunningRecordingCount)
showRunningRecordingCount.value = enabled && count > 0
}
// Listen to changes of the server status especially the free storage space.
// If the free space is above the threshold or the setting to show
// notifications is disabled, set the value to false to remove any notification
showLowStorageSpace.addSource(serverStatusLiveData) { serverStatus ->
if (serverStatus != null) {
availableStorageSpace = (serverStatus.freeDiskSpace / (1024 * 1024 * 1024)).toInt()
val enabled = sharedPreferences.getBoolean("notify_low_storage_space_enabled", defaultNotifyLowStorageSpace)
val threshold = Integer.valueOf(sharedPreferences.getString("low_storage_space_threshold", defaultNotifyLowStorageSpaceThreshold)!!)
Timber.d("Server status free space has changed to $availableStorageSpace, threshold is $threshold, checking if notification shall be shown")
showLowStorageSpace.value = enabled && availableStorageSpace <= threshold
}
}
discSpaceUpdateTask = Runnable {
val activityManager = application.applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningAppProcessInfo = activityManager.runningAppProcesses?.get(0)
if (runningAppProcessInfo != null
&& runningAppProcessInfo.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Timber.d("Application is in the foreground, starting service to get disk space ")
val intent = Intent(application.applicationContext, ConnectionService::class.java)
intent.action = "getDiskSpace"
application.applicationContext.startService(intent)
}
Timber.d("Restarting disc space update handler in 60s")
diskSpaceUpdateHandler.postDelayed(discSpaceUpdateTask, 60000)
}
onSharedPreferenceChanged(sharedPreferences, "notify_running_recording_count_enabled")
onSharedPreferenceChanged(sharedPreferences, "notify_low_storage_space_enabled")
Timber.d("Registering shared preference change listener")
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onCleared() {
Timber.d("Unregistering shared preference change listener")
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
stopDiskSpaceUpdateHandler()
super.onCleared()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
Timber.d("Shared preference $key has changed")
if (sharedPreferences == null) return
when (key) {
"notifications_enabled" -> {
Timber.d("Setting has changed, checking if running recording count notification shall be shown")
val enabled = sharedPreferences.getBoolean(key, defaultNotifyRunningRecordingCount)
showRunningRecordingCount.value = enabled && runningRecordingCount > 0
}
"notify_low_storage_space_enabled" -> {
val enabled = sharedPreferences.getBoolean(key, defaultNotifyLowStorageSpace)
val threshold = Integer.valueOf(sharedPreferences.getString("low_storage_space_threshold", defaultNotifyLowStorageSpaceThreshold)!!)
Timber.d("Server status free space has changed to $availableStorageSpace, threshold is $threshold, checking if notification shall be shown")
showLowStorageSpace.value = enabled && availableStorageSpace <= threshold
}
}
}
fun getChannelById(id: Int): Channel? {
return appRepository.channelData.getItemById(id)
}
fun startDiskSpaceUpdateHandler() {
Timber.d("Starting disk space update handler")
diskSpaceUpdateHandler.post(discSpaceUpdateTask)
}
fun stopDiskSpaceUpdateHandler() {
Timber.d("Stopping disk space update handler")
diskSpaceUpdateHandler.removeCallbacks(discSpaceUpdateTask)
}
} | gpl-3.0 | b84953794b575b0ea0a59cc7f3f77061 | 55.548872 | 164 | 0.745346 | 5.280899 | false | false | false | false |
d9n/intellij-rust | src/test/kotlin/org/rust/lang/refactoring/RsLocalVariableHandlerTest.kt | 1 | 5022 | package org.rust.lang.refactoring
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsFile
class RsLocalVariableHandlerTest : RsTestBase() {
override val dataPath = "org/rust/lang/refactoring/fixtures/introduce_variable/"
fun testExpression() = doTest("""
fn hello() {
foo(5 + /*caret*/10);
}""", """
fn hello() {
let i = 10;
foo(5 + i);
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 3)
ref.replaceElementForAllExpr(expr, listOf(expr))
}
fun testExplicitSelectionWorks() {
myFixture.configureByText("main.rs", """
fn main() { 1 + <selection>1</selection>;}
""")
refactoring().getTarget(0, 1)
}
fun testMultipleOccurrences() = doTest("""
fn hello() {
foo(5 + /*caret*/10);
foo(5 + 10);
}
fn foo(x: Int) {
}""", """
fn hello() {
let x = 5 + 10;
foo(x);
foo(x);
}
fn foo(x: Int) {
}""")
{
val ref = refactoring()
val expr = ref.getTarget(1, 3)
val occurrences = findOccurrences(expr)
ref.replaceElementForAllExpr(expr, occurrences)
}
fun testMultipleOccurrences2() = doTest("""
fn main() {
let a = 1;
let b = a + 1;
let c = a +/*caret*/ 1;
}""", """
fn main() {
let a = 1;
let x = a + 1;
let b = x;
let c = x;
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 1)
val occurrences = findOccurrences(expr)
ref.replaceElementForAllExpr(expr, occurrences)
}
fun testCaretAfterElement() = doTest("""
fn main() {
1/*caret*/;
}""", """
fn main() {
let i = 1;
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 1)
ref.replaceElement(expr, listOf(expr))
}
fun testTopLevelInBlock() = doTest("""
fn main() {
let _ = {
1/*caret*/
};
}""", """
fn main() {
let _ = {
let i = 1;
};
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 1)
ref.replaceElement(expr, listOf(expr))
}
fun testStatement() = doTest("""
fn hello() {
foo(5 + /*caret*/10);
}""", """
fn hello() {
let foo = foo(5 + 10);
}""")
{
val ref = refactoring()
val expr = ref.getTarget(2, 3)
ref.replaceElement(expr, listOf(expr))
}
fun testMatch() = doTest("""
fn bar() {
ma/*caret*/tch 5 {
2 => 2,
_ => 8,
};
}""", """
fn bar() {
let i = match 5 {
2 => 2,
_ => 8,
};
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 1)
ref.replaceElement(expr, listOf(expr))
}
fun testFile() = doTest("""
fn read_fle() -> Result<Vec<String, io::Error>> {
File::op/*caret*/en("res/input.txt")?
}""", """
fn read_fle() -> Result<Vec<String, io::Error>> {
let x = File::open("res/input.txt")?;
}""")
{
val ref = refactoring()
val expr = ref.getTarget(1, 2)
ref.replaceElement(expr, listOf(expr))
}
fun testRefMut() = doTest("""
fn read_file() -> Result<String, Error> {
let file = File::open("res/input.txt")?;
file.read_to_string(&mut String:/*caret*/:new())
}""", """
fn read_file() -> Result<String, Error> {
let file = File::open("res/input.txt")?;
let mut string = String::new();
file.read_to_string(&mut string)
}""")
{
val ref = refactoring()
val expr = ref.getTarget(0, 3)
ref.replaceElement(expr, listOf(expr))
}
private fun doTest(@Language("Rust") before: String, @Language("Rust") after: String, action: () -> Unit) {
InlineFile(before).withCaret()
openFileInEditor("main.rs")
action()
myFixture.checkResult(after)
}
private fun refactoring(): RsIntroduceVariableRefactoring =
RsIntroduceVariableRefactoring(project, myFixture.editor, myFixture.file as RsFile)
fun RsIntroduceVariableRefactoring.getTarget(idx: Int, total: Int): RsExpr {
check(idx < total) { "Can't select $idx target out of $total" }
val targets = possibleTargets()
check(targets.size == total) {
"Expected $total targets, got ${targets.size}:\n\n${targets.map { it.text }.joinToString("\n\n")}"
}
return targets[idx]
}
}
| mit | 521eee029b0d2ac50a35aa4f5c7ee7a6 | 25.712766 | 111 | 0.476503 | 4.153846 | false | true | false | false |
lunivore/montecarluni | src/main/kotlin/com/lunivore/montecarluni/engine/WeeklyDistributionCalculator.kt | 1 | 2619 | package com.lunivore.montecarluni.engine
import com.lunivore.montecarluni.model.DateRange
import com.lunivore.montecarluni.model.Record
import com.lunivore.montecarluni.model.WorkItemsClosedInWeek
import org.apache.logging.log4j.LogManager
import java.time.LocalDateTime
class WeeklyDistributionCalculator() {
companion object {
val logger = LogManager.getLogger()!!
}
val neverUsed = LocalDateTime.of(1970, 1, 1, 0, 0)
fun calculateDistribution(completedDates: List<Record>): List<WorkItemsClosedInWeek> {
val dateRange = findFirstAndLastCompletedDates(completedDates)
val dateBrackets = calculateDateBrackets(dateRange)
return dateBrackets.map {
bracket ->
WorkItemsClosedInWeek(DateRange(bracket.first.toLocalDate(), bracket.second.toLocalDate().minusDays(1)),
completedDates.count {
val date = it.resolvedOrLastUpdatedDate
date != null &&
with(date) {
(isAfter(bracket.first) &&
isBefore(bracket.second)) ||
isEqual(bracket.second)
}
})
}
}
private fun calculateDateBrackets(dateRange : Pair<LocalDateTime, LocalDateTime>):
MutableList<Pair<LocalDateTime, LocalDateTime>> {
val dateBrackets = mutableListOf<Pair<LocalDateTime, LocalDateTime>>()
var processedDate = dateRange.second
while (processedDate != null &&
processedDate.compareTo(dateRange.first) >= 0) {
var nextDate = processedDate.minusDays(7)
dateBrackets.add(Pair(nextDate, processedDate))
processedDate = nextDate
}
dateBrackets.reverse()
return dateBrackets
}
private fun findFirstAndLastCompletedDates(completedDates: List<Record>): Pair<LocalDateTime, LocalDateTime> {
val earliestCompletedDate = completedDates.minBy { it.resolvedOrLastUpdatedDate ?: neverUsed }
?.resolvedOrLastUpdatedDate?.toLocalDate()?.atStartOfDay()
val lastCompletedDate = completedDates.maxBy { it.resolvedOrLastUpdatedDate ?: neverUsed }
?.resolvedOrLastUpdatedDate?.plusDays(1)?.toLocalDate()?.atStartOfDay()
if (earliestCompletedDate == null || lastCompletedDate == null) {
throw Exception("Could not find records to parse for date brackets. (Montecarluni should checked for this already!)")
}
return Pair(earliestCompletedDate, lastCompletedDate)
}
}
| apache-2.0 | 0dcf324382552c188c6fc77a4fc55dcc | 36.414286 | 129 | 0.649485 | 5.227545 | false | false | false | false |
asubb/mcaster | src/main/kotlin/MCasterPlayer.kt | 1 | 1306 | import javax.sound.midi.MidiSystem
fun main(args: Array<String>) {
val mdOut = MidiSystem.getMidiDeviceInfo()
.map {
println("""
name: ${it.name}
vendor: ${it.vendor}
version: ${it.version}
description: ${it.description}
""".trimIndent())
val dev = MidiSystem.getMidiDevice(it)!!
if (!dev.isOpen) {
dev.open()
}
dev
}
.first { it.deviceInfo.name.contains("Gervill") }
val playPlan = createPlayPlan(example1)
println("Play plan: $playPlan")
MidiSoundProducer(mdOut).use { producer ->
playPlan.forEach {
when (it) {
is Long -> {
println(" $it");Thread.sleep(it)
}
is PadType -> {
print(it.note)
producer.play(it, if (it == PadType.METRONOME_TICK) 127 else 0)
}
else -> throw IllegalStateException("Not recognized $it")
}
}
println("\ntrack played")
Thread.sleep(1000)
println("finished waiting for last note to play")
}
System.exit(0)
}
| apache-2.0 | 933d2c1f397006385648fed3503a6637 | 28.022222 | 83 | 0.453292 | 4.631206 | false | false | false | false |
YUKAI/KonashiInspectorForAndroid | app/src/main/java/com/uxxu/konashi/inspector/android/CommunicationFragment.kt | 1 | 9448 | package com.uxxu.konashi.inspector.android
import android.support.v4.app.Fragment
import android.bluetooth.BluetoothGattCharacteristic
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Button
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.Spinner
import android.widget.Switch
import android.widget.Toast
import com.uxxu.konashi.lib.Konashi
import com.uxxu.konashi.lib.KonashiListener
import com.uxxu.konashi.lib.KonashiManager
import org.jdeferred.DoneCallback
import org.jdeferred.DonePipe
import org.jdeferred.FailCallback
import org.jdeferred.Promise
import info.izumin.android.bletia.BletiaException
/**
* Created by kiryu on 7/27/15.
*/
class CommunicationFragment : Fragment() {
private var mKonashiManager: KonashiManager? = null
private var mUartSwitch: Switch? = null
private var mUartBaudrateSpinner: Spinner? = null
private var mUartDataEditText: EditText? = null
private var mUartDataSendButton: Button? = null
private var mUartResultEditText: EditText? = null
private var mUartResultClearButton: Button? = null
private var mI2cSwitch: Switch? = null
private var mI2cBaudrateSpinner: Spinner? = null
private var mI2cDataEditText: EditText? = null
private var mI2cDataSendButton: Button? = null
private var mI2cResultEditText: EditText? = null
private var mI2cResultReadButton: Button? = null
private var mI2cResultClearButton: Button? = null
private var mValue: ByteArray? = null
private val mKonashiListener = object : KonashiListener {
override fun onConnect(manager: KonashiManager) {}
override fun onDisconnect(manager: KonashiManager) {}
override fun onError(manager: KonashiManager, e: BletiaException) {}
override fun onUpdatePioOutput(manager: KonashiManager, value: Int) {}
override fun onUpdateSpiMiso(manager: KonashiManager, value: ByteArray) {}
override fun onUpdateUartRx(manager: KonashiManager, value: ByteArray) {
mValue = value
mUartResultEditText!!.append(String(mValue!!))
}
override fun onUpdateBatteryLevel(manager: KonashiManager, level: Int) {}
override fun onFindNoDevice(manager: KonashiManager) {}
override fun onConnectOtherDevice(manager: KonashiManager) {}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity!!.title = getString(R.string.title_communication)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_communication, container, false)
initUartViews(view)
initI2cViews(view)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mKonashiManager = Konashi.getManager()
mKonashiManager!!.addListener(mKonashiListener)
}
override fun onDestroy() {
mKonashiManager!!.removeListener(mKonashiListener)
super.onDestroy()
}
private fun initUartViews(parent: View) {
mUartBaudrateSpinner = parent.findViewById<View>(R.id.uartBaudrateSpinner) as Spinner
mUartBaudrateSpinner!!.setSelection(1)
mUartBaudrateSpinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
resetUart()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {}
}
mUartSwitch = parent.findViewById<View>(R.id.uartSwitch) as Switch
mUartSwitch!!.setOnCheckedChangeListener { compoundButton, b -> resetUart() }
mUartDataEditText = parent.findViewById<View>(R.id.uartDataEditText) as EditText
mUartDataSendButton = parent.findViewById<View>(R.id.uartDataSendButton) as Button
mUartDataSendButton!!.setOnClickListener {
mKonashiManager!!.uartWrite(mUartDataEditText!!.text.toString().toByteArray())
.then { }
.fail { result -> Toast.makeText(activity, result.message, Toast.LENGTH_SHORT).show() }
}
mUartResultEditText = parent.findViewById<View>(R.id.uartResultEditText) as EditText
mUartResultClearButton = parent.findViewById<View>(R.id.uartResultClearButton) as Button
mUartResultClearButton!!.setOnClickListener { mUartResultEditText!!.setText("") }
setEnableUartViews(false)
}
private fun initI2cViews(parent: View) {
mI2cBaudrateSpinner = parent.findViewById<View>(R.id.i2cBaudrateSpinner) as Spinner
mI2cBaudrateSpinner!!.setSelection(0)
mI2cBaudrateSpinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
resetI2c()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {}
}
mI2cSwitch = parent.findViewById<View>(R.id.i2cSwitch) as Switch
mI2cSwitch!!.setOnCheckedChangeListener { compoundButton, b -> resetI2c() }
mI2cDataEditText = parent.findViewById<View>(R.id.i2cDataEditText) as EditText
mI2cDataSendButton = parent.findViewById<View>(R.id.i2cDataSendButton) as Button
mI2cDataSendButton!!.setOnClickListener {
val value = mI2cDataEditText!!.text.toString().trim { it <= ' ' }.toByteArray()
mKonashiManager!!.i2cMode(Konashi.I2C_ENABLE_100K)
.then(mKonashiManager!!.i2cStartConditionPipe())
.then(mKonashiManager!!.i2cWritePipe(value.size, value, I2C_ADDRESS))
.then(mKonashiManager!!.i2cStopConditionPipe())
.fail { result -> Toast.makeText(activity, result.message, Toast.LENGTH_SHORT).show() }
}
mI2cResultEditText = parent.findViewById<View>(R.id.i2cResultEditText) as EditText
mI2cResultReadButton = parent.findViewById<View>(R.id.i2cResultReadButton) as Button
mI2cResultReadButton!!.setOnClickListener {
mKonashiManager!!.i2cStartCondition()
.then(mKonashiManager!!.i2cReadPipe(Konashi.I2C_DATA_MAX_LENGTH, I2C_ADDRESS))
.then { result ->
val builder = StringBuilder()
for (b in result) {
builder.append(b.toInt()).append(",")
}
mI2cResultEditText!!.setText(builder.toString().substring(0, builder.length - 1))
}
.then(mKonashiManager!!.i2cStopConditionPipe())
.fail { result -> Toast.makeText(activity, result.message, Toast.LENGTH_SHORT).show() }
}
mI2cResultClearButton = parent.findViewById<View>(R.id.i2cResultClearButton) as Button
mI2cResultClearButton!!.setOnClickListener { mI2cResultEditText!!.setText("") }
setEnableI2cViews(false)
}
private fun resetUart() {
if (!mKonashiManager!!.isReady) {
return
}
if (mUartSwitch!!.isChecked) {
mKonashiManager!!.uartMode(Konashi.UART_ENABLE)
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> {
val i = mUartBaudrateSpinner!!.selectedItemPosition
val labels = resources.getStringArray(R.array.uartBaudrateLabels)
val label = labels[i]
mKonashiManager!!.uartBaudrate(Utils.uartLabelToValue(activity!!, label))
})
.then { setEnableUartViews(true) }
} else {
mKonashiManager!!.uartMode(Konashi.UART_DISABLE)
.then { setEnableUartViews(false) }
}
}
private fun resetI2c() {
if (!mKonashiManager!!.isReady) {
return
}
if (mI2cSwitch!!.isChecked) {
val i = mI2cBaudrateSpinner!!.selectedItemPosition
if (i == 0) {
mKonashiManager!!.i2cMode(Konashi.I2C_ENABLE_100K)
.then { setEnableI2cViews(true) }
.fail { result -> Log.d("i2cMode", result.message) }
} else {
mKonashiManager!!.i2cMode(Konashi.I2C_ENABLE_400K)
.then { setEnableI2cViews(true) }
}
} else {
mKonashiManager!!.i2cMode(Konashi.I2C_DISABLE)
.then { setEnableI2cViews(false) }
}
}
private fun setEnableUartViews(enable: Boolean) {
mUartBaudrateSpinner!!.isEnabled = enable
mUartDataEditText!!.isEnabled = enable
mUartDataSendButton!!.isEnabled = enable
}
private fun setEnableI2cViews(enable: Boolean) {
mI2cBaudrateSpinner!!.isEnabled = enable
mI2cDataEditText!!.isEnabled = enable
mI2cDataSendButton!!.isEnabled = enable
mI2cResultReadButton!!.isEnabled = enable
}
companion object {
private val I2C_ADDRESS: Byte = 0x01f
}
}
| apache-2.0 | 5258d11833fb1394ab324a5060cff5a6 | 39.724138 | 117 | 0.658446 | 4.093588 | false | false | false | false |
uchuhimo/kotlin-playground | lang/src/main/kotlin/com/uchuhimo/lib/configurate/Play.kt | 1 | 2574 | package com.uchuhimo.lib.configurate
import ninja.leaping.configurate.gson.GsonConfigurationLoader
import ninja.leaping.configurate.hocon.HoconConfigurationLoader
import ninja.leaping.configurate.json.JSONConfigurationLoader
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader
import org.yaml.snakeyaml.DumperOptions
import java.io.File
fun testYaml() {
val loader = YAMLConfigurationLoader.builder().apply {
setFile(File("test.yml"))
setFlowStyle(DumperOptions.FlowStyle.BLOCK)
}.build()
val root = loader.createEmptyNode()
val node = root.getNode("network", "buffer", "size")
node.value = 1024
loader.save(root)
}
fun readYaml() {
val loader = YAMLConfigurationLoader.builder().apply {
setFile(File("test.yml"))
setFlowStyle(DumperOptions.FlowStyle.BLOCK)
}.build()
val root = loader.load()
val node = root.getNode("network", "buffer", "size")
println(node.value)
}
fun testHocon() {
val loader = HoconConfigurationLoader.builder().apply {
setFile(File("test.conf"))
}.build()
val root = loader.createEmptyNode()
val node = root.getNode("network", "buffer", "size")
node.value = 1024
val comment = "size of network buffer"
node.setComment(Array(100) { comment }.reduce(String::plus))
loader.save(root)
}
fun readHocon() {
val loader = HoconConfigurationLoader.builder().apply {
setFile(File("test.conf"))
}.build()
val root = loader.load()
val node = root.getNode("network", "buffer", "size")
println(node.value)
}
fun testJson() {
val loader = JSONConfigurationLoader.builder().apply {
setFile(File("test.json"))
}.build()
val root = loader.createEmptyNode()
val node = root.getNode("network", "buffer", "size")
node.value = 1024
node.getNode("comment").value = "size of network buffer"
loader.save(root)
}
fun readJson() {
val loader = JSONConfigurationLoader.builder().apply {
setFile(File("test.json"))
}.build()
val root = loader.load()
val node = root.getNode("network", "buffer", "size")
println(node.getNode("comment").value)
}
fun testGson() {
val loader = GsonConfigurationLoader.builder().apply {
setFile(File("test.gson"))
}.build()
val root = loader.createEmptyNode()
val node = root.getNode("network", "buffer", "size")
node.value = 1024
loader.save(root)
}
fun main(args: Array<String>) {
testYaml()
testHocon()
testJson()
testGson()
readJson()
readYaml()
readHocon()
}
| apache-2.0 | 35274ddafbfd22f95834e01c65539424 | 27.6 | 64 | 0.666667 | 3.888218 | false | true | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-event/src/main/kotlin/ch/schulealtendorf/psa/service/event/business/StartlistExportManager.kt | 1 | 1414 | package ch.schulealtendorf.psa.service.event.business
import ch.schulealtendorf.psa.core.io.AppDirectory
import ch.schulealtendorf.psa.core.io.ApplicationFile
import ch.schulealtendorf.psa.core.io.FileSystem
import ch.schulealtendorf.psa.service.event.business.reporter.StartlistReporter
import ch.schulealtendorf.psa.service.standard.export.ArchiveGenerationException
import ch.schulealtendorf.psa.service.standard.export.ExportManager
import mu.KotlinLogging
import org.springframework.stereotype.Component
import java.io.File
import java.util.ResourceBundle
@Component
class StartlistExportManager(
private val fileSystem: FileSystem,
private val startlistReporter: StartlistReporter
) : ExportManager<Void> {
private val resourceBundle = ResourceBundle.getBundle("i18n.event-sheets")
private val log = KotlinLogging.logger {}
override fun generateArchive(data: Void) = generateArchive()
/**
* Generates an archive file for the startlist.
*
* @return the generated archive
* @throws ArchiveGenerationException if the archive could not be generated
*/
fun generateArchive(): File {
log.info { "Create archive for startlist" }
val report = startlistReporter.generateReport()
val file = ApplicationFile(AppDirectory.EXPORT, resourceBundle.getString("startlist"))
return fileSystem.createArchive(file, setOf(report))
}
}
| gpl-3.0 | d31201326aa6f5dc94f9fc3d61e4a7d0 | 37.216216 | 94 | 0.775813 | 4.460568 | false | false | false | false |
usmansaleem/kt-vertx | src/main/kotlin/info/usmans/blog/model/model.kt | 1 | 3724 | package info.usmans.blog.model
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
internal const val BLOG_ITEMS_PER_PAGE = 10
/**
* BlogItem represents each blog entry.
*/
data class BlogItem(
val id: Long = 0,
val urlFriendlyId: String = "",
val title: String,
val description: String? = "",
val body: String? = "",
var blogSection: String? = "Main",
val createdOn: String? = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE),
val modifiedOn: String? = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE),
val createDay: String? = LocalDate.now().format(DateTimeFormatter.ofPattern("dd")),
val createMonth: String? = LocalDate.now().format(DateTimeFormatter.ofPattern("MMM")),
val createYear: String? = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy")),
val categories: List<Category>? = emptyList()
)
/**
* Represents a category*
*/
data class Category(val id: Int = 0, val name: String = "")
data class Message(val message: String = "")
class BlogItemUtil {
//store blog entries per page
private val pagedBlogItemIdMap: TreeMap<Long, List<Long>> = TreeMap()
//store blog entries based on id
private val blogItemMap: TreeMap<Long, BlogItem> = TreeMap(Collections.reverseOrder())
private val friendlyUrlMap = mutableMapOf<String, Long>()
fun initBlogItemMaps(blogItems: List<BlogItem>) {
this.blogItemMap.putAll(blogItems.associateBy({ it.id }) { it })
this.friendlyUrlMap.putAll(blogItems.associateBy({ it.urlFriendlyId }) { it.id })
initPagedBlogItems()
}
fun getBlogItemIdList() = blogItemMap.keys.toList()
fun getBlogItemUrlList() = friendlyUrlMap.keys.toList()
fun getBlogItemList() = blogItemMap.values.toList()
fun getBlogItemForId(id: Long) = blogItemMap.get(id)
fun getBlogItemForUrl(url: String) = blogItemMap.get(friendlyUrlMap.get(url) ?: 0)
fun putBlogItemForId(id: Long, blogItem: BlogItem) = blogItemMap.put(id, blogItem)
fun getNextBlogItemId() = blogItemMap.firstKey() + 1
fun getBlogItemListForPage(pageNumber: Long): List<BlogItem> = this.pagedBlogItemIdMap.get(pageNumber)?.map { blogItemMap.get(it) ?: BlogItem(id = 0, title = "Not Found") } ?: emptyList()
fun getHighestPage() = (if(pagedBlogItemIdMap.size == 0) 0L else pagedBlogItemIdMap.lastKey())!!
fun getBlogCount() = blogItemMap.size
fun initPagedBlogItems() {
val sortedBlogItemsList = blogItemMap.values.toList().sortedByDescending(BlogItem::id)
val itemsOnLastPage = sortedBlogItemsList.size % BLOG_ITEMS_PER_PAGE
val totalPagesCount = if (itemsOnLastPage == 0) sortedBlogItemsList.size / BLOG_ITEMS_PER_PAGE else sortedBlogItemsList.size / BLOG_ITEMS_PER_PAGE + 1
val localBlogItemsIdPerPageList = mutableMapOf<Long, List<Long>>()
for (pageNumber in totalPagesCount downTo 1) {
var endIdx = (pageNumber * BLOG_ITEMS_PER_PAGE)
val startIdx = endIdx - BLOG_ITEMS_PER_PAGE
if ((pageNumber == totalPagesCount) && (itemsOnLastPage != 0)) {
endIdx = startIdx + itemsOnLastPage
}
val pagedList: List<Long> = sortedBlogItemsList.subList(startIdx, endIdx).map { it.id }
localBlogItemsIdPerPageList.put(pageNumber.toLong(), pagedList)
}
if (localBlogItemsIdPerPageList.size < this.pagedBlogItemIdMap.size) {
//the pages has been decreased (in case of deletion), clear out global map
this.pagedBlogItemIdMap.clear()
}
this.pagedBlogItemIdMap.putAll(localBlogItemsIdPerPageList)
}
}
| mit | fb38fc2f1496a2e0488a36c17b97d2ea | 38.2 | 191 | 0.682062 | 3.867082 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/view/DateUtils.kt | 1 | 3320 | package com.stripe.android.view
import androidx.annotation.IntRange
import androidx.annotation.VisibleForTesting
import java.util.Calendar
internal object DateUtils {
private const val MAX_VALID_YEAR = 9980
/**
* Checks whether or not the input month and year has yet expired.
*
* @param expiryMonth An integer representing a month. Only values 1-12 are valid,
* but this is called by user input, so we have to check outside that range.
* @param expiryYear An integer representing the year (either 2017 or 17). Only positive values
* are valid, but this is called by user input, so we have to check outside
* for otherwise nonsensical dates. This code cannot validate years greater
* than [9980][MAX_VALID_YEAR] because of how we parse years in [convertTwoDigitYearToFour].
* @return `true` if the current month and year is the same as or later than the input
* month and year, `false` otherwise. Note that some cards expire on the first of the
* month, but we don't validate that here.
*/
@JvmStatic
fun isExpiryDataValid(expiryMonth: Int, expiryYear: Int): Boolean {
val fullExpiryYear = if (expiryYear < 100) {
convertTwoDigitYearToFour(expiryYear)
} else {
expiryYear
}
return isExpiryDataValid(expiryMonth, fullExpiryYear, Calendar.getInstance())
}
@VisibleForTesting
@JvmStatic
fun isExpiryDataValid(expiryMonth: Int, expiryYear: Int, calendar: Calendar): Boolean {
if (expiryMonth !in 1..12) {
return false
}
if (expiryYear !in 0..MAX_VALID_YEAR) {
return false
}
val currentYear = calendar.get(Calendar.YEAR)
return when {
expiryYear < currentYear -> false
expiryYear > currentYear -> true
else -> { // the card expires this year
val readableMonth = calendar.get(Calendar.MONTH) + 1
expiryMonth >= readableMonth
}
}
}
/**
* Converts a two-digit input year to a four-digit year. As the current calendar year
* approaches a century, we assume small values to mean the next century. For instance, if
* the current year is 2090, and the input value is "18", the user probably means 2118,
* not 2018. However, in 2017, the input "18" probably means 2018. This code should be
* updated before the year 9981.
*
* @param inputYear a two-digit integer, between 0 and 99, inclusive
* @return a four-digit year
*/
@IntRange(from = 1000, to = 9999)
fun convertTwoDigitYearToFour(@IntRange(from = 0, to = 99) inputYear: Int): Int {
return convertTwoDigitYearToFour(inputYear, Calendar.getInstance())
}
@VisibleForTesting
@IntRange(from = 1000, to = 9999)
fun convertTwoDigitYearToFour(
@IntRange(from = 0, to = 99) inputYear: Int,
calendar: Calendar
): Int {
val year = calendar.get(Calendar.YEAR)
// Intentional integer division
var centuryBase = year / 100
if (year % 100 > 80 && inputYear < 20) {
centuryBase++
} else if (year % 100 < 20 && inputYear > 80) {
centuryBase--
}
return centuryBase * 100 + inputYear
}
}
| mit | 0e0f53d4b4f271e2bb08f92bb1163830 | 37.16092 | 99 | 0.639759 | 4.306096 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/OnRemeasuredModifier.kt | 3 | 3165 | /*
* 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.layout
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.internal.JvmDefaultWithCompatibility
/**
* Invoked with the size of the modified Compose UI element when the element is first measured or
* when the size of the element changes.
*
* There are no guarantees `onSizeChanged` will not be re-invoked with the same size.
*
* Using the `onSizeChanged` size value in a [MutableState] to update layout causes the new size
* value to be read and the layout to be recomposed in the succeeding frame, resulting in a one
* frame lag.
*
* You can use `onSizeChanged` to affect drawing operations. Use [Layout] or [SubcomposeLayout] to
* enable the size of one component to affect the size of another.
*
* Example usage:
* @sample androidx.compose.ui.samples.OnSizeChangedSample
*/
@Stable
fun Modifier.onSizeChanged(
onSizeChanged: (IntSize) -> Unit
) = this.then(
OnSizeChangedModifier(
onSizeChanged = onSizeChanged,
inspectorInfo = debugInspectorInfo {
name = "onSizeChanged"
properties["onSizeChanged"] = onSizeChanged
}
)
)
private class OnSizeChangedModifier(
val onSizeChanged: (IntSize) -> Unit,
inspectorInfo: InspectorInfo.() -> Unit
) : OnRemeasuredModifier, InspectorValueInfo(inspectorInfo) {
private var previousSize = IntSize(Int.MIN_VALUE, Int.MIN_VALUE)
override fun onRemeasured(size: IntSize) {
if (previousSize != size) {
onSizeChanged(size)
previousSize = size
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is OnSizeChangedModifier) return false
return onSizeChanged == other.onSizeChanged
}
override fun hashCode(): Int {
return onSizeChanged.hashCode()
}
}
/**
* A modifier whose [onRemeasured] is called when the layout content is remeasured. The
* most common usage is [onSizeChanged].
*
* Example usage:
* @sample androidx.compose.ui.samples.OnSizeChangedSample
*/
@JvmDefaultWithCompatibility
interface OnRemeasuredModifier : Modifier.Element {
/**
* Called after a layout's contents have been remeasured.
*/
fun onRemeasured(size: IntSize)
}
| apache-2.0 | e0a5849345a68281ee062abf333cbacb | 32.315789 | 98 | 0.725434 | 4.408078 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/permissions/requesters/RequestersHelper.kt | 2 | 1607 | package abi43_0_0.expo.modules.permissions.requesters
import android.Manifest
import android.os.Bundle
import abi43_0_0.expo.modules.interfaces.permissions.PermissionsResponse
import abi43_0_0.expo.modules.interfaces.permissions.PermissionsStatus
fun parseBasicLocationPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return Bundle().apply {
val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION)
val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION)
val canAskAgain = accessFineLocation.canAskAgain && accessCoarseLocation.canAskAgain
val isGranted = accessCoarseLocation.status == PermissionsStatus.GRANTED || accessFineLocation.status == PermissionsStatus.GRANTED
putString(
PermissionsResponse.STATUS_KEY,
when {
accessFineLocation.status == PermissionsStatus.GRANTED -> {
PermissionsStatus.GRANTED.status
}
accessCoarseLocation.status == PermissionsStatus.GRANTED -> {
PermissionsStatus.GRANTED.status
}
accessFineLocation.status == PermissionsStatus.DENIED && accessCoarseLocation.status == PermissionsStatus.DENIED -> {
PermissionsStatus.DENIED.status
}
else -> {
PermissionsStatus.UNDETERMINED.status
}
}
)
putString(PermissionsResponse.EXPIRES_KEY, PermissionsResponse.PERMISSION_EXPIRES_NEVER)
putBoolean(PermissionsResponse.CAN_ASK_AGAIN_KEY, canAskAgain)
putBoolean(PermissionsResponse.GRANTED_KEY, isGranted)
}
}
| bsd-3-clause | 39c9fc4b9569993b66a5f3e0958afb55 | 42.432432 | 134 | 0.756689 | 5.447458 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/types/BasicTypeConverters.kt | 2 | 2233 | package expo.modules.kotlin.types
import com.facebook.react.bridge.Dynamic
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
class IntTypeConverter(isOptional: Boolean) : TypeConverter<Int>(isOptional) {
override fun convertNonOptional(value: Dynamic): Int = value.asInt()
}
class DoubleTypeConverter(isOptional: Boolean) : TypeConverter<Double>(isOptional) {
override fun convertNonOptional(value: Dynamic): Double = value.asDouble()
}
class FloatTypeConverter(isOptional: Boolean) : TypeConverter<Float>(isOptional) {
override fun convertNonOptional(value: Dynamic): Float = value.asDouble().toFloat()
}
class BoolTypeConverter(isOptional: Boolean) : TypeConverter<Boolean>(isOptional) {
override fun convertNonOptional(value: Dynamic): Boolean = value.asBoolean()
}
class StringTypeConverter(isOptional: Boolean) : TypeConverter<String>(isOptional) {
override fun convertNonOptional(value: Dynamic): String = value.asString()
}
class ReadableArrayTypeConverter(isOptional: Boolean) : TypeConverter<ReadableArray>(isOptional) {
override fun convertNonOptional(value: Dynamic): ReadableArray = value.asArray()
}
class ReadableMapTypeConverter(isOptional: Boolean) : TypeConverter<ReadableMap>(isOptional) {
override fun convertNonOptional(value: Dynamic): ReadableMap = value.asMap()
}
class PrimitiveIntArrayTypeConverter(isOptional: Boolean) : TypeConverter<IntArray>(isOptional) {
override fun convertNonOptional(value: Dynamic): IntArray {
val jsArray = value.asArray()
return IntArray(jsArray.size()) { index ->
jsArray.getInt(index)
}
}
}
class PrimitiveDoubleArrayTypeConverter(isOptional: Boolean) : TypeConverter<DoubleArray>(isOptional) {
override fun convertNonOptional(value: Dynamic): DoubleArray {
val jsArray = value.asArray()
return DoubleArray(jsArray.size()) { index ->
jsArray.getDouble(index)
}
}
}
class PrimitiveFloatArrayTypeConverter(isOptional: Boolean) : TypeConverter<FloatArray>(isOptional) {
override fun convertNonOptional(value: Dynamic): FloatArray {
val jsArray = value.asArray()
return FloatArray(jsArray.size()) { index ->
jsArray.getDouble(index).toFloat()
}
}
}
| bsd-3-clause | 3b4e4771add409d7954d4e97602c07d0 | 36.216667 | 103 | 0.769369 | 4.369863 | false | false | false | false |
AndroidX/androidx | compose/material/material/integration-tests/material-catalog/src/main/java/androidx/compose/material/catalog/library/ui/home/Home.kt | 3 | 3117 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.catalog.library.ui.home
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material.catalog.library.R
import androidx.compose.material.catalog.library.model.Component
import androidx.compose.material.catalog.library.model.Theme
import androidx.compose.material.catalog.library.ui.common.CatalogScaffold
import androidx.compose.material.catalog.library.ui.component.ComponentItem
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@Composable
fun Home(
components: List<Component>,
theme: Theme,
onThemeChange: (theme: Theme) -> Unit,
onComponentClick: (component: Component) -> Unit
) {
CatalogScaffold(
topBarTitle = stringResource(id = R.string.compose_material),
theme = theme,
onThemeChange = onThemeChange
) { paddingValues ->
BoxWithConstraints(modifier = Modifier.padding(paddingValues)) {
val cellsCount = maxOf((maxWidth / HomeCellMinSize).toInt(), 1)
LazyVerticalGrid(
// LazyGridScope doesn't expose nColumns from LazyVerticalGrid
// https://issuetracker.google.com/issues/183187002
columns = GridCells.Fixed(count = cellsCount),
content = {
itemsIndexed(components) { index, component ->
ComponentItem(
component = component,
onClick = onComponentClick,
index = index,
cellsCount = cellsCount
)
}
},
contentPadding = WindowInsets.safeDrawing
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom)
.asPaddingValues()
)
}
}
}
private val HomeCellMinSize = 180.dp
| apache-2.0 | d0b29bdb7c0d21ec29c43eaafdb674a6 | 40.56 | 82 | 0.694899 | 4.832558 | false | false | false | false |
androidx/androidx | compose/ui/ui-graphics/src/skikoMain/kotlin/androidx/compose/ui/graphics/SkiaBackedCanvas.skiko.kt | 3 | 12652 | /*
* 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.graphics
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.util.fastForEach
import org.jetbrains.skia.CubicResampler
import org.jetbrains.skia.FilterMipmap
import org.jetbrains.skia.FilterMode
import org.jetbrains.skia.Image
import org.jetbrains.skia.Matrix44
import org.jetbrains.skia.MipmapMode
import org.jetbrains.skia.SamplingMode
import org.jetbrains.skia.ClipMode as SkClipMode
import org.jetbrains.skia.RRect as SkRRect
import org.jetbrains.skia.Rect as SkRect
// Using skiko use as it has versions for all mpp platforms
import org.jetbrains.skia.impl.use
actual typealias NativeCanvas = org.jetbrains.skia.Canvas
internal actual fun ActualCanvas(image: ImageBitmap): Canvas {
val skiaBitmap = image.asSkiaBitmap()
require(!skiaBitmap.isImmutable) {
"Cannot draw on immutable ImageBitmap"
}
return SkiaBackedCanvas(org.jetbrains.skia.Canvas(skiaBitmap))
}
/**
* Convert the [org.jetbrains.skia.Canvas] instance into a Compose-compatible Canvas
*/
fun org.jetbrains.skia.Canvas.asComposeCanvas(): Canvas = SkiaBackedCanvas(this)
actual val Canvas.nativeCanvas: NativeCanvas get() = (this as SkiaBackedCanvas).skia
class SkiaBackedCanvas(val skia: org.jetbrains.skia.Canvas) : Canvas {
var alphaMultiplier: Float = 1.0f
private val Paint.skia get() = (this as SkiaBackedPaint).apply {
this.alphaMultiplier = [email protected]
}.skia
override fun save() {
skia.save()
}
override fun restore() {
skia.restore()
}
override fun saveLayer(bounds: Rect, paint: Paint) {
skia.saveLayer(
bounds.left,
bounds.top,
bounds.right,
bounds.bottom,
paint.skia
)
}
override fun translate(dx: Float, dy: Float) {
skia.translate(dx, dy)
}
override fun scale(sx: Float, sy: Float) {
skia.scale(sx, sy)
}
override fun rotate(degrees: Float) {
skia.rotate(degrees)
}
override fun skew(sx: Float, sy: Float) {
skia.skew(sx, sy)
}
override fun concat(matrix: Matrix) {
if (!matrix.isIdentity()) {
skia.concat(matrix.toSkia())
}
}
override fun clipRect(left: Float, top: Float, right: Float, bottom: Float, clipOp: ClipOp) {
val antiAlias = true
skia.clipRect(SkRect.makeLTRB(left, top, right, bottom), clipOp.toSkia(), antiAlias)
}
override fun clipPath(path: Path, clipOp: ClipOp) {
val antiAlias = true
skia.clipPath(path.asSkiaPath(), clipOp.toSkia(), antiAlias)
}
override fun drawLine(p1: Offset, p2: Offset, paint: Paint) {
skia.drawLine(p1.x, p1.y, p2.x, p2.y, paint.skia)
}
override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
skia.drawRect(SkRect.makeLTRB(left, top, right, bottom), paint.skia)
}
override fun drawRoundRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
radiusX: Float,
radiusY: Float,
paint: Paint
) {
skia.drawRRect(
SkRRect.makeLTRB(
left,
top,
right,
bottom,
radiusX,
radiusY
),
paint.skia
)
}
override fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
skia.drawOval(SkRect.makeLTRB(left, top, right, bottom), paint.skia)
}
override fun drawCircle(center: Offset, radius: Float, paint: Paint) {
skia.drawCircle(center.x, center.y, radius, paint.skia)
}
override fun drawArc(
left: Float,
top: Float,
right: Float,
bottom: Float,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
) {
skia.drawArc(
left,
top,
right,
bottom,
startAngle,
sweepAngle,
useCenter,
paint.skia
)
}
override fun drawPath(path: Path, paint: Paint) {
skia.drawPath(path.asSkiaPath(), paint.skia)
}
override fun drawImage(image: ImageBitmap, topLeftOffset: Offset, paint: Paint) {
val size = Size(image.width.toFloat(), image.height.toFloat())
drawImageRect(image, Offset.Zero, size, topLeftOffset, size, paint)
}
override fun drawImageRect(
image: ImageBitmap,
srcOffset: IntOffset,
srcSize: IntSize,
dstOffset: IntOffset,
dstSize: IntSize,
paint: Paint
) {
drawImageRect(
image,
Offset(srcOffset.x.toFloat(), srcOffset.y.toFloat()),
Size(srcSize.width.toFloat(), srcSize.height.toFloat()),
Offset(dstOffset.x.toFloat(), dstOffset.y.toFloat()),
Size(dstSize.width.toFloat(), dstSize.height.toFloat()),
paint
)
}
// TODO(demin): probably this method should be in the common Canvas
private fun drawImageRect(
image: ImageBitmap,
srcOffset: Offset,
srcSize: Size,
dstOffset: Offset,
dstSize: Size,
paint: Paint
) {
val bitmap = image.asSkiaBitmap()
// TODO(gorshenev): need to use skiko's .use() rather than jvm one here.
// But can't do that as skiko is jvmTarget=11 for now, so can't inline
// into jvmTarget=8 compose.
// After this issue is resolved use:
// import org.jetbrains.skia.impl.use
Image.makeFromBitmap(bitmap).use { skiaImage ->
skia.drawImageRect(
skiaImage,
SkRect.makeXYWH(
srcOffset.x,
srcOffset.y,
srcSize.width,
srcSize.height
),
SkRect.makeXYWH(
dstOffset.x,
dstOffset.y,
dstSize.width,
dstSize.height
),
paint.filterQuality.toSkia(),
paint.skia,
true
)
}
}
override fun drawPoints(pointMode: PointMode, points: List<Offset>, paint: Paint) {
when (pointMode) {
// Draw a line between each pair of points, each point has at most one line
// If the number of points is odd, then the last point is ignored.
PointMode.Lines -> drawLines(points, paint, 2)
// Connect each adjacent point with a line
PointMode.Polygon -> drawLines(points, paint, 1)
// Draw a point at each provided coordinate
PointMode.Points -> drawPoints(points, paint)
}
}
override fun enableZ() = Unit
override fun disableZ() = Unit
private fun drawPoints(points: List<Offset>, paint: Paint) {
points.fastForEach { point ->
skia.drawPoint(
point.x,
point.y,
paint.skia
)
}
}
/**
* Draw lines connecting points based on the corresponding step.
*
* ex. 3 points with a step of 1 would draw 2 lines between the first and second points
* and another between the second and third
*
* ex. 4 points with a step of 2 would draw 2 lines between the first and second and another
* between the third and fourth. If there is an odd number of points, the last point is
* ignored
*
* @see drawRawLines
*/
private fun drawLines(points: List<Offset>, paint: Paint, stepBy: Int) {
if (points.size >= 2) {
for (i in 0 until points.size - 1 step stepBy) {
val p1 = points[i]
val p2 = points[i + 1]
skia.drawLine(
p1.x,
p1.y,
p2.x,
p2.y,
paint.skia
)
}
}
}
/**
* @throws IllegalArgumentException if a non even number of points is provided
*/
override fun drawRawPoints(pointMode: PointMode, points: FloatArray, paint: Paint) {
if (points.size % 2 != 0) {
throw IllegalArgumentException("points must have an even number of values")
}
when (pointMode) {
PointMode.Lines -> drawRawLines(points, paint, 2)
PointMode.Polygon -> drawRawLines(points, paint, 1)
PointMode.Points -> drawRawPoints(points, paint, 2)
}
}
private fun drawRawPoints(points: FloatArray, paint: Paint, stepBy: Int) {
if (points.size % 2 == 0) {
for (i in 0 until points.size - 1 step stepBy) {
val x = points[i]
val y = points[i + 1]
skia.drawPoint(x, y, paint.skia)
}
}
}
/**
* Draw lines connecting points based on the corresponding step. The points are interpreted
* as x, y coordinate pairs in alternating index positions
*
* ex. 3 points with a step of 1 would draw 2 lines between the first and second points
* and another between the second and third
*
* ex. 4 points with a step of 2 would draw 2 lines between the first and second and another
* between the third and fourth. If there is an odd number of points, the last point is
* ignored
*
* @see drawLines
*/
private fun drawRawLines(points: FloatArray, paint: Paint, stepBy: Int) {
// Float array is treated as alternative set of x and y coordinates
// x1, y1, x2, y2, x3, y3, ... etc.
if (points.size >= 4 && points.size % 2 == 0) {
for (i in 0 until points.size - 3 step stepBy * 2) {
val x1 = points[i]
val y1 = points[i + 1]
val x2 = points[i + 2]
val y2 = points[i + 3]
skia.drawLine(
x1,
y1,
x2,
y2,
paint.skia
)
}
}
}
override fun drawVertices(vertices: Vertices, blendMode: BlendMode, paint: Paint) {
skia.drawVertices(
vertices.vertexMode.toSkiaVertexMode(),
vertices.positions,
vertices.colors,
vertices.textureCoordinates,
vertices.indices,
blendMode.toSkia(),
paint.asFrameworkPaint()
)
}
private fun ClipOp.toSkia() = when (this) {
ClipOp.Difference -> SkClipMode.DIFFERENCE
ClipOp.Intersect -> SkClipMode.INTERSECT
else -> SkClipMode.INTERSECT
}
private fun Matrix.toSkia() = Matrix44(
this[0, 0],
this[1, 0],
this[2, 0],
this[3, 0],
this[0, 1],
this[1, 1],
this[2, 1],
this[3, 1],
this[0, 2],
this[1, 2],
this[2, 2],
this[3, 2],
this[0, 3],
this[1, 3],
this[2, 3],
this[3, 3]
)
// These constants are chosen to correspond the old implementation of SkFilterQuality:
// https://github.com/google/skia/blob/1f193df9b393d50da39570dab77a0bb5d28ec8ef/src/image/SkImage.cpp#L809
// https://github.com/google/skia/blob/1f193df9b393d50da39570dab77a0bb5d28ec8ef/include/core/SkSamplingOptions.h#L86
private fun FilterQuality.toSkia(): SamplingMode = when (this) {
FilterQuality.Low -> FilterMipmap(FilterMode.LINEAR, MipmapMode.NONE)
FilterQuality.Medium -> FilterMipmap(FilterMode.LINEAR, MipmapMode.NEAREST)
FilterQuality.High -> CubicResampler(1 / 3.0f, 1 / 3.0f)
else -> FilterMipmap(FilterMode.NEAREST, MipmapMode.NONE)
}
} | apache-2.0 | faa97032bfbc3ae4a0e8df40553c248a | 30.711779 | 120 | 0.583386 | 4.04864 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/graphics/vector/compat/AndroidVectorResources.android.kt | 3 | 4066 | /*
* 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.ui.graphics.vector.compat
/**
* Constants used to resolve VectorDrawable attributes during xml inflation
*/
internal object AndroidVectorResources {
// Resources ID generated in the latest R.java for framework.
val STYLEABLE_VECTOR_DRAWABLE_TYPE_ARRAY = intArrayOf(
android.R.attr.name,
android.R.attr.tint,
android.R.attr.height,
android.R.attr.width,
android.R.attr.alpha,
android.R.attr.autoMirrored,
android.R.attr.tintMode,
android.R.attr.viewportWidth,
android.R.attr.viewportHeight
)
val STYLEABLE_VECTOR_DRAWABLE_ALPHA = 4
val STYLEABLE_VECTOR_DRAWABLE_AUTO_MIRRORED = 5
val STYLEABLE_VECTOR_DRAWABLE_HEIGHT = 2
val STYLEABLE_VECTOR_DRAWABLE_NAME = 0
val STYLEABLE_VECTOR_DRAWABLE_TINT = 1
val STYLEABLE_VECTOR_DRAWABLE_TINT_MODE = 6
val STYLEABLE_VECTOR_DRAWABLE_VIEWPORT_HEIGHT = 8
val STYLEABLE_VECTOR_DRAWABLE_VIEWPORT_WIDTH = 7
val STYLEABLE_VECTOR_DRAWABLE_WIDTH = 3
val STYLEABLE_VECTOR_DRAWABLE_GROUP = intArrayOf(
android.R.attr.name,
android.R.attr.pivotX,
android.R.attr.pivotY,
android.R.attr.scaleX,
android.R.attr.scaleY,
android.R.attr.rotation,
android.R.attr.translateX,
android.R.attr.translateY
)
val STYLEABLE_VECTOR_DRAWABLE_GROUP_NAME = 0
val STYLEABLE_VECTOR_DRAWABLE_GROUP_PIVOT_X = 1
val STYLEABLE_VECTOR_DRAWABLE_GROUP_PIVOT_Y = 2
val STYLEABLE_VECTOR_DRAWABLE_GROUP_ROTATION = 5
val STYLEABLE_VECTOR_DRAWABLE_GROUP_SCALE_X = 3
val STYLEABLE_VECTOR_DRAWABLE_GROUP_SCALE_Y = 4
val STYLEABLE_VECTOR_DRAWABLE_GROUP_TRANSLATE_X = 6
val STYLEABLE_VECTOR_DRAWABLE_GROUP_TRANSLATE_Y = 7
val STYLEABLE_VECTOR_DRAWABLE_PATH = intArrayOf(
android.R.attr.name,
android.R.attr.fillColor,
android.R.attr.pathData,
android.R.attr.strokeColor,
android.R.attr.strokeWidth,
android.R.attr.trimPathStart,
android.R.attr.trimPathEnd,
android.R.attr.trimPathOffset,
android.R.attr.strokeLineCap,
android.R.attr.strokeLineJoin,
android.R.attr.strokeMiterLimit,
android.R.attr.strokeAlpha,
android.R.attr.fillAlpha,
// android.R.attr.fillType is in API level 24+ use hardcoded value to extract the attribute if it exists
0x101051E
)
val STYLEABLE_VECTOR_DRAWABLE_PATH_FILL_ALPHA = 12
val STYLEABLE_VECTOR_DRAWABLE_PATH_FILL_COLOR = 1
val STYLEABLE_VECTOR_DRAWABLE_PATH_NAME = 0
val STYLEABLE_VECTOR_DRAWABLE_PATH_PATH_DATA = 2
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_ALPHA = 11
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_COLOR = 3
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_LINE_CAP = 8
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_LINE_JOIN = 9
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_MITER_LIMIT = 10
val STYLEABLE_VECTOR_DRAWABLE_PATH_STROKE_WIDTH = 4
val STYLEABLE_VECTOR_DRAWABLE_PATH_TRIM_PATH_END = 6
val STYLEABLE_VECTOR_DRAWABLE_PATH_TRIM_PATH_OFFSET = 7
val STYLEABLE_VECTOR_DRAWABLE_PATH_TRIM_PATH_START = 5
val STYLEABLE_VECTOR_DRAWABLE_PATH_TRIM_PATH_FILLTYPE = 13
val STYLEABLE_VECTOR_DRAWABLE_CLIP_PATH =
intArrayOf(android.R.attr.name, android.R.attr.pathData)
val STYLEABLE_VECTOR_DRAWABLE_CLIP_PATH_NAME = 0
val STYLEABLE_VECTOR_DRAWABLE_CLIP_PATH_PATH_DATA = 1
} | apache-2.0 | 794e03e3e2cc8adf1eb746ab0fe061e4 | 40.5 | 112 | 0.708805 | 3.703097 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/KotlinScriptDependenciesClassFinder.kt | 1 | 3778 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.core.model
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.NonClasspathClassFinder
import com.intellij.psi.PsiElementFinder
import org.eclipse.core.resources.IFile
import org.jetbrains.kotlin.resolve.jvm.KotlinSafeClassFinder
import java.io.File
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import java.net.URLClassLoader
import org.eclipse.osgi.internal.loader.EquinoxClassLoader
import java.net.URL
class KotlinScriptDependenciesClassFinder(
project: Project,
val eclipseFile: IFile) : NonClasspathClassFinder(project), KotlinSafeClassFinder {
companion object {
fun resetScriptExternalDependencies(file: IFile) {
val environment = getEnvironment(file)
if (environment !is KotlinScriptEnvironment) return
Extensions.getArea(environment.project)
.getExtensionPoint(PsiElementFinder.EP_NAME)
.getExtensions()
.filterIsInstance(KotlinScriptDependenciesClassFinder::class.java)
.forEach {
it.clearCache()
}
}
}
override fun calcClassRoots(): List<VirtualFile> {
return emptyList()
}
private fun fromClassLoader(definition: KotlinScriptDefinition): List<File> {
val classLoader = definition.template.java.classLoader
return classpathFromClassloader(classLoader)
}
private fun classpathFromClassloader(classLoader: ClassLoader): List<File> {
return when (classLoader) {
is URLClassLoader -> {
classLoader.urLs
?.mapNotNull { it.toFile() }
?: emptyList()
}
is EquinoxClassLoader -> {
classLoader.classpathManager.hostClasspathEntries.map { entry ->
entry.bundleFile.baseFile
}
}
else -> {
KotlinLogger.logWarning("Could not get dependencies from $classLoader for script provider")
emptyList()
}
}
}
private fun URL.toFile() =
try {
File(toURI().schemeSpecificPart)
} catch (e: java.net.URISyntaxException) {
if (protocol != "file") null
else File(file)
}
private fun File.classpathEntryToVfs(): VirtualFile? {
if (!exists()) return null
val applicationEnvironment = KotlinScriptEnvironment.getEnvironment(eclipseFile).javaApplicationEnvironment
return when {
isFile -> applicationEnvironment.jarFileSystem.findFileByPath(this.canonicalPath + "!/")
isDirectory -> applicationEnvironment.localFileSystem.findFileByPath(this.canonicalPath)
else -> null
}
}
} | apache-2.0 | f772db456c3e74fa0fe7c31fe41445a2 | 37.561224 | 115 | 0.628904 | 5.336158 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/model/WidgetsTransport.kt | 1 | 521 | package de.tum.`in`.tumcampusapp.component.ui.transportation.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.RoomWarnings
@Entity(tableName = "widgets_transport")
@SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR)
data class WidgetsTransport(
@PrimaryKey
var id: Int = 0,
var station: String = "",
@ColumnInfo(name = "station_id")
var stationId: String = "",
var location: Boolean = false,
var reload: Boolean = false
) | gpl-3.0 | 2679e3b08ef1bfbea997aa094bb20c8d | 28 | 66 | 0.744722 | 4.102362 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/editor/parameters/XPathParameterInfoHandler.kt | 1 | 4955 | /*
* Copyright (C) 2019-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.lang.editor.parameters
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.lang.parameterInfo.*
import uk.co.reecedunn.intellij.plugin.core.sequences.ancestors
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList
import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmVariadic
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmConcatenatingExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.function.*
import uk.co.reecedunn.intellij.plugin.xpm.staticallyKnownFunctions
import xqt.platform.intellij.xpath.XPathTokenProvider
class XPathParameterInfoHandler : ParameterInfoHandler<XPathArgumentList, XpmFunctionDeclaration> {
override fun findElementForParameterInfo(context: CreateParameterInfoContext): XPathArgumentList? {
val e = context.file.findElementAt(context.offset)
val args = e?.ancestors()?.filterIsInstance<XPathArgumentList>()?.firstOrNull()
context.itemsToShow = functionCandidates(args).filter {
if (it.declaredArity == 0)
args?.parent !is XpmArrowFunctionCall
else
true
}.toList().toTypedArray()
return args
}
override fun showParameterInfo(element: XPathArgumentList, context: CreateParameterInfoContext) {
context.showHint(element, element.textOffset, this)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): XPathArgumentList? {
val e = context.file.findElementAt(context.offset)
return e?.ancestors()?.filterIsInstance<XPathArgumentList>()?.firstOrNull()
}
override fun updateParameterInfo(parameterOwner: XPathArgumentList, context: UpdateParameterInfoContext) {
val index =
ParameterInfoUtils.getCurrentParameterIndex(parameterOwner.node, context.offset, XPathTokenProvider.Comma)
context.setCurrentParameter(if (parameterOwner.parent is XpmArrowFunctionCall) index + 1 else index)
}
override fun updateUI(p: XpmFunctionDeclaration?, context: ParameterInfoUIContext) {
if (p == null) return
val parameters = p.parameters
if (parameters.isNotEmpty()) {
val functionCall = context.parameterOwner.parent as XpmFunctionCall
val argument = functionCall.argumentAt(context.currentParameterIndex)
val text = StringBuffer()
val variadicType = p.variadicType
var start = -1
var end = -1
functionCall.bindTo(parameters, variadicType).forEachIndexed { i, binding ->
val match = when (val expr = binding.variableExpression) {
is XpmConcatenatingExpression -> expr === argument || expr.expressions.contains(argument)
else -> expr === argument
}
if (match) {
start = text.length
}
text.append(binding.toString())
if (i == parameters.size - 1 && variadicType === XpmVariadic.Ellipsis) {
text.append(ELLIPSIS_VARIADIC_MARKER)
}
if (match) {
end = text.length
}
if (i < parameters.size - 1) {
text.append(PARAM_SEPARATOR)
}
}
context.setupUIComponentPresentation(
text.toString(),
start, end, false, false, false, context.defaultParameterColor
)
} else {
context.setupUIComponentPresentation(
CodeInsightBundle.message("parameter.info.no.parameters"),
-1, -1, false, false, false, context.defaultParameterColor
)
}
}
private fun functionCandidates(args: XPathArgumentList?): Sequence<XpmFunctionDeclaration> {
val functionName = when (val parent = args?.parent) {
is XpmFunctionCall -> parent.functionReference?.functionName
else -> null
}
return functionName?.staticallyKnownFunctions()?.sortedBy { it.declaredArity }?.distinct() ?: emptySequence()
}
companion object {
private const val PARAM_SEPARATOR = ", "
private const val ELLIPSIS_VARIADIC_MARKER = " ..."
}
}
| apache-2.0 | a96f31ea25ef72738ed656ed5c3823d6 | 42.464912 | 118 | 0.663774 | 5.030457 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/latex/model/rule/ReplaceModelViewWithImage.kt | 2 | 1086 | package org.stepik.android.domain.latex.model.rule
import ru.nobird.android.view.base.ui.extension.toPx
class ReplaceModelViewWithImage : ContentRule {
companion object {
private const val BORDER_RADIUS_DP = 8f
private val modelViewerRegex = Regex("<model-viewer\\s*.*>\\s*.*</model-viewer>")
private val thumbnailRegex = Regex("thumbnail=\"(.*?)\"")
private val srcRegex = Regex("\\ssrc=\"(.*?)\"")
}
override fun process(content: String): String =
modelViewerRegex.replace(content) { matchResult ->
val matchResultValue = matchResult.value ?: ""
val src = thumbnailRegex.find(matchResultValue)?.groups?.get(1)?.value ?: ""
val href = srcRegex.find(matchResultValue)?.groups?.get(1)?.value ?: ""
formARElement(src, href)
}
private fun formARElement(src: String, href: String): String =
"<div style=\"background-image: url($src); border-radius: ${BORDER_RADIUS_DP.toPx()}px;\" " +
"class=\"ar-model\" onclick=\"handleARModel('$href')\"></div>"
} | apache-2.0 | fa3116002aa8db655f3bbcb4d7b1385b | 42.48 | 101 | 0.626151 | 4.082707 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/adaptive/ui/fragments/RecommendationsFragment.kt | 2 | 7116 | package org.stepic.droid.adaptive.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.error_no_connection_with_button.*
import kotlinx.android.synthetic.main.fragment_recommendations.*
import org.stepic.droid.R
import org.stepic.droid.adaptive.ui.adapters.QuizCardsAdapter
import org.stepic.droid.adaptive.ui.animations.RecommendationsFragmentAnimations
import org.stepic.droid.adaptive.ui.dialogs.AdaptiveLevelDialogFragment
import org.stepic.droid.base.App
import org.stepic.droid.base.FragmentBase
import org.stepic.droid.core.presenters.RecommendationsPresenter
import org.stepic.droid.core.presenters.contracts.RecommendationsView
import org.stepic.droid.ui.util.PopupHelper
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.resolveColorAttribute
import org.stepik.android.model.Course
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import javax.inject.Inject
class RecommendationsFragment : FragmentBase(), RecommendationsView {
companion object {
fun newInstance(course: Course): RecommendationsFragment {
val args = Bundle().apply { putParcelable(AppConstants.KEY_COURSE_BUNDLE, course) }
return RecommendationsFragment().apply { arguments = args }
}
private const val MAX_UNFORMATTED_EXP = 1e6
private fun formatExp(exp: Long) = if (exp > MAX_UNFORMATTED_EXP) {
"${exp / 1000}K"
} else {
exp.toString()
}
private const val LEVEL_DIALOG_TAG = "level_dialog"
}
@Inject
lateinit var recommendationsPresenter: RecommendationsPresenter
private lateinit var animations: RecommendationsFragmentAnimations
private var course: Course? = null
private val loadingPlaceholders by lazy { resources.getStringArray(R.array.recommendation_loading_placeholders) }
private var expPopupWindow: PopupWindow? = null
override fun onCreate(savedInstanceState: Bundle?) {
course = arguments?.getParcelable(AppConstants.KEY_COURSE_BUNDLE)
super.onCreate(savedInstanceState)
}
override fun injectComponent() {
App.componentManager()
.adaptiveCourseComponent(course?.id ?: 0)
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_recommendations, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val context = requireContext()
animations = RecommendationsFragmentAnimations(streakSuccessContainer.context)
error.setBackgroundColor(0)
tryAgain.setOnClickListener {
recommendationsPresenter.retry()
}
(activity as? AppCompatActivity)?.let {
it.setSupportActionBar(toolbar)
it.supportActionBar?.setDisplayHomeAsUpEnabled(true)
it.supportActionBar?.setDisplayShowTitleEnabled(false)
}
toolbar.setOnClickListener {
screenManager.showAdaptiveStats(context, course?.id ?: 0)
expPopupWindow?.let { popup ->
if (popup.isShowing) {
popup.dismiss()
}
}
}
streakSuccessContainer.nestedTextView = streakSuccess
streakSuccessContainer.setGradientDrawableParams(streakSuccessContainer.context.resolveColorAttribute(R.attr.colorPrimary), 0f)
}
override fun onAdapter(cardsAdapter: QuizCardsAdapter) {
cardsContainer.setAdapter(cardsAdapter)
}
override fun onLoading() {
progress.visibility = View.VISIBLE
error.visibility = View.GONE
loadingPlaceholder.text = loadingPlaceholders.random()
}
override fun onCardLoaded() {
progress.visibility = View.GONE
cardsContainer.visibility = View.VISIBLE
}
private fun onError() {
cardsContainer.visibility = View.GONE
error.visibility = View.VISIBLE
progress.visibility = View.GONE
}
override fun onConnectivityError() {
errorMessage.setText(R.string.no_connection)
onError()
}
override fun onRequestError() {
errorMessage.setText(R.string.request_error)
onError()
}
private fun onCourseState() {
cardsContainer.visibility = View.GONE
progress.visibility = View.GONE
courseState.visibility = View.VISIBLE
}
override fun onCourseCompleted() {
courseStateText.setText(R.string.adaptive_course_completed)
onCourseState()
}
override fun onCourseNotSupported() {
courseStateText.setText(R.string.adaptive_course_not_supported)
onCourseState()
}
override fun updateExp(
exp: Long,
currentLevelExp: Long,
nextLevelExp: Long,
level: Long
) {
expProgress.progress = (exp - currentLevelExp).toInt()
expProgress.max = (nextLevelExp - currentLevelExp).toInt()
expCounter.text = formatExp(exp)
expLevel.text = getString(R.string.adaptive_exp_title, level)
expLevelNext.text = getString(R.string.adaptive_exp_subtitle, formatExp(nextLevelExp - exp))
}
override fun onStreak(streak: Long) {
expInc.text = getString(R.string.adaptive_exp_inc, streak)
streakSuccess.text = resources.getQuantityString(R.plurals.adaptive_streak_success, streak.toInt(), streak)
if (streak > 1) {
animations.playStreakSuccessAnimationSequence(
root = rootView,
streakSuccessContainer = streakSuccessContainer,
expProgress = expProgress,
expInc = expInc,
expBubble = expBubble
)
} else {
animations.playStreakBubbleAnimation(expInc)
}
}
override fun showExpTooltip() {
expPopupWindow = PopupHelper.showPopupAnchoredToView(requireContext(), expBubble, getString(R.string.adaptive_exp_tooltip_text), withArrow = true)
}
override fun onStreakLost() {
animations.playStreakFailedAnimation(streakFailed, expProgress)
}
override fun showNewLevelDialog(level: Long) {
AdaptiveLevelDialogFragment
.newInstance(level)
.showIfNotExists(childFragmentManager, LEVEL_DIALOG_TAG)
}
override fun onStart() {
super.onStart()
recommendationsPresenter.attachView(this)
}
override fun onStop() {
recommendationsPresenter.detachView(this)
super.onStop()
}
override fun onReleaseComponent() {
App.componentManager()
.releaseAdaptiveCourseComponent(course?.id ?: 0)
}
override fun onDestroy() {
recommendationsPresenter.destroy()
super.onDestroy()
}
} | apache-2.0 | 20ae6e4098b7c5437207f78131800e22 | 32.257009 | 154 | 0.688027 | 4.798382 | false | false | false | false |
greenlaw110/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/com/hexagonkt/Benchmark.kt | 5 | 3722 | package com.hexagonkt
import com.hexagonkt.helpers.Jvm.systemSetting
import com.hexagonkt.serialization.Json
import com.hexagonkt.serialization.convertToMap
import com.hexagonkt.http.server.*
import com.hexagonkt.http.server.jetty.JettyServletAdapter
import com.hexagonkt.http.server.servlet.ServletServer
import com.hexagonkt.settings.SettingsManager
import com.hexagonkt.templates.TemplateManager.render
import com.hexagonkt.templates.TemplatePort
import com.hexagonkt.templates.pebble.PebbleAdapter
import java.util.Locale
import javax.servlet.annotation.WebListener
// DATA CLASSES
internal data class Message(val message: String)
internal data class Fortune(val _id: Int, val message: String)
internal data class World(val _id: Int, val id: Int, val randomNumber: Int)
// CONSTANTS
private const val TEXT_MESSAGE: String = "Hello, World!"
private const val QUERIES_PARAM: String = "queries"
internal val benchmarkStores: Map<String, BenchmarkStore> by lazy {
mapOf(
"mongodb" to BenchmarkMongoDbStore("mongodb"),
"postgresql" to BenchmarkSqlStore("postgresql")
)
}
internal val benchmarkTemplateEngines: Map<String, TemplatePort> by lazy {
mapOf("pebble" to PebbleAdapter)
}
internal val engine by lazy { createEngine() }
private val defaultLocale = Locale.getDefault()
private val router: Router by lazy {
Router {
before {
response.headers["Server"] = "Servlet/3.1"
response.headers["Transfer-Encoding"] = "chunked"
}
get("/plaintext") { ok(TEXT_MESSAGE, "text/plain") }
get("/json") { ok(Message(TEXT_MESSAGE), Json) }
benchmarkStores.forEach { (storeEngine, store) ->
benchmarkTemplateEngines.forEach { templateKind ->
val path = "/$storeEngine/${templateKind.key}/fortunes"
get(path) { listFortunes(store, templateKind.key, templateKind.value) }
}
get("/$storeEngine/db") { dbQuery(store) }
get("/$storeEngine/query") { getWorlds(store) }
get("/$storeEngine/update") { updateWorlds(store) }
}
}
}
internal val benchmarkServer: Server by lazy { Server(engine, router, SettingsManager.settings) }
// UTILITIES
internal fun createEngine(): ServerPort = when (systemSetting("WEBENGINE", "jetty")) {
"jetty" -> JettyServletAdapter()
else -> error("Unsupported server engine")
}
private fun returnWorlds(worldsList: List<World>): List<Map<Any?, Any?>> =
worldsList.map { it.convertToMap() - "_id" }
private fun Call.getWorldsCount(): Int =
queryParametersValues[QUERIES_PARAM]?.firstOrNull()?.toIntOrNull().let {
when {
it == null -> 1
it < 1 -> 1
it > 500 -> 500
else -> it
}
}
// HANDLERS
private fun Call.listFortunes(
store: BenchmarkStore, templateKind: String, templateAdapter: TemplatePort) {
val fortunes = store.findAllFortunes() + Fortune(0, "Additional fortune added at request time.")
val sortedFortunes = fortunes.sortedBy { it.message }
val context = mapOf("fortunes" to sortedFortunes)
response.contentType = "text/html;charset=utf-8"
ok(render(templateAdapter, "fortunes.$templateKind.html", defaultLocale, context))
}
private fun Call.dbQuery(store: BenchmarkStore) {
ok(returnWorlds(store.findWorlds(1)).first(), Json)
}
private fun Call.getWorlds(store: BenchmarkStore) {
ok(returnWorlds(store.findWorlds(getWorldsCount())), Json)
}
private fun Call.updateWorlds(store: BenchmarkStore) {
ok(returnWorlds(store.replaceWorlds(getWorldsCount())), Json)
}
// SERVERS
@WebListener class Web : ServletServer(router)
fun main() {
benchmarkServer.start()
}
| bsd-3-clause | 2daaa09cab30f815e832d4d276a0509e | 31.086207 | 100 | 0.696937 | 4.045652 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt | 1 | 12523 | package info.nightscout.androidaps.dialogs
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.google.common.base.Joiner
import com.google.common.collect.Lists
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction
import info.nightscout.androidaps.databinding.DialogTemptargetBinding
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS
import info.nightscout.androidaps.interfaces.ResourceHelper
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import java.text.DecimalFormat
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class TempTargetDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository
@Inject lateinit var ctx: Context
@Inject lateinit var protectionCheck: ProtectionCheck
private lateinit var reasonList: List<String>
private var queryingProtection = false
private val disposable = CompositeDisposable()
private var _binding: DialogTemptargetBinding? = null
// This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!!
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("duration", binding.duration.value)
savedInstanceState.putDouble("tempTarget", binding.temptarget.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
onCreateViewGeneral()
_binding = DialogTemptargetBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.duration.setParams(savedInstanceState?.getDouble("duration")
?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, binding.okcancel.ok)
if (profileFunction.getUnits() == GlucoseUnit.MMOL)
binding.temptarget.setParams(
savedInstanceState?.getDouble("tempTarget")
?: 8.0,
Constants.MIN_TT_MMOL, Constants.MAX_TT_MMOL, 0.1, DecimalFormat("0.0"), false, binding.okcancel.ok)
else
binding.temptarget.setParams(
savedInstanceState?.getDouble("tempTarget")
?: 144.0,
Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, binding.okcancel.ok)
val units = profileFunction.getUnits()
binding.units.text = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
// temp target
context?.let { context ->
if (repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing)
binding.targetCancel.visibility = View.VISIBLE
else
binding.targetCancel.visibility = View.GONE
reasonList = Lists.newArrayList(
rh.gs(R.string.manual),
rh.gs(R.string.eatingsoon),
rh.gs(R.string.activity),
rh.gs(R.string.hypo)
)
binding.reasonList.setAdapter(ArrayAdapter(context, R.layout.spinner_centered, reasonList))
binding.targetCancel.setOnClickListener { binding.duration.value = 0.0; shortClick(it) }
binding.eatingSoon.setOnClickListener { shortClick(it) }
binding.activity.setOnClickListener { shortClick(it) }
binding.hypo.setOnClickListener { shortClick(it) }
binding.eatingSoon.setOnLongClickListener {
longClick(it)
return@setOnLongClickListener true
}
binding.activity.setOnLongClickListener {
longClick(it)
return@setOnLongClickListener true
}
binding.hypo.setOnLongClickListener {
longClick(it)
return@setOnLongClickListener true
}
binding.durationLabel.labelFor = binding.duration.editTextId
binding.temptargetLabel.labelFor = binding.temptarget.editTextId
}
}
private fun shortClick(v: View) {
v.performLongClick()
if (submit()) dismiss()
}
private fun longClick(v: View) {
when (v.id) {
R.id.eating_soon -> {
binding.temptarget.value = defaultValueHelper.determineEatingSoonTT()
binding.duration.value = defaultValueHelper.determineEatingSoonTTDuration().toDouble()
binding.reasonList.setText(rh.gs(R.string.eatingsoon), false)
}
R.id.activity -> {
binding.temptarget.value = defaultValueHelper.determineActivityTT()
binding.duration.value = defaultValueHelper.determineActivityTTDuration().toDouble()
binding.reasonList.setText(rh.gs(R.string.activity), false)
}
R.id.hypo -> {
binding.temptarget.value = defaultValueHelper.determineHypoTT()
binding.duration.value = defaultValueHelper.determineHypoTTDuration().toDouble()
binding.reasonList.setText(rh.gs(R.string.hypo), false)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()
_binding = null
}
override fun submit(): Boolean {
if (_binding == null) return false
val actions: LinkedList<String> = LinkedList()
var reason = binding.reasonList.text.toString()
val unitResId = if (profileFunction.getUnits() == GlucoseUnit.MGDL) R.string.mgdl else R.string.mmol
val target = binding.temptarget.value
val duration = binding.duration.value.toInt()
if (target != 0.0 && duration != 0) {
actions.add(rh.gs(R.string.reason) + ": " + reason)
actions.add(rh.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + rh.gs(unitResId))
actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, duration))
} else {
actions.add(rh.gs(R.string.stoptemptarget))
reason = rh.gs(R.string.stoptemptarget)
}
if (eventTimeChanged)
actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
activity?.let { activity ->
OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
val units = profileFunction.getUnits()
when(reason) {
rh.gs(R.string.eatingsoon) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
rh.gs(R.string.activity) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
rh.gs(R.string.hypo) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
rh.gs(R.string.manual) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.CUSTOM), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
rh.gs(R.string.stoptemptarget) -> uel.log(Action.CANCEL_TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged })
}
if (target == 0.0 || duration == 0) {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(eventTime))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
} else {
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction(
timestamp = eventTime,
duration = TimeUnit.MINUTES.toMillis(duration.toLong()),
reason = when (reason) {
rh.gs(R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON
rh.gs(R.string.activity) -> TemporaryTarget.Reason.ACTIVITY
rh.gs(R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA
else -> TemporaryTarget.Reason.CUSTOM
},
lowTarget = Profile.toMgdl(target, profileFunction.getUnits()),
highTarget = Profile.toMgdl(target, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
}
if (duration == 10) sp.putBoolean(R.string.key_objectiveusetemptarget, true)
})
}
return true
}
override fun onResume() {
super.onResume()
if(!queryingProtection) {
queryingProtection = true
activity?.let { activity ->
val cancelFail = {
queryingProtection = false
aapsLogger.debug(LTag.APS, "Dialog canceled on resume protection: ${this.javaClass.name}")
ToastUtils.showToastInUiThread(ctx, R.string.dialog_canceled)
dismiss()
}
protectionCheck.queryProtection(activity, BOLUS, { queryingProtection = false }, cancelFail, cancelFail)
}
}
}
}
| agpl-3.0 | 9cec0b2dfd460d5a07b9f5270c8fb293 | 51.179167 | 313 | 0.662701 | 4.723878 | false | false | false | false |
prt2121/android-workspace | ContentProvider/app/src/main/kotlin/com/prt2121/contentprovider/SummonContentProvider.kt | 1 | 2339 | package com.prt2121.contentprovider
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.util.Log
import com.prt2121.contentprovider.InviteContract.BASE_PATH
import com.prt2121.contentprovider.InviteContract.INVITE_DIR
import com.prt2121.contentprovider.InviteContract.INVITE_ITEM
import com.prt2121.contentprovider.InviteContract.MATCHER
/**
* Created by pt2121 on 1/6/16.
*/
open class SummonContentProvider() : ContentProvider() {
var helper: DbHelper? = null
override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
throw UnsupportedOperationException()
}
override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
val db = helper?.writableDatabase
val qb = SQLiteQueryBuilder()
qb.tables = InviteEntry.TABLE_NAME
// val uriType = MATCHER.match(uri)
// if (uriType == INVITE_ITEM) {
//qb.appendWhere("${InviteEntry.INVITE_ID}=${uri?.lastPathSegment}")
// qb.appendWhere("${InviteEntry._ID}=${uri?.lastPathSegment}")
// }
val cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder)
cursor.setNotificationUri(context.contentResolver, uri)
return cursor
}
override fun onCreate(): Boolean {
helper = DbHelper(context)
return helper != null
}
override fun getType(uri: Uri?): String? = null
override fun insert(uri: Uri?, values: ContentValues?): Uri? {
val uriType = MATCHER.match(uri)
val db = helper?.writableDatabase
val id = if (uriType == INVITE_DIR) db?.insert(InviteEntry.TABLE_NAME, null, values) else 0
context.contentResolver.notifyChange(uri, null)
return Uri.parse(BASE_PATH + "/" + id)
}
override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
val uriType = MATCHER.match(uri)
val db = helper?.writableDatabase
val row = if (uriType == INVITE_ITEM) {
db?.update(InviteEntry.TABLE_NAME, values, "${InviteEntry.INVITE_ID}=${uri?.lastPathSegment}", null) ?: 0
} else 0
context.contentResolver.notifyChange(uri, null)
return row
}
} | apache-2.0 | 7d47d2f40ae4f2606f520974bd5af183 | 35.5625 | 149 | 0.721248 | 4.067826 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/CompiledKotlinSettingsScript.kt | 3 | 1792 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.support
import org.gradle.api.initialization.Settings
import org.gradle.api.initialization.dsl.ScriptHandler
import org.gradle.api.internal.ProcessOperations
import org.gradle.api.internal.file.FileOperations
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import org.gradle.api.logging.LoggingManager
import org.gradle.api.plugins.PluginAware
@ImplicitReceiver(Settings::class)
open class CompiledKotlinSettingsScript(
private val host: KotlinScriptHost<Settings>
) : DefaultKotlinScript(SettingsScriptHost(host)), PluginAware by PluginAwareScript(host) {
/**
* The [ScriptHandler] for this script.
*/
val buildscript: ScriptHandler
get() = host.scriptHandler
private
class SettingsScriptHost(val host: KotlinScriptHost<Settings>) : Host {
override fun getLogger(): Logger = Logging.getLogger(Settings::class.java)
override fun getLogging(): LoggingManager = host.target.serviceOf()
override fun getFileOperations(): FileOperations = host.fileOperations
override fun getProcessOperations(): ProcessOperations = host.processOperations
}
}
| apache-2.0 | 4377091c97688fa93a8353db32f3cc00 | 37.12766 | 91 | 0.760045 | 4.424691 | false | false | false | false |
K0zka/finder4j | finder4j-backtrack-examples/src/main/kotlin/com/github/k0zka/finder4j/backtrack/examples/queens/QueensState.kt | 1 | 1899 | package com.github.k0zka.finder4j.backtrack.examples.queens
import com.github.k0zka.finder4j.backtrack.State
class QueensState @JvmOverloads constructor(
val queens: ShortArray = ShortArray(8, { _ -> notSet })
) : State {
val lastQueen: Short
get() {
for (i in queens.indices) {
if (queens[i] == notSet) {
return i.toShort()
}
}
return queens.size.toShort()
}
val isLegal: Boolean
get() = isLegal(queens)
override val complete: Boolean
get() =
queens.any { it == notSet }
override fun toString(): String {
val builder = StringBuilder(81)
builder.append("+----------------+\n")
for (queen in queens) {
builder.append('|')
if (queen != notSet) {
appendNSpaces(builder, queen * 2)
builder.append("X ")
appendNSpaces(builder, (8 - queen.toInt() - 1) * 2)
} else {
appendNSpaces(builder, 8 * 2)
}
builder.append("|\n")
}
builder.append("+----------------+\n")
return builder.toString()
}
private fun appendNSpaces(builder: StringBuilder, nr: Int) {
for (i in 0 until nr) {
builder.append(' ')
}
}
companion object {
private val serialVersionUID = -3147893306213484516L
val notSet = (-1).toShort()
fun isLegal(queens: ShortArray): Boolean {
// take each queen
for (i in 0 until queens.size - 1) {
val checkQueen = queens[i]
// check that it does not hit any other queens
for (j in i + 1 until queens.size) {
val otherQueen = queens[j]
if (isHit(i, checkQueen, j, otherQueen)) {
return false
}
}
}
return true
}
fun isHit(checkQueenPosition: Int, checkQueen: Short?,
otherQueenPosition: Int, otherQueen: Short?): Boolean {
val distance = otherQueenPosition - checkQueenPosition
return (checkQueen == otherQueen
|| checkQueen == (otherQueen!! + distance).toShort()
|| checkQueen == (otherQueen - distance).toShort())
}
}
}
| apache-2.0 | 2b22853a37e12352218957f301a123db | 23.346154 | 61 | 0.630858 | 3.097879 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/HeaderViewHolder.kt | 1 | 1333 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.ViewGroup
import android.widget.TextView
import org.wordpress.android.R
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Header
class HeaderViewHolder(parent: ViewGroup) : BlockListItemViewHolder(
parent,
R.layout.stats_block_header_item
) {
private val startLabel = itemView.findViewById<TextView>(R.id.start_label)
private val endLabel = itemView.findViewById<TextView>(R.id.end_label)
fun bind(item: Header) {
val spannableString = SpannableString(startLabel.resources.getString(item.startLabel))
item.bolds?.forEach { bold ->
spannableString.withBoldSpan(bold)
}
startLabel.text = spannableString
endLabel.setText(item.endLabel)
}
private fun SpannableString.withBoldSpan(boldPart: String): SpannableString {
val boldPartIndex = indexOf(boldPart)
setSpan(
StyleSpan(Typeface.BOLD),
boldPartIndex,
boldPartIndex + boldPart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return this
}
}
| gpl-2.0 | 48be0a9ff9916fe6910917c016c4a32d | 35.027027 | 94 | 0.710428 | 4.39934 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/StatsFragment.kt | 1 | 13701 | package org.wordpress.android.ui.stats.refresh
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.MarginPageTransformer
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayout.Tab
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.StatsFragmentBinding
import org.wordpress.android.ui.ScrollableViewInitializedListener
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureFullScreenOverlayFragment
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType
import org.wordpress.android.ui.main.WPMainNavigationView.PageType.MY_SITE
import org.wordpress.android.ui.mysite.jetpackbadge.JetpackPoweredBottomSheetFragment
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.stats.refresh.StatsViewModel.StatsModuleUiModel
import org.wordpress.android.ui.stats.refresh.lists.StatsListFragment
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.ANNUAL_STATS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.DAYS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.DETAIL
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.INSIGHTS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.INSIGHT_DETAIL
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.MONTHS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_COMMENTS_DETAIL
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_FOLLOWERS_DETAIL
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.TOTAL_LIKES_DETAIL
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.WEEKS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.YEARS
import org.wordpress.android.ui.stats.refresh.lists.sections.insights.UpdateAlertDialogFragment
import org.wordpress.android.ui.stats.refresh.lists.sections.insights.UpdateAlertDialogFragment.Companion.UPDATE_ALERT_DIALOG_TAG
import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider.SiteUpdateResult
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.JetpackBrandingUtils
import org.wordpress.android.util.JetpackBrandingUtils.Screen.STATS
import org.wordpress.android.util.WPSwipeToRefreshHelper
import org.wordpress.android.util.helpers.SwipeToRefreshHelper
import org.wordpress.android.viewmodel.observeEvent
import org.wordpress.android.widgets.WPSnackbar
import javax.inject.Inject
private val statsSections = listOf(INSIGHTS, DAYS, WEEKS, MONTHS, YEARS)
@AndroidEntryPoint
class StatsFragment : Fragment(R.layout.stats_fragment), ScrollableViewInitializedListener {
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var jetpackBrandingUtils: JetpackBrandingUtils
private val viewModel: StatsViewModel by activityViewModels()
private lateinit var swipeToRefreshHelper: SwipeToRefreshHelper
private lateinit var selectedTabListener: SelectedTabListener
private var restorePreviousSearch = false
private var binding: StatsFragmentBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val nonNullActivity = requireActivity()
with(StatsFragmentBinding.bind(view)) {
binding = this
with(nonNullActivity as AppCompatActivity) {
setSupportActionBar(toolbar)
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
}
}
initializeViewModels(nonNullActivity, savedInstanceState == null, savedInstanceState)
initializeViews()
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(WordPress.LOCAL_SITE_ID, activity?.intent?.getIntExtra(WordPress.LOCAL_SITE_ID, 0) ?: 0)
viewModel.onSaveInstanceState(outState)
super.onSaveInstanceState(outState)
}
private fun StatsFragmentBinding.initializeViews() {
val adapter = StatsPagerAdapter(this@StatsFragment)
statsPager.adapter = adapter
statsPager.setPageTransformer(
MarginPageTransformer(resources.getDimensionPixelSize(R.dimen.margin_extra_large))
)
statsPager.offscreenPageLimit = 2
selectedTabListener = SelectedTabListener(viewModel)
TabLayoutMediator(tabLayout, statsPager) { tab, position ->
tab.text = adapter.getTabTitle(position)
}.attach()
tabLayout.addOnTabSelectedListener(selectedTabListener)
swipeToRefreshHelper = WPSwipeToRefreshHelper.buildSwipeToRefreshHelper(pullToRefresh) {
viewModel.onPullToRefresh()
}
disabledView.statsDisabledView.button.setOnClickListener {
viewModel.onEnableStatsModuleClick()
}
}
@SuppressLint("ClickableViewAccessibility")
private fun StatsFragmentBinding.initializeViewModels(
activity: FragmentActivity,
isFirstStart: Boolean,
savedInstanceState: Bundle?
) {
viewModel.onRestoreInstanceState(savedInstanceState)
setupObservers(activity)
viewModel.start(activity.intent)
if (!isFirstStart) {
restorePreviousSearch = true
}
statsPager.setOnTouchListener { _, event ->
swipeToRefreshHelper.setEnabled(false)
if (event.action == MotionEvent.ACTION_UP) {
swipeToRefreshHelper.setEnabled(true)
}
return@setOnTouchListener false
}
viewModel.showJetpackPoweredBottomSheet.observeEvent(viewLifecycleOwner) {
if (isFirstStart) {
JetpackPoweredBottomSheetFragment
.newInstance(it, MY_SITE)
.show(childFragmentManager, JetpackPoweredBottomSheetFragment.TAG)
}
}
viewModel.showJetpackOverlay.observeEvent(viewLifecycleOwner) {
if (isFirstStart) {
JetpackFeatureFullScreenOverlayFragment
.newInstance(JetpackFeatureOverlayScreenType.STATS)
.show(childFragmentManager, JetpackFeatureFullScreenOverlayFragment.TAG)
}
}
}
private fun StatsFragmentBinding.setupObservers(activity: FragmentActivity) {
viewModel.isRefreshing.observe(viewLifecycleOwner, {
it?.let { isRefreshing ->
swipeToRefreshHelper.isRefreshing = isRefreshing
}
})
viewModel.showSnackbarMessage.observe(viewLifecycleOwner, { holder ->
showSnackbar(activity, holder)
})
viewModel.toolbarHasShadow.observe(viewLifecycleOwner, { hasShadow ->
appBarLayout.showShadow(hasShadow == true)
})
viewModel.siteChanged.observeEvent(viewLifecycleOwner, { siteUpdateResult ->
when (siteUpdateResult) {
is SiteUpdateResult.SiteConnected -> viewModel.onSiteChanged()
is SiteUpdateResult.NotConnectedJetpackSite -> getActivity()?.finish()
}
})
viewModel.hideToolbar.observeEvent(viewLifecycleOwner, { hideToolbar ->
appBarLayout.setExpanded(!hideToolbar, true)
})
viewModel.selectedSection.observe(viewLifecycleOwner, { selectedSection ->
selectedSection?.let {
handleSelectedSection(selectedSection)
}
})
viewModel.statsModuleUiModel.observeEvent(viewLifecycleOwner, { event ->
updateUi(event)
})
viewModel.showUpgradeAlert.observeEvent(viewLifecycleOwner) {
UpdateAlertDialogFragment.newInstance().show(childFragmentManager, UPDATE_ALERT_DIALOG_TAG)
}
}
private fun StatsFragmentBinding.updateUi(statsModuleUiModel: StatsModuleUiModel) {
if (statsModuleUiModel.disabledStatsViewVisible) {
disabledView.statsDisabledView.visibility = View.VISIBLE
tabLayout.visibility = View.GONE
pullToRefresh.visibility = View.GONE
if (statsModuleUiModel.disabledStatsProgressVisible) {
disabledView.statsDisabledView.progressBar.visibility = View.VISIBLE
disabledView.statsDisabledView.button.visibility = View.GONE
} else {
disabledView.statsDisabledView.progressBar.visibility = View.GONE
disabledView.statsDisabledView.button.visibility = View.VISIBLE
}
} else {
disabledView.statsDisabledView.visibility = View.GONE
tabLayout.visibility = View.VISIBLE
pullToRefresh.visibility = View.VISIBLE
}
}
private fun StatsFragmentBinding.handleSelectedSection(
selectedSection: StatsSection
) {
val position = when (selectedSection) {
INSIGHTS -> 0
DAYS -> 1
WEEKS -> 2
MONTHS -> 3
YEARS -> 4
DETAIL,
INSIGHT_DETAIL,
TOTAL_LIKES_DETAIL,
TOTAL_COMMENTS_DETAIL,
TOTAL_FOLLOWERS_DETAIL,
ANNUAL_STATS -> null
}
position?.let {
if (statsPager.currentItem != position) {
tabLayout.removeOnTabSelectedListener(selectedTabListener)
statsPager.setCurrentItem(position, false)
tabLayout.addOnTabSelectedListener(selectedTabListener)
}
}
}
private fun showSnackbar(
activity: FragmentActivity,
holder: SnackbarMessageHolder?
) {
val parent = activity.findViewById<View>(R.id.coordinatorLayout)
if (holder != null && parent != null) {
if (holder.buttonTitle == null) {
WPSnackbar.make(
parent,
uiHelpers.getTextOfUiString(requireContext(), holder.message),
Snackbar.LENGTH_LONG
).show()
} else {
val snackbar = WPSnackbar.make(
parent,
uiHelpers.getTextOfUiString(requireContext(), holder.message),
Snackbar.LENGTH_LONG
)
snackbar.setAction(uiHelpers.getTextOfUiString(requireContext(), holder.buttonTitle)) {
holder.buttonAction()
}
snackbar.show()
}
}
}
override fun onScrollableViewInitialized(containerId: Int) {
StatsFragmentBinding.bind(requireView()).appBarLayout.liftOnScrollTargetViewId = containerId
initJetpackBanner(containerId)
}
private fun initJetpackBanner(scrollableContainerId: Int) {
if (jetpackBrandingUtils.shouldShowJetpackBranding()) {
binding?.root?.post {
val jetpackBannerView = binding?.jetpackBanner?.root ?: return@post
val scrollableView = binding?.root?.findViewById<View>(scrollableContainerId) as? RecyclerView
?: return@post
jetpackBrandingUtils.showJetpackBannerIfScrolledToTop(jetpackBannerView, scrollableView)
jetpackBrandingUtils.initJetpackBannerAnimation(jetpackBannerView, scrollableView)
if (jetpackBrandingUtils.shouldShowJetpackPoweredBottomSheet()) {
binding?.jetpackBanner?.root?.setOnClickListener {
jetpackBrandingUtils.trackBannerTapped(STATS)
JetpackPoweredBottomSheetFragment
.newInstance()
.show(childFragmentManager, JetpackPoweredBottomSheetFragment.TAG)
}
}
}
}
}
}
class StatsPagerAdapter(private val parent: Fragment) : FragmentStateAdapter(parent) {
override fun getItemCount(): Int = statsSections.size
override fun createFragment(position: Int): Fragment {
return StatsListFragment.newInstance(statsSections[position])
}
fun getTabTitle(position: Int): CharSequence {
return parent.context?.getString(statsSections[position].titleRes).orEmpty()
}
}
private class SelectedTabListener(val viewModel: StatsViewModel) : OnTabSelectedListener {
override fun onTabReselected(tab: Tab?) {
}
override fun onTabUnselected(tab: Tab?) {
}
override fun onTabSelected(tab: Tab) {
viewModel.onSectionSelected(statsSections[tab.position])
}
}
| gpl-2.0 | c7142c339762c73d1e4e2c495342466e | 41.682243 | 129 | 0.697175 | 5.255466 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/details/adapters/viewholders/ThreatContextLinesViewHolder.kt | 1 | 1102 | package org.wordpress.android.ui.jetpack.scan.details.adapters.viewholders
import android.view.ViewGroup
import org.wordpress.android.databinding.ThreatDetailsListContextLinesItemBinding
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import org.wordpress.android.ui.jetpack.common.viewholders.JetpackViewHolder
import org.wordpress.android.ui.jetpack.scan.details.ThreatDetailsListItemState.ThreatContextLinesItemState
import org.wordpress.android.ui.jetpack.scan.details.adapters.ThreatContextLinesAdapter
class ThreatContextLinesViewHolder(parent: ViewGroup) : JetpackViewHolder<ThreatDetailsListContextLinesItemBinding>(
parent,
ThreatDetailsListContextLinesItemBinding::inflate
) {
override fun onBind(itemUiState: JetpackListItemState) = with(binding) {
val contextLinesItemState = itemUiState as ThreatContextLinesItemState
if (recyclerView.adapter == null) {
recyclerView.adapter = ThreatContextLinesAdapter()
}
(recyclerView.adapter as ThreatContextLinesAdapter).update(contextLinesItemState.lines)
}
}
| gpl-2.0 | eb6b95a8dc54fa1f804f1be15de7b8b5 | 51.47619 | 116 | 0.815789 | 4.75 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertForEachToForLoopIntention.kt | 3 | 4327 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
class ConvertForEachToForLoopIntention : SelfTargetingOffsetIndependentIntention<KtSimpleNameExpression>(
KtSimpleNameExpression::class.java, KotlinBundle.lazyMessage("replace.with.a.for.loop")
) {
companion object {
private const val FOR_EACH_NAME = "forEach"
private val FOR_EACH_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$FOR_EACH_NAME" }.toSet()
}
}
override fun isApplicableTo(element: KtSimpleNameExpression): Boolean {
if (element.getReferencedName() != FOR_EACH_NAME) return false
val data = extractData(element) ?: return false
if (data.functionLiteral.valueParameters.size > 1) return false
if (data.functionLiteral.bodyExpression == null) return false
return true
}
override fun applyTo(element: KtSimpleNameExpression, editor: Editor?) {
val (expressionToReplace, receiver, functionLiteral, context) = extractData(element)!!
val commentSaver = CommentSaver(expressionToReplace)
val loop = generateLoop(functionLiteral, receiver, context)
val result = expressionToReplace.replace(loop) as KtForExpression
result.loopParameter?.also { editor?.caretModel?.moveToOffset(it.startOffset) }
commentSaver.restore(result)
}
private data class Data(
val expressionToReplace: KtExpression,
val receiver: KtExpression,
val functionLiteral: KtLambdaExpression,
val context: BindingContext
)
private fun extractData(nameExpr: KtSimpleNameExpression): Data? {
val parent = nameExpr.parent
val expression = (when (parent) {
is KtCallExpression -> parent.parent as? KtDotQualifiedExpression
is KtBinaryExpression -> parent
else -> null
} ?: return null) as KtExpression //TODO: submit bug
val context = expression.analyze()
val resolvedCall = expression.getResolvedCall(context) ?: return null
if (DescriptorUtils.getFqName(resolvedCall.resultingDescriptor).toString() !in FOR_EACH_FQ_NAMES) return null
val receiver = resolvedCall.call.explicitReceiver as? ExpressionReceiver ?: return null
val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return null
val functionLiteral = argument.getArgumentExpression() as? KtLambdaExpression ?: return null
return Data(expression, receiver.expression, functionLiteral, context)
}
private fun generateLoop(functionLiteral: KtLambdaExpression, receiver: KtExpression, context: BindingContext): KtExpression {
val factory = KtPsiFactory(functionLiteral)
val body = functionLiteral.bodyExpression!!
val function = functionLiteral.functionLiteral
body.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunction(context) == function) {
it.replace(factory.createExpression("continue"))
}
}
val loopRange = KtPsiUtil.safeDeparenthesize(receiver)
val parameter = functionLiteral.valueParameters.singleOrNull()
return factory.createExpressionByPattern("for($0 in $1){ $2 }", parameter ?: "it", loopRange, body.allChildren)
}
}
| apache-2.0 | 60c5c310fd8144bfd43f725dd5884eed | 45.031915 | 158 | 0.73492 | 5.15733 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt | 1 | 14844 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate.compilation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.backend.common.output.OutputFile
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.KotlinCodegenFacade
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus
import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_CLASS_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.GENERATED_FUNCTION_NAME
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledCodeFragmentData.MethodSignature
import org.jetbrains.kotlin.idea.debugger.evaluate.getResolutionFacadeForCodeFragment
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo
import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor
import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.utils.Printer
class CodeFragmentCodegenException(val reason: Exception) : Exception()
class CodeFragmentCompiler(private val executionContext: ExecutionContext, private val status: EvaluationStatus) {
companion object {
fun useIRFragmentCompiler(): Boolean =
Registry.get("debugger.kotlin.evaluator.use.jvm.ir.backend").asBoolean()
}
data class CompilationResult(
val classes: List<ClassToLoad>,
val parameterInfo: CodeFragmentParameterInfo,
val localFunctionSuffixes: Map<CodeFragmentParameter.Dumb, String>,
val mainMethodSignature: MethodSignature
)
fun compile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
val result = ReadAction.nonBlocking<Result<CompilationResult>> {
try {
Result.success(doCompile(codeFragment, filesToCompile, bindingContext, moduleDescriptor))
} catch (ex: ProcessCanceledException) {
throw ex
} catch (ex: Exception) {
Result.failure(ex)
}
}.executeSynchronously()
return result.getOrThrow()
}
private fun initBackend(codeFragment: KtCodeFragment): FragmentCompilerCodegen {
return if (useIRFragmentCompiler()) {
IRFragmentCompilerCodegen()
} else {
OldFragmentCompilerCodegen(codeFragment)
}
}
private fun doCompile(
codeFragment: KtCodeFragment, filesToCompile: List<KtFile>,
bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor
): CompilationResult {
require(codeFragment is KtBlockCodeFragment || codeFragment is KtExpressionCodeFragment) {
"Unsupported code fragment type: $codeFragment"
}
val project = codeFragment.project
val resolutionFacade = getResolutionFacadeForCodeFragment(codeFragment)
@OptIn(FrontendInternals::class)
val resolveSession = resolutionFacade.getFrontendService(ResolveSession::class.java)
val moduleDescriptorWrapper = EvaluatorModuleDescriptor(codeFragment, moduleDescriptor, filesToCompile, resolveSession)
val defaultReturnType = moduleDescriptor.builtIns.unitType
val returnType = getReturnType(codeFragment, bindingContext, defaultReturnType)
val fragmentCompilerBackend = initBackend(codeFragment)
val compilerConfiguration = CompilerConfiguration().apply {
languageVersionSettings = codeFragment.languageVersionSettings
fragmentCompilerBackend.configureCompiler(this)
}
val parameterInfo = fragmentCompilerBackend.computeFragmentParameters(executionContext, codeFragment, bindingContext, status)
val (classDescriptor, methodDescriptor) = createDescriptorsForCodeFragment(
codeFragment, Name.identifier(GENERATED_CLASS_NAME), Name.identifier(GENERATED_FUNCTION_NAME),
parameterInfo, returnType, moduleDescriptorWrapper.packageFragmentForEvaluator
)
fragmentCompilerBackend.initCodegen(classDescriptor, methodDescriptor, parameterInfo)
val generationState = GenerationState.Builder(
project, ClassBuilderFactories.BINARIES, moduleDescriptorWrapper,
bindingContext, filesToCompile, compilerConfiguration
).apply {
fragmentCompilerBackend.configureGenerationState(
this,
bindingContext,
compilerConfiguration,
classDescriptor,
methodDescriptor,
parameterInfo
)
generateDeclaredClassFilter(GeneratedClassFilterForCodeFragment(codeFragment))
}.build()
try {
KotlinCodegenFacade.compileCorrectFiles(generationState)
return fragmentCompilerBackend.extractResult(methodDescriptor, parameterInfo, generationState).also {
generationState.destroy()
}
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Exception) {
throw CodeFragmentCodegenException(e)
} finally {
fragmentCompilerBackend.cleanupCodegen()
}
}
private class GeneratedClassFilterForCodeFragment(private val codeFragment: KtCodeFragment) : GenerationState.GenerateClassFilter() {
override fun shouldGeneratePackagePart(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") file: KtFile) = file == codeFragment
override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.containingFile == codeFragment
override fun shouldGenerateCodeFragment(script: KtCodeFragment) = script == this.codeFragment
override fun shouldGenerateScript(script: KtScript) = false
}
private fun getReturnType(
codeFragment: KtCodeFragment,
bindingContext: BindingContext,
defaultReturnType: SimpleType
): KotlinType {
return when (codeFragment) {
is KtExpressionCodeFragment -> {
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, codeFragment.getContentElement()]
typeInfo?.type ?: defaultReturnType
}
is KtBlockCodeFragment -> {
val blockExpression = codeFragment.getContentElement()
val lastStatement = blockExpression.statements.lastOrNull() ?: return defaultReturnType
val typeInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, lastStatement]
typeInfo?.type ?: defaultReturnType
}
else -> defaultReturnType
}
}
private fun createDescriptorsForCodeFragment(
declaration: KtCodeFragment,
className: Name,
methodName: Name,
parameterInfo: CodeFragmentParameterInfo,
returnType: KotlinType,
packageFragmentDescriptor: PackageFragmentDescriptor
): Pair<ClassDescriptor, FunctionDescriptor> {
val classDescriptor = ClassDescriptorImpl(
packageFragmentDescriptor, className, Modality.FINAL, ClassKind.OBJECT,
emptyList(),
KotlinSourceElement(declaration),
false,
LockBasedStorageManager.NO_LOCKS
)
val methodDescriptor = SimpleFunctionDescriptorImpl.create(
classDescriptor, Annotations.EMPTY, methodName,
CallableMemberDescriptor.Kind.SYNTHESIZED, classDescriptor.source
)
val parameters = parameterInfo.parameters.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
methodDescriptor, null, index, Annotations.EMPTY, Name.identifier("p$index"),
parameter.targetType,
declaresDefaultValue = false,
isCrossinline = false,
isNoinline = false,
varargElementType = null,
source = SourceElement.NO_SOURCE
)
}
methodDescriptor.initialize(
null, classDescriptor.thisAsReceiverParameter, emptyList(), emptyList(),
parameters, returnType, Modality.FINAL, DescriptorVisibilities.PUBLIC
)
val memberScope = EvaluatorMemberScopeForMethod(methodDescriptor)
val constructor = ClassConstructorDescriptorImpl.create(classDescriptor, Annotations.EMPTY, true, classDescriptor.source)
classDescriptor.initialize(memberScope, setOf(constructor), constructor)
return Pair(classDescriptor, methodDescriptor)
}
}
private class EvaluatorMemberScopeForMethod(private val methodDescriptor: SimpleFunctionDescriptor) : MemberScopeImpl() {
override fun getContributedFunctions(name: Name, location: LookupLocation): Collection<SimpleFunctionDescriptor> {
return if (name == methodDescriptor.name) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return if (kindFilter.accepts(methodDescriptor) && nameFilter(methodDescriptor.name)) {
listOf(methodDescriptor)
} else {
emptyList()
}
}
override fun getFunctionNames() = setOf(methodDescriptor.name)
override fun printScopeStructure(p: Printer) {
p.println(this::class.java.simpleName)
}
}
private class EvaluatorModuleDescriptor(
val codeFragment: KtCodeFragment,
val moduleDescriptor: ModuleDescriptor,
filesToCompile: List<KtFile>,
resolveSession: ResolveSession
) : ModuleDescriptor by moduleDescriptor {
private val declarationProvider = object : PackageMemberDeclarationProvider {
private val rootPackageFiles =
filesToCompile.filter { it.packageFqName == FqName.ROOT } + codeFragment
override fun getPackageFiles() = rootPackageFiles
override fun containsFile(file: KtFile) = file in rootPackageFiles
override fun getDeclarationNames() = emptySet<Name>()
override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean) = emptyList<KtDeclaration>()
override fun getClassOrObjectDeclarations(name: Name) = emptyList<KtClassOrObjectInfo<*>>()
override fun getAllDeclaredSubPackages(nameFilter: (Name) -> Boolean) = emptyList<FqName>()
override fun getFunctionDeclarations(name: Name) = emptyList<KtNamedFunction>()
override fun getPropertyDeclarations(name: Name) = emptyList<KtProperty>()
override fun getTypeAliasDeclarations(name: Name) = emptyList<KtTypeAlias>()
override fun getDestructuringDeclarationsEntries(name: Name) = emptyList<KtDestructuringDeclarationEntry>()
override fun getScriptDeclarations(name: Name) = emptyList<KtScriptInfo>()
}
// NOTE: Without this override, psi2ir complains when introducing new symbol
// when creating an IrFileImpl in `createEmptyIrFile`.
override fun getOriginal(): DeclarationDescriptor {
return this
}
val packageFragmentForEvaluator = LazyPackageDescriptor(this, FqName.ROOT, resolveSession, declarationProvider)
val rootPackageDescriptorWrapper: PackageViewDescriptor =
object : DeclarationDescriptorImpl(Annotations.EMPTY, FqName.ROOT.shortNameOrSpecial()), PackageViewDescriptor {
private val rootPackageDescriptor = moduleDescriptor.safeGetPackage(FqName.ROOT)
override fun getContainingDeclaration() = rootPackageDescriptor.containingDeclaration
override val fqName get() = rootPackageDescriptor.fqName
override val module get() = this@EvaluatorModuleDescriptor
override val memberScope by lazy {
if (fragments.isEmpty()) {
MemberScope.Empty
} else {
val scopes = fragments.map { it.getMemberScope() } + SubpackagesScope(module, fqName)
ChainedMemberScope.create("package view scope for $fqName in ${module.name}", scopes)
}
}
override val fragments = listOf(packageFragmentForEvaluator)
override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R {
return visitor.visitPackageViewDescriptor(this, data)
}
}
override fun getPackage(fqName: FqName): PackageViewDescriptor =
if (fqName != FqName.ROOT) {
moduleDescriptor.safeGetPackage(fqName)
} else {
rootPackageDescriptorWrapper
}
private fun ModuleDescriptor.safeGetPackage(fqName: FqName): PackageViewDescriptor =
try {
getPackage(fqName)
} catch (e: InvalidModuleException) {
throw ProcessCanceledException(e)
}
}
internal val OutputFile.internalClassName: String
get() = relativePath.removeSuffix(".class").replace('/', '.')
| apache-2.0 | c36f3d06f84c181e49292c35d2ad01d9 | 44.956656 | 158 | 0.719078 | 5.878812 | false | false | false | false |
ChristopherGittner/OSMBugs | app/src/main/java/org/gittner/osmbugs/osmose/OsmoseInfoWindow.kt | 1 | 936 | package org.gittner.osmbugs.osmose
import android.view.View
import org.gittner.osmbugs.R
import org.gittner.osmbugs.databinding.OsmoseMarkerBinding
import org.gittner.osmbugs.ui.ErrorInfoWindow
import org.osmdroid.views.MapView
class OsmoseInfoWindow(map: MapView) : ErrorInfoWindow(R.layout.osmose_marker, map) {
private val mBinding: OsmoseMarkerBinding = OsmoseMarkerBinding.bind(view)
override fun onOpen(item: Any?) {
super.onOpen(item)
val error = (item as OsmoseMarker).mError
mBinding.apply {
txtvTitle.text = error.Title
txtvSubTitle.text = error.SubTitle
imgIcon.setImageDrawable(error.Type.Icon)
if (error.Elements.size == 0) {
lstvElements.visibility = View.GONE
}
lstvElements.adapter = OsmoseElementAdapter(mMapView.context, error.Elements)
}
}
override fun onClose() {
}
} | mit | 14cba3c6d30c6c35d2da02ab0d27954a | 27.393939 | 89 | 0.679487 | 3.916318 | false | false | false | false |
KSP-KOS/EditorTools | IDEA/src/main/java/ksp/kos/ideaplugin/reference/context/FileContext.kt | 2 | 4458 | package ksp.kos.ideaplugin.reference.context
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiManager
import ksp.kos.ideaplugin.KerboScriptFile
import ksp.kos.ideaplugin.dataflow.ReferenceFlow
import ksp.kos.ideaplugin.reference.OccurrenceType
import ksp.kos.ideaplugin.reference.ReferableType
import ksp.kos.ideaplugin.reference.Reference
import java.net.URL
/**
* Created on 08/10/16.
*
* @author ptasha
*/
abstract class FileContext protected constructor(
parent: LocalContext?,
private val name: String,
resolvers: List<ReferenceResolver<LocalContext>>,
) : LocalContext(parent, resolvers), ReferenceFlow<FileContext>, FileDuality {
constructor(parent: LocalContext?, name: String, fileResolver: FileContextResolver)
: this(parent, name, createResolvers(fileResolver))
override fun getKingdom(): LocalContext = this
override fun getReferableType(): ReferableType = ReferableType.FILE
override fun getName(): String = name
val imports: Map<String, Duality>
get() = getDeclarations(ReferableType.FILE)
override fun registerUnknown(type: ReferableType, name: String, element: Duality) {
if (type == ReferableType.FILE) {
addDefinition(type, KerboScriptFile.stripExtension(name), element)
} else {
super.registerUnknown(type, name, element)
}
}
class FileResolver(private val fileContextResolver: FileContextResolver) : ReferenceResolver<LocalContext> {
override fun resolve(context: LocalContext, reference: Reference, createAllowed: Boolean): Duality? =
if (reference.referableType == ReferableType.FILE) {
fileContextResolver.resolveFile(reference.name)
} else {
null
}
}
override fun getSemantics(): FileContext = this
class ImportsResolver(private val fileContextResolver: FileContextResolver) : ReferenceResolver<LocalContext> {
override fun resolve(context: LocalContext, reference: Reference, createAllowed: Boolean): Duality? =
context.getDeclarations(ReferableType.FILE)
.values
.mapNotNull { run ->
fileContextResolver.resolveFile(run.name)
?.semantics
?.findLocalDeclaration(reference, OccurrenceType.GLOBAL)
}
.firstOrNull()
}
class BuiltinResolver : ReferenceResolver<LocalContext> {
override fun resolve(context: LocalContext, reference: Reference, createAllowed: Boolean): Duality? {
if (ksFile == null) {
tryGetBuiltinKsFile()
}
return ksFile?.semantics?.findLocalDeclaration(reference, OccurrenceType.GLOBAL)
}
companion object {
private var ksFile: KerboScriptFile? = null
private fun URL.toVirtualFile(): VirtualFile? {
val urlStr = VfsUtilCore.convertFromUrl(this)
return VirtualFileManager.getInstance().findFileByUrl(urlStr)
}
private fun tryGetBuiltinKsFile() {
val builtinVirtualFile = BuiltinResolver::class.java.classLoader
.getResource("builtin.ks")
?.toVirtualFile()
?: return
val project = ProjectManager.getInstance().defaultProject
val psiFile = PsiManager.getInstance(project).findFile(builtinVirtualFile)
ksFile = psiFile as? KerboScriptFile
}
}
}
private class VirtualResolver : ParentResolver() {
override fun resolve(context: LocalContext, reference: Reference, createAllowed: Boolean): Duality? =
if (!createAllowed) null else super.resolve(context, reference, createAllowed)
}
companion object {
@JvmStatic
fun createResolvers(fileResolver: FileContextResolver): MutableList<ReferenceResolver<LocalContext>> =
mutableListOf(
FileResolver(fileResolver),
LocalResolver(),
VirtualResolver(),
ImportsResolver(fileResolver),
BuiltinResolver(), // Make sure this is last, to allow shadowing of builtin values
)
}
}
| gpl-3.0 | 3d97604f21ea5549bf4f1dc6ec0d7e5c | 38.105263 | 115 | 0.658591 | 5.083238 | false | false | false | false |
carltonwhitehead/crispy-fish | library/src/main/kotlin/org/coner/crispyfish/filetype/ecf/EventControlFile.kt | 1 | 2115 | package org.coner.crispyfish.filetype.ecf
import org.coner.crispyfish.datatype.underscorepairs.SimpleStringUnderscorePairReader
import org.coner.crispyfish.filetype.classdefinition.ClassDefinitionFile
import org.coner.crispyfish.filetype.registration.RegistrationFileLocator
import org.coner.crispyfish.filetype.staging.SimpleStringStagingLineReader
import org.coner.crispyfish.filetype.staging.StagingFile
import org.coner.crispyfish.filetype.staging.StagingFileAssistant
import org.coner.crispyfish.filetype.staging.StagingFileLocator
import org.coner.crispyfish.model.EventDay
import org.coner.crispyfish.query.CategoriesQuery
import org.coner.crispyfish.query.HandicapsQuery
import org.coner.crispyfish.query.RegistrationsQuery
import java.io.File
import java.io.FileNotFoundException
class EventControlFile(
val file: File,
val classDefinitionFile: ClassDefinitionFile,
val isTwoDayEvent: Boolean,
val conePenalty: Int,
private val ecfAssistant: EventControlFileAssistant = EventControlFileAssistant(),
private val stagingFileAssistant: StagingFileAssistant = StagingFileAssistant()
) {
init {
if (!ecfAssistant.isEventControlFile(file)) {
throw NotEventControlFileException(file)
}
}
val registrationFileLocator by lazy { RegistrationFileLocator(this) }
fun registrationFile() = registrationFileLocator.locate()
val stagingFileLocator by lazy { StagingFileLocator(this) }
fun stagingFile(eventDay: EventDay = EventDay.ONE) = StagingFile(
file = stagingFileLocator.locate(eventDay) ?: throw FileNotFoundException(),
reader = SimpleStringStagingLineReader(SimpleStringUnderscorePairReader()),
assistant = stagingFileAssistant
)
fun queryCategories() = CategoriesQuery(classDefinitionFile).query()
fun queryHandicaps() = HandicapsQuery(classDefinitionFile).query()
fun queryRegistrations() = RegistrationsQuery(
eventControlFile = this,
categories = queryCategories(),
handicaps = queryHandicaps()
).query()
}
| gpl-2.0 | 0d743a8a685845181d7610318d157533 | 38.90566 | 90 | 0.767849 | 4.710468 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.