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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JiaweiWu/GiphyApp | app/src/main/java/com/jwu5/giphyapp/MainActivity.kt | 1 | 2971 | package com.jwu5.giphyapp
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.jwu5.giphyapp.adapters.GiphyFragmentPagerAdapter
import com.jwu5.giphyapp.dataSingleton.SavedFavorites
import com.jwu5.giphyapp.network.model.GiphyModel
import java.util.LinkedHashMap
/*
Freshworks Android Giphy Sample App
The Assignment:
Use the Giphy API to create an application which allows user's to search, view, and favourite gifs.
Specifications:
There will be one activity with two Fragments.
The fragments should be swipeable using a tablayout and viewpager.
First Fragment:
Contains a search bar at the top.
Contains a recycler view that displays searched gifs.
Loading indicator while searching.
The default items in the recycler view should be the trending gifs.
Second Fragment:
Contains a recycler view that displays a grid of favourited gifs stored locally.
List/Grid Item:
Should contain a view of the gif running.
Should contain a favourite button which allows favouriting and unfavouriting.
The favourited items should be stored locally on the device.
Bonus:
Use Android MVP or MVVVM architecture.
Use RxJava
Use Kotlin instead of Java.
Add pagination (infinite scrolling) to the gif lists.
*/
class MainActivity : AppCompatActivity() {
private var mGiphyFragmentPagerAdapter: GiphyFragmentPagerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
mGiphyFragmentPagerAdapter = GiphyFragmentPagerAdapter(supportFragmentManager)
val viewPager = findViewById(R.id.main_activity_view_pager) as ViewPager?
viewPager!!.adapter = mGiphyFragmentPagerAdapter
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixel: Int) {
}
override fun onPageSelected(position: Int) {
val fragment = mGiphyFragmentPagerAdapter!!.getFragment(position)
fragment?.onResume()
}
override fun onPageScrollStateChanged(state: Int) {
}
})
val tabLayout = findViewById(R.id.main_activity_tabs) as TabLayout?
tabLayout!!.setupWithViewPager(viewPager)
}
override fun onStart() {
super.onStart()
SavedFavorites.instance.favorites = utils.loadFromFile(FILENAME, this)
}
public override fun onPause() {
super.onPause()
utils.saveInFile(SavedFavorites.instance.favorites, FILENAME, this)
}
companion object {
private val FILENAME = "file.sav"
}
}
| mit | 6df2e988c822f2ee10d58749cb5bc26f | 32.382022 | 105 | 0.744194 | 4.715873 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/sequentialparsers/LexerBasedTokensCache.kt | 1 | 1796 | package org.intellij.markdown.parser.sequentialparsers
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.lexer.MarkdownLexer
import java.util.*
class LexerBasedTokensCache(lexer: MarkdownLexer) : TokensCache() {
override val cachedTokens: List<TokensCache.TokenInfo>
override val filteredTokens: List<TokensCache.TokenInfo>
override val originalText: CharSequence
override val originalTextRange: IntRange
init {
val (_cachedTokens, _filteredTokens) = cacheTokens(lexer)
cachedTokens = _cachedTokens
filteredTokens = _filteredTokens
originalText = lexer.originalText
originalTextRange = lexer.bufferStart..lexer.bufferEnd - 1
verify()
}
companion object {
private fun isWhitespace(elementType: IElementType?): Boolean {
return elementType == MarkdownTokenTypes.WHITE_SPACE
}
data class ResultOfCaching(val cachedTokens : List<TokensCache.TokenInfo>, val filteredTokens : List<TokensCache.TokenInfo>)
private fun cacheTokens(lexer: MarkdownLexer) : ResultOfCaching {
val cachedTokens = ArrayList<TokensCache.TokenInfo>()
val filteredTokens = ArrayList<TokensCache.TokenInfo>()
while (lexer.type != null) {
val info = TokensCache.TokenInfo(lexer.type!!, lexer.tokenStart, lexer.tokenEnd, cachedTokens.size, -1)
cachedTokens.add(info)
if (!isWhitespace(info.type)) {
info.normIndex = filteredTokens.size
filteredTokens.add(info)
}
lexer.advance()
}
return ResultOfCaching(cachedTokens, filteredTokens)
}
}
}
| apache-2.0 | 5ca4af34a9b957d9675303f904927a07 | 34.92 | 132 | 0.669822 | 4.880435 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/hints/ranges/simple.kt | 5 | 1295 | val range = 0<# ≤ #>..<# ≤ #>10
fun foo() {
for (index in 0<# ≤ #> .. <# ≤ #>100) {}
for (index in 'a'<# ≤ #> .. <# ≤ #>'z') {}
for (index in 0L<# ≤ #> .. <# ≤ #>100L) {}
for (index in 0<# ≤ #> until <# < #>100) {}
for (index in 'a'<# ≤ #> until <# < #>'z') {}
for (index in 0L<# ≤ #> until <# < #>100L) {}
for (index in 100<# ≥ #> downTo <# ≥ #>0) {}
for (index in 'z'<# ≥ #> downTo <# ≥ #>'a') {}
for (index in 100L<# ≥ #> downTo <# ≥ #>0L) {}
for (i in 0 until 0<# ≤ #>..<# ≤ #>5 ) {}
for (i in 1<# ≤ #> until <# < #>10 step 2) {}
run {
val left: Short = 0
val right: Short = 10
for (i in left<# ≤ #> .. <# ≤ #>right) {}
for (i in left<# ≤ #> until <# < #>right) {}
for (index in right<# ≥ #> downTo <# ≥ #>left) {}
}
for (index in someVeryVeryLongLongLongLongFunctionName(0)<# ≤ #> .. <# ≤ #>someVeryVeryLongLongLongLongFunctionName(100)) {}
}
private infix fun Int.until(intRange: IntRange): IntRange = TODO()
private fun someVeryVeryLongLongLongLongFunctionName(x: Int): Int = x
private fun check(x: Int, y: Int) {
val b = x in 8<# ≤ #>..<# ≤ #>9
if (x in 7<# ≤ #>..<# ≤ #>9 && y in 5<# ≤ #>..<# ≤ #>9) {
}
}
| apache-2.0 | 799ab7e45548bf007d104e90bf186225 | 34.114286 | 128 | 0.445077 | 2.513292 | false | false | false | false |
nico-gonzalez/K-Places | presentation/src/main/java/com/edreams/android/workshops/kotlin/presentation/venues/VenuesViewModel.kt | 1 | 2073 | package com.edreams.android.workshops.kotlin.presentation.venues
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.edreams.android.workshops.kotlin.domain.interactor.GetVenues
import com.edreams.android.workshops.kotlin.domain.mapper.Mapper
import com.edreams.android.workshops.kotlin.domain.model.VenueModel
import com.edreams.android.workshops.kotlin.presentation.resources.ResourceProvider
import com.edreams.android.workshops.kotlin.presentation.venues.model.VenueUiModel
import com.edreams.android.workshops.kotlin.presentation.venues.model.VenuesUiModel
import com.edreams.android.workshops.kotlin.presentation.viewmodel.SingleLiveEvent
import javax.inject.Inject
class VenuesViewModel @Inject constructor(
private val getVenues: GetVenues,
private val mapper: Mapper<VenueModel, VenueUiModel>,
private val resourceProvider: ResourceProvider) : ViewModel() {
private val venues: MutableLiveData<VenuesUiModel> = MutableLiveData()
private val emptySearchError: MutableLiveData<String> = MutableLiveData()
private val selectedVenue: MutableLiveData<VenueUiModel> = SingleLiveEvent()
fun venues() = venues
fun selectedVenue() = selectedVenue
fun emptySearchError() = emptySearchError
fun loadVenues(near: String): LiveData<VenuesUiModel> = venues.apply {
value = VenuesUiModel.progress()
getVenues.execute(near,
{ value = VenuesUiModel.success(mapper.map(it.value)) },
{ value = VenuesUiModel.error(it.error.localizedMessage) })
}
fun onSearch(queryString: String) = venues.apply {
if (queryString.isEmpty()) {
emptySearchError.value = resourceProvider.emptyVenueSearchErrorMessage()
return@apply
}
value = VenuesUiModel.progress()
getVenues.execute(queryString,
{ value = VenuesUiModel.success(mapper.map(it.value)) },
{ value = VenuesUiModel.error(it.error.localizedMessage) })
}
fun onVenueSelected(venue: VenueUiModel) = selectedVenue.apply {
value = venue
}
}
| apache-2.0 | a98bbc6e04a8a206357665670eeeb434 | 38.113208 | 83 | 0.779064 | 4.291925 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/Parser.kt | 1 | 1937 | package com.beust.klaxon
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.Reader
import java.nio.charset.Charset
interface Parser {
/**
* Parse the json from a raw string contained in the [StringBuilder].
*/
fun parse(rawValue: StringBuilder): Any
/**
* Parse the json from a file with the given [fileName].
* @return a JsonObject or JsonArray
*/
fun parse(fileName: String) : Any =
FileInputStream(File(fileName)).use {
parse(it)
}
fun parse(inputStream: InputStream, charset: Charset = Charsets.UTF_8): Any
fun parse(reader: Reader): Any
/**
* Provides access to instances of the [Parser].
* Plugins will add additional parsers by adding extension functions to this companion object.
*/
companion object {
@Deprecated(
message = "Please use a factory method to create the Parser.",
replaceWith = ReplaceWith(expression = "default(pathMatchers, passedLexer, streaming)")
)
operator fun invoke(
pathMatchers: List<PathMatcher> = emptyList(),
passedLexer: Lexer? = null,
streaming: Boolean = false
): Parser =
KlaxonParser(
pathMatchers,
passedLexer,
streaming
)
/**
* Main entry for Klaxon's parser.
*
* If [streaming] is true, the parser doesn't expect to finish on an EOF token. This is used for streaming, when
* the user requests to read a subset of the entire JSON document.
*/
fun default(
pathMatchers: List<PathMatcher> = emptyList(),
passedLexer: Lexer? = null,
streaming: Boolean = false
): Parser = KlaxonParser(
pathMatchers,
passedLexer,
streaming
)
}
}
| apache-2.0 | 28621fe90cf9badc0248ca1d8f0136eb | 28.348485 | 120 | 0.590088 | 4.966667 | false | false | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/python/sdk/add/wizardUIUtil.kt | 3 | 4827 | // 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.jetbrains.python.sdk.add
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.JBCardLayout
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.python.packaging.PyExecutionException
import java.awt.*
import javax.swing.*
import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
import javax.swing.text.StyleConstants
internal fun doCreateSouthPanel(leftButtons: List<JButton>, rightButtons: List<JButton>): JPanel {
val panel = JPanel(BorderLayout())
//noinspection UseDPIAwareInsets
val insets = if (SystemInfo.isMacOSLeopard)
if (UIUtil.isUnderIntelliJLaF()) JBUI.insets(0, 8) else JBUI.emptyInsets()
else if (UIUtil.isUnderWin10LookAndFeel()) JBUI.emptyInsets() else Insets(8, 0, 0, 0) //don't wrap to JBInsets
val bag = GridBag().setDefaultInsets(insets)
val lrButtonsPanel = NonOpaquePanel(GridBagLayout())
val leftButtonsPanel = createButtonsPanel(leftButtons)
leftButtonsPanel.border = BorderFactory.createEmptyBorder(0, 0, 0, 20) // leave some space between button groups
lrButtonsPanel.add(leftButtonsPanel, bag.next())
lrButtonsPanel.add(Box.createHorizontalGlue(), bag.next().weightx(1.0).fillCellHorizontally()) // left strut
val buttonsPanel = createButtonsPanel(rightButtons)
lrButtonsPanel.add(buttonsPanel, bag.next())
panel.add(lrButtonsPanel, BorderLayout.CENTER)
panel.border = JBUI.Borders.emptyTop(8)
return panel
}
private fun createButtonsPanel(buttons: List<JButton>): JPanel {
val hgap = if (SystemInfo.isMacOSLeopard) if (UIUtil.isUnderIntelliJLaF()) 8 else 0 else 5
val buttonsPanel = NonOpaquePanel(GridLayout(1, buttons.size, hgap, 0))
buttons.forEach { buttonsPanel.add(it) }
return buttonsPanel
}
internal fun swipe(panel: JPanel, stepContent: Component, swipeDirection: JBCardLayout.SwipeDirection) {
val stepContentName = stepContent.hashCode().toString()
panel.add(stepContentName, stepContent)
(panel.layout as JBCardLayout).swipe(panel, stepContentName, swipeDirection)
}
internal fun show(panel: JPanel, stepContent: Component) {
val stepContentName = stepContent.hashCode().toString()
panel.add(stepContentName, stepContent)
(panel.layout as CardLayout).show(panel, stepContentName)
}
fun showProcessExecutionErrorDialog(project: Project?, e: PyExecutionException) {
val errorMessageText = "${e.command} could not complete successfully. " +
"Please see the command's output for information about resolving this problem."
// HTML format for text in `JBLabel` enables text wrapping
val errorMessageLabel = JBLabel(UIUtil.toHtml(errorMessageText), Messages.getErrorIcon(), SwingConstants.LEFT)
val commandOutputTextPane = JTextPane().apply {
appendProcessOutput(e.stdout, e.stderr, e.exitCode)
background = JBColor.WHITE
isEditable = false
}
val commandOutputPanel = BorderLayoutPanel().apply {
border = IdeBorderFactory.createTitledBorder("Command output", false)
addToCenter(JBScrollPane(commandOutputTextPane, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER))
}
val formBuilder = FormBuilder()
.addComponent(errorMessageLabel)
.addComponentFillVertically(commandOutputPanel, UIUtil.DEFAULT_VGAP)
object : DialogWrapper(project) {
init {
init()
title = e.localizedMessage
}
override fun createActions(): Array<Action> = arrayOf(okAction)
override fun createCenterPanel(): JComponent = formBuilder.panel.apply {
preferredSize = Dimension(600, 300)
}
}.showAndGet()
}
private fun JTextPane.appendProcessOutput(stdout: String, stderr: String, exitCode: Int) {
val stdoutStyle = addStyle(null, null)
StyleConstants.setFontFamily(stdoutStyle, Font.MONOSPACED)
val stderrStyle = addStyle(null, stdoutStyle)
StyleConstants.setForeground(stderrStyle, JBColor.RED)
document.apply {
arrayOf(stdout to stdoutStyle, stderr to stderrStyle).forEach { (std, style) ->
if (std.isNotEmpty()) insertString(length, std + "\n", style)
}
insertString(length, "Process finished with exit code $exitCode", stdoutStyle)
}
} | apache-2.0 | 96aca7af1fae4d5fc1a51a463cc12825 | 38.252033 | 140 | 0.77253 | 4.2305 | false | false | false | false |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.kt | 1 | 6567 | // 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.diff.tools.util.base
import com.intellij.diff.util.DiffPlaces
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.util.Key
import com.intellij.util.EventDispatcher
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
import com.intellij.util.xmlb.annotations.XMap
import java.util.*
@State(name = "TextDiffSettings", storages = [(Storage(value = DiffUtil.DIFF_CONFIG))])
class TextDiffSettingsHolder : PersistentStateComponent<TextDiffSettingsHolder.State> {
companion object {
@JvmField val CONTEXT_RANGE_MODES: IntArray = intArrayOf(1, 2, 4, 8, -1)
@JvmField val CONTEXT_RANGE_MODE_LABELS: Array<String> = arrayOf("1", "2", "4", "8", "Disable")
}
data class SharedSettings(
// Fragments settings
var CONTEXT_RANGE: Int = 4,
var MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES: Boolean = false,
var MERGE_LST_GUTTER_MARKERS: Boolean = true
)
data class PlaceSettings(
// Diff settings
var HIGHLIGHT_POLICY: HighlightPolicy = HighlightPolicy.BY_WORD,
var IGNORE_POLICY: IgnorePolicy = IgnorePolicy.DEFAULT,
// Presentation settings
var ENABLE_SYNC_SCROLL: Boolean = true,
// Editor settings
var SHOW_WHITESPACES: Boolean = false,
var SHOW_LINE_NUMBERS: Boolean = true,
var SHOW_INDENT_LINES: Boolean = false,
var USE_SOFT_WRAPS: Boolean = false,
var HIGHLIGHTING_LEVEL: HighlightingLevel = HighlightingLevel.INSPECTIONS,
var READ_ONLY_LOCK: Boolean = true,
// Fragments settings
var EXPAND_BY_DEFAULT: Boolean = true
) {
@Transient
val eventDispatcher: EventDispatcher<TextDiffSettings.Listener> = EventDispatcher.create(TextDiffSettings.Listener::class.java)
}
class TextDiffSettings internal constructor(private val SHARED_SETTINGS: SharedSettings,
private val PLACE_SETTINGS: PlaceSettings) {
constructor() : this(SharedSettings(), PlaceSettings())
fun addListener(listener: Listener, disposable: Disposable) {
PLACE_SETTINGS.eventDispatcher.addListener(listener, disposable)
}
// Presentation settings
var isEnableSyncScroll: Boolean
get() = PLACE_SETTINGS.ENABLE_SYNC_SCROLL
set(value) { PLACE_SETTINGS.ENABLE_SYNC_SCROLL = value }
// Diff settings
var highlightPolicy: HighlightPolicy
get() = PLACE_SETTINGS.HIGHLIGHT_POLICY
set(value) { PLACE_SETTINGS.HIGHLIGHT_POLICY = value
PLACE_SETTINGS.eventDispatcher.multicaster.highlightPolicyChanged() }
var ignorePolicy: IgnorePolicy
get() = PLACE_SETTINGS.IGNORE_POLICY
set(value) { PLACE_SETTINGS.IGNORE_POLICY = value
PLACE_SETTINGS.eventDispatcher.multicaster.ignorePolicyChanged() }
//
// Merge
//
var isAutoApplyNonConflictedChanges: Boolean
get() = SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES
set(value) { SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES = value }
var isEnableLstGutterMarkersInMerge: Boolean
get() = SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS
set(value) { SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS = value }
// Editor settings
var isShowLineNumbers: Boolean
get() = PLACE_SETTINGS.SHOW_LINE_NUMBERS
set(value) { PLACE_SETTINGS.SHOW_LINE_NUMBERS = value }
var isShowWhitespaces: Boolean
get() = PLACE_SETTINGS.SHOW_WHITESPACES
set(value) { PLACE_SETTINGS.SHOW_WHITESPACES = value }
var isShowIndentLines: Boolean
get() = PLACE_SETTINGS.SHOW_INDENT_LINES
set(value) { PLACE_SETTINGS.SHOW_INDENT_LINES = value }
var isUseSoftWraps: Boolean
get() = PLACE_SETTINGS.USE_SOFT_WRAPS
set(value) { PLACE_SETTINGS.USE_SOFT_WRAPS = value }
var highlightingLevel: HighlightingLevel
get() = PLACE_SETTINGS.HIGHLIGHTING_LEVEL
set(value) { PLACE_SETTINGS.HIGHLIGHTING_LEVEL = value }
var contextRange: Int
get() = SHARED_SETTINGS.CONTEXT_RANGE
set(value) { SHARED_SETTINGS.CONTEXT_RANGE = value }
var isExpandByDefault: Boolean
get() = PLACE_SETTINGS.EXPAND_BY_DEFAULT
set(value) { PLACE_SETTINGS.EXPAND_BY_DEFAULT = value }
var isReadOnlyLock: Boolean
get() = PLACE_SETTINGS.READ_ONLY_LOCK
set(value) { PLACE_SETTINGS.READ_ONLY_LOCK = value }
//
// Impl
//
companion object {
@JvmField val KEY: Key<TextDiffSettings> = Key.create("TextDiffSettings")
@JvmStatic fun getSettings(): TextDiffSettings = getSettings(null)
@JvmStatic fun getSettings(place: String?): TextDiffSettings = service<TextDiffSettingsHolder>().getSettings(place)
}
interface Listener : EventListener {
fun highlightPolicyChanged() {}
fun ignorePolicyChanged() {}
}
}
fun getSettings(place: String?): TextDiffSettings {
val placeKey = place ?: DiffPlaces.DEFAULT
val placeSettings = myState.PLACES_MAP.getOrPut(placeKey) { defaultPlaceSettings(placeKey) }
return TextDiffSettings(myState.SHARED_SETTINGS, placeSettings)
}
private fun copyStateWithoutDefaults(): State {
val result = State()
result.SHARED_SETTINGS = myState.SHARED_SETTINGS
result.PLACES_MAP = DiffUtil.trimDefaultValues(myState.PLACES_MAP) { defaultPlaceSettings(it) }
return result
}
private fun defaultPlaceSettings(place: String): PlaceSettings {
val settings = PlaceSettings()
if (place == DiffPlaces.CHANGES_VIEW) {
settings.EXPAND_BY_DEFAULT = false
}
if (place == DiffPlaces.COMMIT_DIALOG) {
settings.EXPAND_BY_DEFAULT = false
}
if (place == DiffPlaces.VCS_LOG_VIEW) {
settings.EXPAND_BY_DEFAULT = false
}
return settings
}
class State {
@OptionTag
@XMap
@JvmField var PLACES_MAP: TreeMap<String, PlaceSettings> = TreeMap()
@JvmField var SHARED_SETTINGS: SharedSettings = SharedSettings()
}
private var myState: State = State()
override fun getState(): State {
return copyStateWithoutDefaults()
}
override fun loadState(state: State) {
myState = state
}
} | apache-2.0 | 196de064a4ededc42dddfdeacfd2dad0 | 33.751323 | 140 | 0.702147 | 4.407383 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationContextImpl.kt | 1 | 7620 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.transformations
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightMethodBuilder
import com.intellij.psi.impl.light.LightPsiClassBuilder
import com.intellij.psi.util.MethodSignature
import com.intellij.psi.util.MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY
import com.intellij.util.containers.FactoryMap
import com.intellij.util.containers.toArray
import gnu.trove.THashSet
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getAnnotation
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.util.GrClassImplUtil.*
import org.jetbrains.plugins.groovy.transformations.dsl.MemberBuilder
import java.util.*
internal class TransformationContextImpl(private val myCodeClass: GrTypeDefinition) : TransformationContext {
private val myProject: Project = myCodeClass.project
private val myPsiManager: PsiManager = myCodeClass.manager
private val myPsiFacade: JavaPsiFacade = JavaPsiFacade.getInstance(myProject)
private val myClassType: PsiClassType = myPsiFacade.elementFactory.createType(codeClass)
private val myMemberBuilder = MemberBuilder(this)
private val myMethods: LinkedList<PsiMethod> by lazy(LazyThreadSafetyMode.NONE) {
myCodeClass.codeMethods.flatMapTo(LinkedList(), ::expandReflectedMethods)
}
private val myFields: MutableList<GrField> by lazy(LazyThreadSafetyMode.NONE) {
myCodeClass.codeFields.toMutableList()
}
private val myInnerClasses: MutableList<PsiClass> by lazy(LazyThreadSafetyMode.NONE) {
myCodeClass.codeInnerClasses.toMutableList<PsiClass>()
}
private val myImplementsTypes: MutableList<PsiClassType> by lazy(LazyThreadSafetyMode.NONE) {
getReferenceListTypes(myCodeClass.implementsClause).toMutableList()
}
private val myExtendsTypes: MutableList<PsiClassType> by lazy(LazyThreadSafetyMode.NONE) {
getReferenceListTypes(myCodeClass.extendsClause).toMutableList()
}
private val mySignaturesCache: Map<String, MutableSet<MethodSignature>> = FactoryMap.create { name ->
val result = THashSet(METHOD_PARAMETERS_ERASURE_EQUALITY)
for (existingMethod in myMethods) {
if (existingMethod.name == name) {
result.add(existingMethod.getSignature(PsiSubstitutor.EMPTY))
}
}
result
}
override fun getCodeClass(): GrTypeDefinition = myCodeClass
override fun getProject(): Project = myProject
override fun getManager(): PsiManager = myPsiManager
override fun getPsiFacade(): JavaPsiFacade = myPsiFacade
override fun getClassType(): PsiClassType = myClassType
override fun getMemberBuilder(): MemberBuilder = myMemberBuilder
override fun getFields(): Collection<GrField> = myFields
override fun getAllFields(includeSynthetic: Boolean): Collection<PsiField> {
if (!includeSynthetic) {
return getAllFields(codeClass, false).toList()
}
val fields = myFields.toMutableSet<PsiField>()
val superTypes = myExtendsTypes + myImplementsTypes
for (type in superTypes) {
val psiClass = type.resolve() ?: continue
fields += psiClass.allFields
}
return fields
}
override fun getMethods(): Collection<PsiMethod> = myMethods
override fun getInnerClasses(): Collection<PsiClass> = myInnerClasses
override fun getImplementsTypes(): List<PsiClassType> = myImplementsTypes
override fun getExtendsTypes(): List<PsiClassType> = myExtendsTypes
override fun getClassName(): String? = myCodeClass.name
override fun getSuperClass(): PsiClass? = getSuperClass(codeClass, myExtendsTypes.toTypedArray())
override fun getAnnotation(fqn: String): PsiAnnotation? = getAnnotation(codeClass, fqn)
override fun isInheritor(baseClass: PsiClass): Boolean {
if (manager.areElementsEquivalent(codeClass, baseClass)) return false
if (codeClass.isInterface && !baseClass.isInterface) return false
for (superType in superTypes) {
val superClass = superType.resolve() ?: continue
if (manager.areElementsEquivalent(superClass, baseClass)) return true
if (superClass.isInheritor(baseClass, true)) return true
}
return false
}
override fun findMethodsByName(name: String, checkBases: Boolean): Collection<PsiMethod> {
val methods = myMethods.filter {
name == it.name
}
if (checkBases) {
val superMethods = superClass?.findMethodsByName(name, true) ?: PsiMethod.EMPTY_ARRAY
return methods + superMethods
}
else {
return methods
}
}
private fun doAddMethod(method: PsiMethod, prepend: Boolean) {
if (method is GrLightMethodBuilder) {
method.setContainingClass(myCodeClass)
}
else if (method is LightMethodBuilder) {
@Suppress("UsePropertyAccessSyntax")
method.setContainingClass(myCodeClass)
}
val signature = method.getSignature(PsiSubstitutor.EMPTY)
val signatures = mySignaturesCache.getValue(method.name)
if (signatures.add(signature)) {
if (prepend) {
myMethods.addFirst(method)
}
else {
myMethods.addLast(method)
}
}
}
override fun addMethod(method: PsiMethod, prepend: Boolean) {
for (expanded in expandReflectedMethods(method)) {
doAddMethod(expanded, prepend)
}
}
override fun addMethods(methods: Array<PsiMethod>) {
for (method in methods) {
addMethod(method)
}
}
override fun addMethods(methods: Collection<PsiMethod>) {
for (method in methods) {
addMethod(method)
}
}
override fun removeMethod(method: PsiMethod) {
val signatures = mySignaturesCache.getValue(method.name)
for (expanded in expandReflectedMethods(method)) {
val signature = expanded.getSignature(PsiSubstitutor.EMPTY)
if (signatures.remove(signature)) {
myMethods.removeIf { m -> METHOD_PARAMETERS_ERASURE_EQUALITY.equals(signature, m.getSignature(PsiSubstitutor.EMPTY)) }
}
}
}
override fun addField(field: GrField) {
if (field is GrLightField) {
field.setContainingClass(codeClass)
}
myFields.add(field)
}
override fun addInnerClass(innerClass: PsiClass) {
if (innerClass is LightPsiClassBuilder) {
innerClass.containingClass = codeClass
}
myInnerClasses.add(innerClass)
}
override fun setSuperType(fqn: String) = setSuperType(createType(fqn, codeClass))
override fun setSuperType(type: PsiClassType) {
if (!codeClass.isInterface) {
myExtendsTypes.clear()
myExtendsTypes.add(type)
}
}
override fun addInterface(fqn: String) = addInterface(createType(fqn, codeClass))
override fun addInterface(type: PsiClassType) {
(if (!codeClass.isInterface || codeClass.isTrait) myImplementsTypes else myExtendsTypes).add(type)
}
internal val transformationResult: TransformationResult
get() = TransformationResult(
methods.toArray(PsiMethod.EMPTY_ARRAY),
fields.toArray(GrField.EMPTY_ARRAY),
innerClasses.toArray(PsiClass.EMPTY_ARRAY),
implementsTypes.toArray(PsiClassType.EMPTY_ARRAY),
extendsTypes.toArray(PsiClassType.EMPTY_ARRAY)
)
}
| apache-2.0 | a746b11be809c88bc15badd27a37f09c | 35.634615 | 140 | 0.750919 | 4.522255 | false | false | false | false |
paplorinc/intellij-community | tools/index-tools/src/org/jetbrains/index/IndexGenerator.kt | 6 | 3558 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.index
import com.google.common.hash.HashCode
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.stubs.FileContentHashing
import com.intellij.util.SystemProperties
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.io.PersistentHashMap
import junit.framework.TestCase
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* @author traff
*/
abstract class IndexGenerator<Value>(private val indexStorageFilePath: String) {
companion object {
const val CHECK_HASH_COLLISIONS_PROPERTY = "idea.index.generator.check.hash.collisions"
val CHECK_HASH_COLLISIONS: Boolean = SystemProperties.`is`(CHECK_HASH_COLLISIONS_PROPERTY)
}
open val fileFilter: VirtualFileFilter
get() = VirtualFileFilter { f -> !f.isDirectory }
data class Stats(val indexed: AtomicInteger, val skipped: AtomicInteger) {
constructor() : this(AtomicInteger(0), AtomicInteger(0))
}
protected fun buildIndexForRoots(roots: Collection<VirtualFile>) {
val hashing = FileContentHashing()
val storage = createStorage(indexStorageFilePath)
println("Writing indices to ${storage.baseFile.absolutePath}")
storage.use {
val map = HashMap<HashCode, String>()
for (file in roots) {
println("Processing files in root ${file.path}")
val stats = Stats()
VfsUtilCore.visitChildrenRecursively(file,
object : VirtualFileVisitor<Boolean>() {
override fun visitFile(file: VirtualFile): Boolean {
return indexFile(file, hashing, map, storage, stats)
}
})
println("${stats.indexed.get()} entries written, ${stats.skipped.get()} skipped")
}
}
}
private fun indexFile(file: VirtualFile,
hashing: FileContentHashing,
map: MutableMap<HashCode, String>,
storage: PersistentHashMap<HashCode, Value>,
stats: Stats): Boolean {
try {
if (fileFilter.accept(file)) {
val fileContent = FileContentImpl(
file, file.contentsToByteArray())
val hashCode = hashing.hashString(fileContent)
val value = getIndexValue(fileContent)
if (value != null) {
val item = map[hashCode]
if (item == null) {
storage.put(hashCode, value)
stats.indexed.incrementAndGet()
if (CHECK_HASH_COLLISIONS) {
map[hashCode] = fileContent.contentAsText.toString()
}
}
else {
TestCase.assertEquals(item, fileContent.contentAsText.toString())
TestCase.assertTrue(storage.get(hashCode) == value)
}
}
else {
stats.skipped.incrementAndGet()
}
}
}
catch (e: NoSuchElementException) {
return false
}
return true
}
protected abstract fun getIndexValue(fileContent: FileContentImpl): Value?
protected abstract fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, Value>
} | apache-2.0 | 502f3eb083d4d888b18bed89096a1aeb | 33.553398 | 140 | 0.634064 | 5.025424 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/playback/utils/exoExtensions.kt | 1 | 2038 | package de.ph1b.audiobook.playback.utils
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.PlaybackParameters
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.analytics.AnalyticsListener
import de.ph1b.audiobook.playback.PlayerState
fun SimpleExoPlayer.setPlaybackParameters(speed: Float, skipSilence: Boolean) {
val params = playbackParameters
if (params == null || params.speed != speed || params.skipSilence != skipSilence) {
playbackParameters = PlaybackParameters(speed, 1F, skipSilence)
}
}
inline fun ExoPlayer.onStateChanged(crossinline action: (PlayerState) -> Unit) {
addListener(
object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
val state = when (playbackState) {
Player.STATE_ENDED -> PlayerState.ENDED
Player.STATE_IDLE -> PlayerState.IDLE
Player.STATE_READY, Player.STATE_BUFFERING -> {
if (playWhenReady) PlayerState.PLAYING
else PlayerState.PAUSED
}
else -> null
}
if (state != null) action(state)
}
}
)
}
inline fun ExoPlayer.onError(crossinline action: (ExoPlaybackException) -> Unit) {
addListener(
object : Player.EventListener {
override fun onPlayerError(error: ExoPlaybackException) {
action(error)
}
}
)
}
inline fun SimpleExoPlayer.onAudioSessionId(crossinline action: (Int) -> Unit) {
addAnalyticsListener(object : AnalyticsListener {
override fun onAudioSessionId(eventTime: AnalyticsListener.EventTime?, audioSessionId: Int) {
action(audioSessionId)
}
})
}
inline fun ExoPlayer.onPositionDiscontinuity(crossinline action: () -> Unit) {
addListener(
object : Player.EventListener {
override fun onPositionDiscontinuity(reason: Int) {
action()
}
}
)
}
| lgpl-3.0 | 94c1e843db1b74255b65df46d5039f7b | 31.349206 | 97 | 0.713445 | 4.498896 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/game/live/SceneElements.kt | 1 | 4759 | package org.runestar.client.api.game.live
import io.reactivex.rxjava3.core.Observable
import org.runestar.client.api.game.SceneElement
import org.runestar.client.raw.access.XClient
import org.runestar.client.raw.access.XScene
import org.runestar.client.raw.access.XTile
import org.runestar.client.raw.CLIENT
import org.runestar.client.raw.access.XScenery
import java.util.Optional
interface SceneElementEvents<T : SceneElement> {
val added: Observable<T>
val removed: Observable<T>
}
object SceneElements : SceneElementEvents<SceneElement> {
val cleared: Observable<Unit> = XScene.clear.exit.map { Unit }
override val added: Observable<SceneElement> = Observable.mergeArray(
WallDecoration.added,
FloorDecoration.added,
Wall.added,
ObjStack.added,
Scenery.added
)
override val removed: Observable<SceneElement> = Observable.mergeArray(
WallDecoration.removed,
FloorDecoration.removed,
Wall.removed,
ObjStack.removed,
Scenery.removed
)
object Loc : SceneElementEvents<SceneElement> {
override val added: Observable<SceneElement> = Observable.mergeArray(
WallDecoration.added,
FloorDecoration.added,
Wall.added,
Scenery.added.filter(SceneElement::isLoc)
)
override val removed: Observable<SceneElement> = Observable.mergeArray(
WallDecoration.removed,
FloorDecoration.removed,
Wall.removed,
Scenery.removed.filter(SceneElement::isLoc)
)
}
object WallDecoration : SceneElementEvents<SceneElement.WallDecoration> {
override val added: Observable<SceneElement.WallDecoration> = XScene.newWallDecoration.exit.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.WallDecoration(tile.wallDecoration, tile.plane)
}
override val removed: Observable<SceneElement.WallDecoration> = XScene.removeWallDecoration.enter.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.WallDecoration(tile.wallDecoration, tile.plane)
}
}
object FloorDecoration : SceneElementEvents<SceneElement.FloorDecoration> {
override val added: Observable<SceneElement.FloorDecoration> = XScene.newFloorDecoration.exit.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.FloorDecoration(tile.floorDecoration, tile.plane)
}
override val removed: Observable<SceneElement.FloorDecoration> = XScene.removeFloorDecoration.enter.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.FloorDecoration(tile.floorDecoration, tile.plane)
}
}
object Wall : SceneElementEvents<SceneElement.Wall> {
override val added: Observable<SceneElement.Wall> = XScene.newWall.exit.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.Wall(tile.wall, tile.plane)
}
override val removed: Observable<SceneElement.Wall> = XScene.removeWall.enter.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.Wall(tile.wall, tile.plane)
}
}
object ObjStack : SceneElementEvents<SceneElement.ObjStack> {
override val added: Observable<SceneElement.ObjStack> = XScene.newObjStack.exit.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.ObjStack(tile.objStack, tile.plane)
}
override val removed: Observable<SceneElement.ObjStack> = Observable.merge(XScene.removeObjStack.enter, XScene.newObjStack.enter)
.map { Optional.ofNullable(getTile(it.arguments)) }
.filter { it.isPresent }
.map { it.get() }
.filter { it.objStack != null }
.map { SceneElement.ObjStack(it.objStack, it.plane) }
}
object Scenery : SceneElementEvents<SceneElement.Scenery> {
override val added: Observable<SceneElement.Scenery> = XScene.newScenery.exit
.filter { it.returned }
.map {
val tile = checkNotNull(getTile(it.arguments))
SceneElement.Scenery(tile.scenery[tile.sceneryCount - 1])
}
override val removed: Observable<SceneElement.Scenery> = XScene.removeScenery.enter
.map { SceneElement.Scenery(it.arguments[0] as XScenery) }
.delay { XClient.doCycle.enter }
}
private fun getTile(args: Array<*>): XTile? = CLIENT.scene.tiles[args[0] as Int][args[1] as Int][args[2] as Int]
} | mit | d1f2e2131b3f47257f70e0efb0027b7d | 37.08 | 137 | 0.65623 | 4.299006 | false | false | false | false |
java-graphics/assimp | src/main/kotlin/assimp/format/assbin/AssbinLoader.kt | 2 | 17948 | package assimp.format.assbin
import assimp.*
import assimp.format.X.reserve
import gli_.has
import gli_.hasnt
import glm_.*
import java.io.InputStream
class AssbinLoader : BaseImporter() {
override val info = AiImporterDesc(
name = ".assbin Importer",
comments = "Gargaj / Conspiracy",
flags = AiImporterFlags.SupportBinaryFlavour or AiImporterFlags.SupportCompressedFlavour,
fileExtensions = listOf("assbin"))
var shortened = false
var compressed = false
private val be = false // big endian TODO glm global?
override fun canRead(file: String, ioSystem: IOSystem, checkSig: Boolean) =
ioSystem.open(file).read().use { i -> "ASSIMP.binary-dump.".all { it.i == i.read() } }
override fun internReadFile(file: String, ioSystem: IOSystem, scene: AiScene) {
ioSystem.open(file).read().use {
it.skip(44) // signature
/* unused */ it.int(be) // unsigned int versionMajor
/* unused */ it.int(be) // unsigned int versionMinor
/* unused */ it.int(be) // unsigned int versionRevision
/* unused */ it.int(be) // unsigned int compileFlags
shortened = it.short(be).bool
compressed = it.short(be).bool
if (shortened) throw Exception("Shortened binaries are not supported!")
it.skip(256) // original filename
it.skip(128) // options
it.skip(64) // padding
if (compressed) {
TODO()
// val uncompressedSize = stream.readint(be)
// val compressedSize = static_cast < uLongf >(stream->FileSize()-stream->Tell())
//
// unsigned char * compressedData = new unsigned char [compressedSize]
// stream->Read(compressedData, 1, compressedSize)
//
// unsigned char * uncompressedData = new unsigned char [uncompressedSize]
//
// uncompress(uncompressedData, & uncompressedSize, compressedData, compressedSize)
//
// MemoryIOStream io (uncompressedData, uncompressedSize)
//
// ReadBinaryScene(& io, scene)
//
// delete[] uncompressedData
// delete[] compressedData
} else it.readScene(scene)
}
}
fun InputStream.readScene(scene: AiScene) {
assert(int(be) == ASSBIN_CHUNK_AISCENE)
int(be) // size
scene.flags = int(be)
scene.numMeshes = int(be)
scene.numMaterials = int(be)
scene.numAnimations = int(be)
scene.numTextures = int(be)
scene.numLights = int(be)
scene.numCameras = int(be)
// Read node graph
scene.rootNode = AiNode()
readNode(scene.rootNode)
// Read all meshes
for (i in 0 until scene.numMeshes)
scene.meshes.add(AiMesh().also { readMesh(it) })
// Read materials
for (i in 0 until scene.numMaterials)
scene.materials.add(AiMaterial().also { readMaterial(it) })
// Read all animations
for (i in 0 until scene.numAnimations)
scene.animations.add(AiAnimation().also { readAnimation(it) })
// Read all textures
for (i in 0 until scene.numTextures)
readTexture()
// scene.textures["$i"] = gli.Texture(AiAnimation().also { readAnimation(it) })
// if (scene.numTextures > 0) {
// scene.textures = new aiTexture *[scene->numTextures]
// for (unsigned int i = 0; i < scene->numTextures;++i) {
// scene.textures[i] = new aiTexture ()
// ReadBinaryTexture(stream, scene->textures[i])
// }
// }
// Read lights
for (i in 0 until scene.numLights)
scene.lights = Array(scene.numLights, { AiLight().also { readLight(it) } }).toCollection(ArrayList())
// Read cameras
for (i in 0 until scene.numCameras)
scene.cameras = Array(scene.numCameras, { AiCamera().also { readCamera(it) } }).toCollection(ArrayList())
}
private fun InputStream.readNode(node: AiNode, parent: AiNode? = null) {
assert(int(be) == ASSBIN_CHUNK_AINODE)
int(be) // size
node.name = string()
node.transformation = mat4()
node.numChildren = int(be)
node.numMeshes = int(be)
parent?.let { node.parent = parent }
if (node.numMeshes > 0)
node.meshes = IntArray(node.numMeshes, { int(be) })
for (i in 0 until node.numChildren)
node.children.add(AiNode().also { readNode(it, node) })
}
private fun InputStream.readMesh(mesh: AiMesh) {
assert(int(be) == ASSBIN_CHUNK_AIMESH)
int(be) // size
mesh.primitiveTypes = int(be)
mesh.numVertices = int(be)
mesh.numFaces = int(be)
mesh.numBones = int(be)
mesh.materialIndex = int(be)
// first of all, write bits for all existent vertex components
val c = int(be)
if (c has ASSBIN_MESH_HAS_POSITIONS)
if (shortened)
TODO()//ReadBounds(stream, mesh->vertices, mesh->numVertices)
else // else write as usual
mesh.vertices = MutableList(mesh.numVertices, { AiVector3D(this, be) })
if (c has ASSBIN_MESH_HAS_NORMALS)
if (shortened)
TODO()//ReadBounds(stream, mesh->normals, mesh->numVertices)
else // else write as usual
mesh.normals = MutableList(mesh.numVertices, { AiVector3D(this, be) })
if (c has ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) {
if (shortened) {
TODO()//ReadBounds(stream, mesh->tangents, mesh->numVertices)
//ReadBounds(stream, mesh->bitangents, mesh->numVertices)
} else { // else write as usual
mesh.tangents = MutableList(mesh.numVertices, { AiVector3D(this, be) })
mesh.bitangents = MutableList(mesh.numVertices, { AiVector3D(this, be) })
}
}
for (n in 0 until AI_MAX_NUMBER_OF_COLOR_SETS) {
if (c hasnt ASSBIN_MESH_HAS_COLOR(n))
break
if (shortened)
TODO()//ReadBounds(stream, mesh->colors[n], mesh->numVertices)
else // else write as usual
mesh.colors.add(MutableList(mesh.numVertices, { AiColor4D(this) }))
}
for (n in 0 until AI_MAX_NUMBER_OF_TEXTURECOORDS) {
if (c hasnt ASSBIN_MESH_HAS_TEXCOORD(n))
break
// write number of UV components
val mNumUVComponents = int(be)
if (shortened)
TODO()//ReadBounds(stream, mesh->textureCoords[n], mesh->numVertices)
else // else write as usual
mesh.textureCoords.add(MutableList(mesh.numVertices, {
val uv = AiVector3D(this, be)
(0 until mNumUVComponents).map { uv[it] }.toFloatArray()
}))
}
/* write faces. There are no floating-point calculations involved in these, so we can write a simple hash over
the face data to the dump file. We generate a single 32 Bit hash for 512 faces using Assimp's standard
hashing function. */
if (shortened)
int(be)
else // else write as usual
// if there are less than 2^16 vertices, we can simply use 16 bit integers ...
mesh.faces = MutableList(mesh.numFaces, {
assert(AI_MAX_FACE_INDICES <= 0xffff, { "AI_MAX_FACE_INDICES <= 0xffff" })
val mNumIndices = short(be)
MutableList(mNumIndices.i, { if (mesh.numVertices < (1 shl 16)) short(be) else int(be) })
})
// write bones
for (i in 0 until mesh.numBones)
mesh.bones.add(AiBone().also { readBone(it) })
}
private fun InputStream.readBone(b: AiBone) {
assert(int(be) == ASSBIN_CHUNK_AIBONE)
int(be) // size
b.name = string()
b.numWeights = int(be)
b.offsetMatrix = mat4()
// for the moment we write dumb min/max values for the bones, too.
// maybe I'll add a better, hash-like solution later
if (shortened)
TODO() //ReadBounds(stream, b->weights, b->mNumWeights)
else // else write as usual
b.weights = MutableList(b.numWeights, { vertexWeight() })
}
private fun InputStream.readMaterial(mat: AiMaterial) {
assert(int(be) == ASSBIN_CHUNK_AIMATERIAL)
int(be) // size
val mNumProperties = int(be)
if (mNumProperties > 0) {
// TODO reset?
// if (mat->mProperties)
// delete[] mat->mProperties
for (i in 0 until mNumProperties)
readMaterialProperty(mat)
}
}
private fun InputStream.readMaterialProperty(mat: AiMaterial) {
assert(int(be) == ASSBIN_CHUNK_AIMATERIALPROPERTY)
int(be) // size
val mKey = string()
val mSemantic = int(be)
val mIndex = int(be)
val mDataLength = int(be)
val mType = int(be)
when (mKey) {
"?mat.name" -> mat.name = string(mDataLength).replace(Regex("[^A-Za-z0-9 ]"), "")
"\$mat.twosided" -> mat.twoSided = short(be).bool
"\$mat.shadingm" -> mat.shadingModel = AiShadingMode.of(int(be))
"\$mat.wireframe" -> mat.wireframe = short(be).bool
"\$mat.blend" -> mat.blendFunc = AiBlendMode.of(int(be))
"\$mat.opacity" -> mat.opacity = float(be)
"\$mat.bumpscaling" -> mat.bumpScaling = float(be)
"\$mat.shininess" -> mat.shininess = float(be)
"\$mat.reflectivity" -> mat.reflectivity = float(be)
"\$mat.shinpercent" -> mat.shininessStrength = float(be)
"\$mat.refracti" -> mat.refracti = float(be)
"\$clr.diffuse" -> {
val diffuse = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.diffuse = diffuse
mat.color = AiMaterial.Color(diffuse = diffuse)
}
"\$clr.ambient" -> {
val ambient = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.ambient = ambient
mat.color = AiMaterial.Color(ambient = ambient)
}
"\$clr.specular" -> {
val specular = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.specular = specular
mat.color = AiMaterial.Color(specular = specular)
}
"\$clr.emissive" -> {
val emissive = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.emissive = emissive
mat.color = AiMaterial.Color(emissive = emissive)
}
"\$clr.transparent" -> {
val transparent = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.transparent = transparent
mat.color = AiMaterial.Color(transparent = transparent)
}
"\$clr.reflective" -> {
val reflective = AiColor3D(this, be)
if (mDataLength == AiColor4D.size) float() // read another float
if (mat.color != null)
mat.color!!.reflective = reflective
mat.color = AiMaterial.Color(reflective = reflective)
}
"?bg.global" -> TODO()
"\$tex.file" -> {
if (mIndex >= mat.textures.size)
mat.textures.add(AiMaterial.Texture())
mat.textures[mIndex].file = string(mDataLength).replace(Regex("[^A-Za-z0-9 ]"), "")
}
"\$tex.uvwsrc" -> mat.textures[mIndex].uvwsrc = int(be)
"\$tex.op" -> mat.textures[mIndex].op = AiTexture.Op.of(int(be))
"\$tex.mapping" -> mat.textures[mIndex].mapping = AiTexture.Mapping.of(int(be))
"\$tex.blend" -> mat.textures[mIndex].blend = float(be)
"\$tex.mapmodeu" -> mat.textures[mIndex].mapModeU = AiTexture.MapMode.of(int(be))
"\$tex.mapmodev" -> mat.textures[mIndex].mapModeV = AiTexture.MapMode.of(int(be))
"\$tex.mapaxis" -> mat.textures[mIndex].mapAxis = AiVector3D(this, be)
"\$tex.uvtrafo" -> TODO("vec2(this)")//mat.textures[mIndex].uvTrafo = AiUVTransform()
"\$tex.flags" -> mat.textures[mIndex].flags = int(be)
}
}
private fun InputStream.readTexture() {
assert(int(be) == ASSBIN_CHUNK_AITEXTURE)
int() // size
val tex = AiTexture()
tex.width = int(be)
tex.width = int(be)
tex.achFormatHint = string(4)
if (!shortened)
tex.pcData =
if (tex.height == 0)
ByteArray(tex.width, { byte() })
else
ByteArray(tex.width * tex.height * 4, { byte() })
// TODO
}
private fun InputStream.readAnimation(anim: AiAnimation) {
assert(int(be) == ASSBIN_CHUNK_AIANIMATION)
int(be) // size
anim.name = string()
anim.duration = double(be)
anim.ticksPerSecond = double(be)
anim.numChannels = int(be)
anim.channels = Array(anim.numChannels, { AiNodeAnim().also { readNodeAnim(it) } }).toCollection(ArrayList())
}
private fun InputStream.readNodeAnim(nd: AiNodeAnim) {
assert(int(be) == ASSBIN_CHUNK_AINODEANIM)
int(be) // size
nd.nodeName = string()
nd.numPositionKeys = int(be)
nd.numRotationKeys = int(be)
nd.numScalingKeys = int(be)
nd.preState = AiAnimBehaviour.of(int(be))
nd.postState = AiAnimBehaviour.of(int(be))
if (nd.numPositionKeys > 0)
if (shortened)
TODO()//ReadBounds(stream, nd->positionKeys, nd->numPositionKeys)
else // else write as usual
nd.positionKeys.apply {
clear()
reserve(nd.numPositionKeys) { vectorKey() }
}
if (nd.numRotationKeys > 0)
if (shortened)
TODO()//ReadBounds(stream, nd->rotationKeys, nd->numRotationKeys)
else // else write as usual
nd.rotationKeys.apply {
clear()
reserve(nd.numRotationKeys) { quatKey() }
}
if (nd.numScalingKeys > 0)
if (shortened)
TODO()//ReadBounds(stream, nd->scalingKeys, nd->numScalingKeys)
else // else write as usual
nd.scalingKeys.apply {
clear()
reserve(nd.numScalingKeys) { vectorKey() }
}
}
private fun InputStream.readLight(l: AiLight) {
assert(int(be) == ASSBIN_CHUNK_AILIGHT)
int(be) // size
l.name = string()
l.type = AiLightSourceType.of(int(be))
if (l.type != AiLightSourceType.DIRECTIONAL) {
l.attenuationConstant = float(be)
l.attenuationLinear = float(be)
l.attenuationQuadratic = float(be)
}
l.colorDiffuse = AiColor3D(this)
l.colorSpecular = AiColor3D(this)
l.colorAmbient = AiColor3D(this)
if (l.type == AiLightSourceType.SPOT) {
l.angleInnerCone = float(be)
l.angleOuterCone = float(be)
}
}
private fun InputStream.readCamera(cam: AiCamera) {
assert(int(be) == ASSBIN_CHUNK_AICAMERA)
int(be) // size
cam.name = string()
cam.position = AiVector3D(this, be)
cam.lookAt = AiVector3D(this, be)
cam.up = AiVector3D(this, be)
cam.horizontalFOV = float(be)
cam.clipPlaneNear = float(be)
cam.clipPlaneFar = float(be)
cam.aspect = float(be)
}
private val ASSBIN_HEADER_LENGTH = 512
// these are the magic chunk identifiers for the binary ASS file format
private val ASSBIN_CHUNK_AICAMERA = 0x1234
private val ASSBIN_CHUNK_AILIGHT = 0x1235
private val ASSBIN_CHUNK_AITEXTURE = 0x1236
private val ASSBIN_CHUNK_AIMESH = 0x1237
private val ASSBIN_CHUNK_AINODEANIM = 0x1238
private val ASSBIN_CHUNK_AISCENE = 0x1239
private val ASSBIN_CHUNK_AIBONE = 0x123a
private val ASSBIN_CHUNK_AIANIMATION = 0x123b
private val ASSBIN_CHUNK_AINODE = 0x123c
private val ASSBIN_CHUNK_AIMATERIAL = 0x123d
private val ASSBIN_CHUNK_AIMATERIALPROPERTY = 0x123e
private val ASSBIN_MESH_HAS_POSITIONS = 0x1
private val ASSBIN_MESH_HAS_NORMALS = 0x2
private val ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS = 0x4
private val ASSBIN_MESH_HAS_TEXCOORD_BASE = 0x100
private val ASSBIN_MESH_HAS_COLOR_BASE = 0x10000
private fun ASSBIN_MESH_HAS_TEXCOORD(n: Int) = ASSBIN_MESH_HAS_TEXCOORD_BASE shl n
private fun ASSBIN_MESH_HAS_COLOR(n: Int) = ASSBIN_MESH_HAS_COLOR_BASE shl n
private fun InputStream.string(length: Int = int(be)) = String(ByteArray(length, { byte() }))
private fun InputStream.vertexWeight() = AiVertexWeight(int(be), float(be))
private fun InputStream.vectorKey() = AiVectorKey(double(be), AiVector3D(this, be))
private fun InputStream.quatKey() = AiQuatKey(double(be), AiQuaternion(this, be))
} | bsd-3-clause | fdf42bfb1524f9aef5cc7814a3f1226d | 36.867089 | 119 | 0.5614 | 3.976955 | false | false | false | false |
JetBrains/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsSyncStatusAction.kt | 1 | 3066 | package com.intellij.settingsSync.config
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.SettingsEntryPointAction
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.settingsSync.SettingsSyncBundle.message
import com.intellij.settingsSync.SettingsSyncSettings
import com.intellij.settingsSync.SettingsSyncStatusTracker
import com.intellij.settingsSync.auth.SettingsSyncAuthService
import com.intellij.settingsSync.isSettingsSyncEnabledByKey
import com.intellij.ui.BadgeIconSupplier
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.SettingsSyncIcons
import org.jetbrains.annotations.Nls
import javax.swing.Icon
class SettingsSyncStatusAction : SettingsSyncOpenSettingsAction(message("title.settings.sync")),
SettingsEntryPointAction.NoDots,
SettingsSyncStatusTracker.Listener {
private enum class SyncStatus {ON, OFF, FAILED}
companion object {
private fun getStatus() : SyncStatus {
if (SettingsSyncSettings.getInstance().syncEnabled &&
SettingsSyncAuthService.getInstance().isLoggedIn()) {
return if (SettingsSyncStatusTracker.getInstance().isSyncSuccessful()) SyncStatus.ON
else SyncStatus.FAILED
}
else
return SyncStatus.OFF
}
}
init {
SettingsSyncStatusTracker.getInstance().addListener(this)
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val p = e.presentation
if (!isSettingsSyncEnabledByKey()) {
p.isEnabledAndVisible = false
return
}
val status = getStatus()
when (status) {
SyncStatus.ON ->
p.icon = SettingsSyncIcons.StatusEnabled
SyncStatus.OFF ->
p.icon = SettingsSyncIcons.StatusDisabled
SyncStatus.FAILED ->
p.icon = AllIcons.General.Error
}
p.text = getStyledStatus(status)
}
private fun getStyledStatus(status: SyncStatus): @Nls String {
val builder = StringBuilder()
builder.append("<html>")
.append(message("status.action.settings.sync")).append(" ")
.append("<span color='#")
val hexColor = UIUtil.colorToHex(JBUI.CurrentTheme.Popup.mnemonicForeground())
builder.append(hexColor).append("'>")
when (status) {
SyncStatus.ON -> builder.append(message("status.action.settings.sync.is.on"))
SyncStatus.OFF -> builder.append(message("status.action.settings.sync.is.off"))
SyncStatus.FAILED -> builder.append(message("status.action.settings.sync.failed"))
}
builder
.append("</span>")
return "$builder"
}
class IconCustomizer : SettingsEntryPointAction.IconCustomizer {
override fun getCustomIcon(supplier: BadgeIconSupplier): Icon? {
return if (getStatus() == SyncStatus.FAILED) {
supplier.getErrorIcon(true)
}
else null
}
}
override fun syncStatusChanged() {
SettingsEntryPointAction.updateState()
}
} | apache-2.0 | 6adb2531438091073f278c10e0bfbdf8 | 32.336957 | 96 | 0.718526 | 4.768274 | false | false | false | false |
StephaneBg/ScoreIt | cache/src/main/kotlin/com/sbgapps/scoreit/cache/repository/ScoreItBillingRepo.kt | 1 | 4750 | /*
* Copyright 2020 Stéphane Baiget
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sbgapps.scoreit.cache.repository
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.sbgapps.scoreit.cache.dao.ScoreItBillingDao
import com.sbgapps.scoreit.data.repository.BillingRepo
import com.sbgapps.scoreit.data.repository.BillingRepo.Companion.BEER
import com.sbgapps.scoreit.data.repository.BillingRepo.Companion.COFFEE
import timber.log.Timber
class ScoreItBillingRepo(
context: Context,
private val billingDao: ScoreItBillingDao
) : BillingRepo, PurchasesUpdatedListener, BillingClientStateListener {
private var purchaseCallback: (() -> Unit)? = null
private var donations: List<SkuDetails>? = null
private val playStoreBillingClient: BillingClient = BillingClient.newBuilder(context)
.enablePendingPurchases()
.setListener(this)
.build()
init {
connectToPlayBillingService()
}
private fun connectToPlayBillingService() {
if (!playStoreBillingClient.isReady) {
playStoreBillingClient.startConnection(this)
}
}
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
for (purchase in purchases) acknowledgePurchase(purchase.purchaseToken)
} else {
Timber.e(billingResult.debugMessage)
}
}
private fun acknowledgePurchase(purchaseToken: String) {
val params = AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchaseToken).build()
playStoreBillingClient.acknowledgePurchase(params) { billingResult ->
donations = null
purchaseCallback?.invoke()
Timber.d(billingResult.debugMessage)
}
}
override fun onBillingServiceDisconnected() = Unit
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
querySkuDetailsAsync()
} else {
Timber.e(billingResult.debugMessage)
}
}
override fun getDonationSkus(): List<SkuDetails>? = donations
override fun startBillingFlow(activity: Activity, skuDetails: SkuDetails, callback: () -> Unit) {
purchaseCallback = callback
val billingFlowParams = BillingFlowParams.newBuilder().setSkuDetails(skuDetails).build()
playStoreBillingClient.launchBillingFlow(activity, billingFlowParams)
}
private fun querySkuDetailsAsync() {
val skus = billingDao.loadSkus()
if (null == skus) {
val params = SkuDetailsParams.newBuilder().setSkusList(DONATION_SKUS)
.setType(BillingClient.SkuType.INAPP).build()
playStoreBillingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
billingDao.saveSkus(skuDetailsList)
queryPurchasesAsync(skuDetailsList)
} else {
Timber.e(billingResult.debugMessage)
}
}
} else {
queryPurchasesAsync(skus)
}
}
private fun queryPurchasesAsync(skus: List<SkuDetails>?) {
val hasDonated = playStoreBillingClient.queryPurchases(BillingClient.SkuType.INAPP)
.purchasesList?.isNotEmpty() == true
Timber.d("User has ${if (!hasDonated) "not" else ""} donated")
if (!hasDonated) donations = skus
}
companion object {
private val DONATION_SKUS = listOf(COFFEE, BEER)
}
}
| apache-2.0 | 9a371e723fe82f93074f02e201d8df4e | 37.92623 | 102 | 0.710465 | 4.82622 | false | false | false | false |
DevPicon/kotlin-marvel-hero-finder | app/src/main/kotlin/pe/devpicon/android/marvelheroes/app/AppContainer.kt | 1 | 1428 | package pe.devpicon.android.marvelheroes.app
import android.content.Context
import kotlinx.coroutines.ExperimentalCoroutinesApi
import pe.devpicon.android.marvelheroes.data.Repository
import pe.devpicon.android.marvelheroes.data.local.DatabaseMapper
import pe.devpicon.android.marvelheroes.data.local.LocalDataSource
import pe.devpicon.android.marvelheroes.data.local.MarvelDatabase
import pe.devpicon.android.marvelheroes.data.remote.MarvelService
import pe.devpicon.android.marvelheroes.data.remote.RemoteDatasource
import pe.devpicon.android.marvelheroes.data.remote.RestClient
import pe.devpicon.android.marvelheroes.domain.DomainMapper
import pe.devpicon.android.marvelheroes.presentation.home.MainViewStateMapper
@ExperimentalCoroutinesApi
class AppContainer(applicationContext: Context) {
private val service: MarvelService = RestClient.service
private val remoteDataSource = RemoteDatasource(service)
private val domainMapper = DomainMapper()
private val marvelDatabase = MarvelDatabase.create(applicationContext)
private val comicDao = marvelDatabase.comicDao()
private val characterDao = marvelDatabase.characterDao()
private val localDataSource = LocalDataSource(comicDao, characterDao)
private val databaseMapper = DatabaseMapper()
val repository = Repository(localDataSource, remoteDataSource, databaseMapper, domainMapper)
val viewStateMapper = MainViewStateMapper()
} | mit | a59978c1e9005b88b5e915f78ca15480 | 45.096774 | 96 | 0.838235 | 4.314199 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt | 1 | 3120 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class TypeOfAnnotationMemberFix(
typeReference: KtTypeReference,
private val fixedType: String
) : KotlinQuickFixAction<KtTypeReference>(typeReference), CleanupFix {
override fun getText(): String = KotlinBundle.message("replace.array.of.boxed.with.array.of.primitive")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val psiElement = element ?: return
psiElement.replace(KtPsiFactory(project).createType(fixedType))
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val typeReference = diagnostic.psiElement as? KtTypeReference ?: return null
val type = typeReference.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return null
val itemType = type.getArrayItemType() ?: return null
val itemTypeName = itemType.constructor.declarationDescriptor?.name?.asString() ?: return null
val fixedArrayTypeText = if (itemType.isItemTypeToFix()) {
"${itemTypeName}Array"
} else {
return null
}
return TypeOfAnnotationMemberFix(typeReference, fixedArrayTypeText)
}
private fun KotlinType.getArrayItemType(): KotlinType? {
if (!KotlinBuiltIns.isArray(this)) {
return null
}
val boxedType = arguments.singleOrNull() ?: return null
if (boxedType.isStarProjection) {
return null
}
return boxedType.type
}
private fun KotlinType.isItemTypeToFix() = KotlinBuiltIns.isByte(this)
|| KotlinBuiltIns.isChar(this)
|| KotlinBuiltIns.isShort(this)
|| KotlinBuiltIns.isInt(this)
|| KotlinBuiltIns.isLong(this)
|| KotlinBuiltIns.isFloat(this)
|| KotlinBuiltIns.isDouble(this)
|| KotlinBuiltIns.isBoolean(this)
}
} | apache-2.0 | b96ec84abe7ad808e9263ccfddb267eb | 42.347222 | 158 | 0.704167 | 5.073171 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/yesod/julius/parser/JuliusParserDefinition.kt | 1 | 3003 | package org.jetbrains.yesod.julius.parser
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.jetbrains.yesod.hamlet.psi.*
import org.jetbrains.yesod.hamlet.psi.DotIdentifier
import org.jetbrains.yesod.hamlet.psi.Interpolation
import org.jetbrains.yesod.julius.JuliusFile
import org.jetbrains.yesod.julius.JuliusLanguage
import org.jetbrains.yesod.julius.psi.*
import org.jetbrains.yesod.julius.psi.Number
/**
* @author Leyla H
*/
class JuliusParserDefinition : ParserDefinition {
override fun createLexer(project: Project): Lexer {
return JuliusLexer()
}
override fun createParser(project: Project): PsiParser {
return JuliusParser()
}
override fun getFileNodeType(): IFileElementType {
return JULIUS_FILE
}
override fun getWhitespaceTokens(): TokenSet {
return JuliusTokenTypes.WHITESPACES
}
override fun getCommentTokens(): TokenSet {
return TokenSet.EMPTY
}
override fun getStringLiteralElements(): TokenSet {
return TokenSet.EMPTY
}
override fun createElement(astNode: ASTNode): PsiElement {
if (astNode.elementType === JuliusTokenTypes.KEYWORD) {
return org.jetbrains.yesod.julius.psi.Keyword(astNode)
}
if (astNode.elementType === JuliusTokenTypes.COMMENT) {
return org.jetbrains.yesod.julius.psi.Comment(astNode)
}
if (astNode.elementType === JuliusTokenTypes.NUMBER) {
return org.jetbrains.yesod.julius.psi.Number(astNode)
}
if (astNode.elementType === JuliusTokenTypes.DOT_IDENTIFIER) {
return org.jetbrains.yesod.julius.psi.DotIdentifier(astNode)
}
if (astNode.elementType === JuliusTokenTypes.INTERPOLATION) {
return org.jetbrains.yesod.julius.psi.Interpolation(astNode)
}
if (astNode.elementType === JuliusTokenTypes.STRING) {
return org.jetbrains.yesod.julius.psi.String(astNode)
}
if (astNode.elementType === JuliusTokenTypes.END_INTERPOLATION) {
return org.jetbrains.yesod.julius.psi.Interpolation(astNode)
}
return ASTWrapperPsiElement(astNode)
}
override fun createFile(fileViewProvider: FileViewProvider): PsiFile {
return JuliusFile(fileViewProvider)
}
override fun spaceExistanceTypeBetweenTokens(astNode: ASTNode, astNode2: ASTNode): ParserDefinition.SpaceRequirements {
return ParserDefinition.SpaceRequirements.MAY
}
companion object {
var JULIUS_FILE: IFileElementType = IFileElementType(JuliusLanguage.INSTANCE)
}
}
| apache-2.0 | b988be79a17b59664532bce561eb3f25 | 32.741573 | 123 | 0.719947 | 4.259574 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/info/EventInfoViewModel.kt | 1 | 3795 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.info
import android.net.wifi.WifiConfiguration
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.model.ConferenceWifiInfo
import com.google.samples.apps.iosched.shared.analytics.AnalyticsActions
import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper
import com.google.samples.apps.iosched.shared.domain.logistics.LoadWifiInfoUseCase
import com.google.samples.apps.iosched.shared.result.data
import com.google.samples.apps.iosched.shared.util.tryOffer
import com.google.samples.apps.iosched.ui.messages.SnackbarMessage
import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager
import com.google.samples.apps.iosched.util.WhileViewSubscribed
import com.google.samples.apps.iosched.util.wifi.WifiInstaller
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class EventInfoViewModel @Inject constructor(
loadWifiInfoUseCase: LoadWifiInfoUseCase,
private val wifiInstaller: WifiInstaller,
private val analyticsHelper: AnalyticsHelper,
private val snackbarMessageManager: SnackbarMessageManager
) : ViewModel() {
companion object {
private const val ASSISTANT_APP_URL =
"https://assistant.google.com/services/invoke/uid/0000009fca77b068"
}
val wifiConfig: StateFlow<ConferenceWifiInfo?> = flow {
emit(loadWifiInfoUseCase(Unit).data)
}.stateIn(viewModelScope, SharingStarted.Lazily, null)
val showWifi: StateFlow<Boolean> = wifiConfig.map {
it?.ssid?.isNotBlank() == true && it.password.isNotBlank()
}.stateIn(viewModelScope, WhileViewSubscribed, false)
private val _navigationActions = Channel<EventInfoNavigationAction>(Channel.CONFLATED)
val navigationActions = _navigationActions.receiveAsFlow()
fun onWifiConnect() {
val config = wifiConfig.value ?: return
val success = wifiInstaller.installConferenceWifi(
WifiConfiguration().apply {
SSID = config.ssid
preSharedKey = config.password
}
)
val snackbarMessage = if (success) {
SnackbarMessage(R.string.wifi_install_success)
} else {
SnackbarMessage(
messageId = R.string.wifi_install_clipboard_message, longDuration = true
)
}
snackbarMessageManager.addMessage(snackbarMessage)
analyticsHelper.logUiEvent("Events", AnalyticsActions.WIFI_CONNECT)
}
fun onClickAssistantApp() {
_navigationActions.tryOffer(EventInfoNavigationAction.OpenUrl(ASSISTANT_APP_URL))
analyticsHelper.logUiEvent("Assistant App", AnalyticsActions.CLICK)
}
}
sealed class EventInfoNavigationAction {
data class OpenUrl(val url: String) : EventInfoNavigationAction()
}
| apache-2.0 | 38207226ad26558c76f2d43a5f993e29 | 38.947368 | 90 | 0.756258 | 4.438596 | false | true | false | false |
customerly/Customerly-Android-SDK | customerly-android-sdk/src/main/java/io/customerly/api/ClyApiRequest.kt | 1 | 16624 | @file:Suppress("unused")
package io.customerly.api
/*
* Copyright (C) 2017 Customerly
*
* 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.
*/
import android.Manifest
import android.content.Context
import android.util.Log
import io.customerly.BuildConfig
import io.customerly.Customerly
import io.customerly.entity.ClyJwtToken
import io.customerly.entity.ERROR_CODE__GENERIC
import io.customerly.entity.JWT_KEY
import io.customerly.entity.parseJwtToken
import io.customerly.entity.ping.parsePing
import io.customerly.sxdependencies.annotations.SXIntRange
import io.customerly.sxdependencies.annotations.SXRequiresPermission
import io.customerly.utils.*
import io.customerly.utils.ggkext.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.ref.WeakReference
import java.net.HttpURLConnection
import java.net.URL
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.util.*
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import kotlin.math.max
/**
* Created by Gianni on 19/04/18.
* Project: Customerly-KAndroid-SDK
*/
internal class ClyApiRequest<RESPONSE: Any>
@SXRequiresPermission(Manifest.permission.INTERNET)
internal constructor(
context: Context? = null,
@ClyEndpoint private val endpoint: String,
private val requireToken: Boolean = false,
@SXIntRange(from=1, to=5) private val trials: Int = 1,
private val onPreExecute: ((Context?)->Unit)? = null,
private val jsonObjectConverter: ((JSONObject)->RESPONSE?)? = null,
private val jsonArrayConverter: ((JSONArray)->RESPONSE?)? = null,
private val callback: ((ClyApiResponse<RESPONSE>)->Unit)? = null,
private val reportingErrorEnabled: Boolean = true
){
private val params: JSONObject = JSONObject()
private var wContext: WeakReference<Context>? = context?.weak()
private val context : Context? get() = this.wContext?.get() ?: ClyActivityLifecycleCallback.getLastDisplayedActivity()
internal fun p(key: String, value: Boolean?) = this.apply { if(value != null) this.params.skipException { it.put(key, value) } }
internal fun p(key: String, value: Double?) = this.apply { if(value != null) this.params.skipException { it.put(key, value) } }
internal fun p(key: String, value: Int?) = this.apply { if(value != null) this.params.skipException { it.put(key, value) } }
internal fun p(key: String, value: Long?) = this.apply { if(value != null) this.params.skipException { it.put(key, value) } }
internal fun p(key: String, value: HashMap<*,*>?) = this.apply { if(value != null) this.params.skipException { it.putOpt(key, JSONObject(value)) } }
internal fun p(key: String, value: Any?) = this.apply { if(value != null) this.params.skipException { it.putOpt(key, value) } }
internal fun start() {
Customerly.checkConfigured(reportingErrorEnabled = this.reportingErrorEnabled) {
val context = this.context
if(context?.checkConnection() == false) {
Customerly.log(message = "Check your connection")
ClyApiResponse.Failure<RESPONSE>(errorCode = RESPONSE_STATE__ERROR_NO_CONNECTION).also { errorResponse ->
this.callback?.doOnUiThread {
it.invoke(errorResponse)
}
}
} else {
this.onPreExecute?.invoke(this.context)
val request = this
doOnBackground {
@ClyResponseState var responseState: Int = RESPONSE_STATE__PREPARING
var responseResult: RESPONSE? = null
val appId = Customerly.appId
if (appId != null) {
val params: JSONObject? = when (request.endpoint) {
ENDPOINT_PING, ENDPOINT_REPORT_CRASH -> request.fillParamsWithAppidAndDeviceInfo(params = request.params, appId = appId)
else -> {
when (Customerly.jwtToken) {
null/* no jwt */ -> when (request.requireToken) {
true/* jwt is required */ -> {
//If not token available and token is mandatory, first perform first a ping to obtain it or kill the request
request.executeRequest(endpoint = ENDPOINT_PING, params = request.fillParamsWithAppidAndDeviceInfo(appId = appId))
when (Customerly.jwtToken) {
null/* failed retrieving jwt */ -> {
responseState = RESPONSE_STATE__NO_TOKEN_AVAILABLE
null
}
else/* jwt ok */ -> request.fillParamsWithAppidAndDeviceInfo(params = request.params, appId = appId)
}
}
false/* jwt is not required */ -> request.params
}
else/* jwt ok */ -> request.params
}
}
}
if (responseState == RESPONSE_STATE__PREPARING) {
//No errors
request.executeRequest(jwtToken = Customerly.jwtToken, params = params).let { (state, resultJsonObject, resultJsonArray) ->
responseState = state
if (request.endpoint == ENDPOINT_PING && resultJsonObject != null) {
Customerly.lastPing = resultJsonObject.parsePing()
Customerly.nextPingAllowed = resultJsonObject.optLong("next-ping-allowed", 0)
Customerly.clySocket.connect(newParams = resultJsonObject.optJSONObject("websocket"))
}
responseResult = when {
resultJsonObject != null -> request.jsonObjectConverter?.invoke(resultJsonObject)
resultJsonArray != null -> request.jsonArrayConverter?.invoke(resultJsonArray)
else -> null
}
}
}
} else {
responseState = RESPONSE_STATE__NO_APPID_AVAILABLE
}
val localResult: RESPONSE? = responseResult
request.callback?.doOnUiThread {
it.invoke(
when (responseState) {
RESPONSE_STATE__OK -> if (localResult != null) {
ClyApiResponse.Success(result = localResult)
} else {
ClyApiResponse.Failure(errorCode = RESPONSE_STATE__ERROR_BAD_RESPONSE)
}
else -> ClyApiResponse.Failure(errorCode = responseState)
})
}
}
}
}
}
private fun executeRequest(endpoint: String = this.endpoint, jwtToken: ClyJwtToken? = null, params: JSONObject? = null) : ClyApiInternalResponse {
val requestBody = JSONObject()
.also {
if (jwtToken != null) try {
it.put(JWT_KEY, jwtToken.toString())
} catch (exception: Exception) { }
}
.also {
if (params != null) try {
it.put("params", params)
} catch (exception: Exception) { }
}
return (0 until max(1, this.trials)).asSequence().map {
val conn = (URL(endpoint).openConnection() as HttpURLConnection).apply {
this.doOutput = true
this.requestMethod = "POST"
this.setRequestProperty(HEADER_X_CUSTOMERLY_SDK_KEY, HEADER_X_CUSTOMERLY_SDK_VALUE)
this.setRequestProperty(HEADER_X_CUSTOMERLY_SDK_VERSION_KEY, BuildConfig.VERSION_NAME)
this.setRequestProperty("Content-Type", "application/json")
this.setRequestProperty("Accept-Language", Locale.getDefault().toString())//es: "it_IT"
this.connectTimeout = 10000
if (this is HttpsURLConnection) {
try {
this.sslSocketFactory = SSLContext.getInstance("TLS").let { ssl ->
ssl.init(null, null, SecureRandom())
ssl.socketFactory
}
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: KeyManagementException) {
e.printStackTrace()
}
}
}.also { connection ->
@Suppress("ConstantConditionIf")
if (CUSTOMERLY_DEV_MODE) {
Log.e(CUSTOMERLY_SDK_NAME,
"-----------------------------------------------------------" +
"\nNEW HTTP REQUEST" +
"\n+ Endpoint: " + endpoint +
"\n+ SSL: " + if (connection is HttpsURLConnection) {
"Active"
} else {
"Not Active"
} +
"\n+ METHOD: " + connection.requestMethod +
"\n+ Content-Type: " + connection.getRequestProperty("Content-Type") +
"\n+ Accept-Language: " + connection.getRequestProperty("Accept-Language") +
"\nJSON BODY:\n")
(requestBody
.nullOnException { jo -> jo.toString(4) } ?: "Malformed JSON")
.chunkedSequence(size = 500)
.forEach { row -> Log.e(CUSTOMERLY_SDK_NAME, row) }
Log.e(CUSTOMERLY_SDK_NAME, "\n-----------------------------------------------------------")
}
}
try {
conn.outputStream.use { os ->
os.write(requestBody.toString().toByteArray())
os.flush()
val responseString = BufferedReader(
InputStreamReader(
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
conn.inputStream
} else {
conn.errorStream
})).use { br -> br.lineSequence().joinToString { line -> line } }
nullOnException { JSONObject(responseString) }?.let { responseJO -> //JSONObject Response
@Suppress("ConstantConditionIf")
if (CUSTOMERLY_DEV_MODE) {
Log.e(CUSTOMERLY_SDK_NAME,
"-----------------------------------------------------------" +
"\nHTTP RESPONSE" +
"\n+ Endpoint: " + endpoint +
"\nJSON BODY:\n")
(responseJO
.nullOnException { jo -> jo.toString(4) } ?: "Malformed JSON")
.chunkedSequence(size = 500)
.forEach { row -> Log.e(CUSTOMERLY_SDK_NAME, row) }
Log.e(CUSTOMERLY_SDK_NAME, "\n-----------------------------------------------------------")
}
if (!responseJO.has("error")) {
if (ENDPOINT_PING == endpoint) {
responseJO.parseJwtToken()
}
ClyApiInternalResponse(responseState = RESPONSE_STATE__OK, responseResultJsonObject = responseJO)
} else {
/* example: { "error": "exception_title",
"message": "Exception_message",
"code": "ExceptionCode" } */
val errorCode = responseJO.optInt("code", -1)
Customerly.log(message = "ErrorCode: $errorCode Message: ${responseJO.optTyped(name = "message", fallback = "The server received the request but an error occurred")}")
when (errorCode) {
RESPONSE_STATE__SERVERERROR_APP_INSOLVENT -> {
Customerly.appInsolvent = true
ClyApiInternalResponse(responseState = RESPONSE_STATE__SERVERERROR_APP_INSOLVENT)
}
RESPONSE_STATE__SERVERERROR_USER_NOT_AUTHENTICATED -> {
ClyApiInternalResponse(responseState = RESPONSE_STATE__SERVERERROR_USER_NOT_AUTHENTICATED)
}
/* -1, */ else -> {
ClyApiInternalResponse(responseState = RESPONSE_STATE__ERROR_NETWORK)
}
}
}
} ?: nullOnException { JSONArray(responseString) }?.let { responseJA -> //JSONArray response
ClyApiInternalResponse(responseState = RESPONSE_STATE__OK, responseResultJsonArray = responseJA)
} ?: ClyApiInternalResponse(responseState = RESPONSE_STATE__ERROR_NETWORK)
}
} catch (json : JSONException) {
Customerly.log(message = "The server received the request but an error has come")
ClyApiInternalResponse(responseState = RESPONSE_STATE__ERROR_BAD_RESPONSE)
} catch (json : JSONException) {
Customerly.log(message = "An error occurs during the connection to server")
ClyApiInternalResponse(responseState = RESPONSE_STATE__ERROR_NETWORK)
}
}.withIndex().firstOrNull { iv : IndexedValue<ClyApiInternalResponse> -> iv.value.responseResultJsonObject != null || iv.index == this.trials -1 }?.value ?: ClyApiInternalResponse(responseState = ERROR_CODE__GENERIC)
}
private fun fillParamsWithAppidAndDeviceInfo(params: JSONObject? = null, appId: String): JSONObject {
return (params ?: JSONObject())
.skipException { it.put("app_id", appId)}
.skipException { it.put("device", DeviceJson.json) }
}
}
private data class ClyApiInternalResponse(@ClyResponseState val responseState: Int, val responseResultJsonObject: JSONObject? = null, val responseResultJsonArray: JSONArray? = null)
@Suppress("unused")
internal sealed class ClyApiResponse<RESPONSE: Any> {
internal data class Success<RESPONSE: Any>(
internal val result: RESPONSE) : ClyApiResponse<RESPONSE>()
internal data class Failure<RESPONSE: Any>(
@ClyResponseState internal val errorCode: Int) : ClyApiResponse<RESPONSE>()
}
| apache-2.0 | 03a9ba1c0847c64fca5168f3d86baa0c | 54.973064 | 224 | 0.503609 | 5.517424 | false | false | false | false |
ruslanys/vkmusic | src/main/kotlin/me/ruslanys/vkmusic/service/DefaultDownloadService.kt | 1 | 3276 | package me.ruslanys.vkmusic.service
import me.ruslanys.vkmusic.component.VkClient
import me.ruslanys.vkmusic.domain.Audio
import me.ruslanys.vkmusic.event.DownloadFailEvent
import me.ruslanys.vkmusic.event.DownloadInProgressEvent
import me.ruslanys.vkmusic.event.DownloadSuccessEvent
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executor
@Service
class DefaultDownloadService(
private val vkClient: VkClient,
private val publisher: ApplicationEventPublisher,
@Qualifier("downloadExecutor") private val executor: Executor
) : DownloadService {
@Async
override fun download(destination: File, audio: Audio) {
download(destination, listOf(audio))
}
@Async
override fun download(destination: File, audioList: List<Audio>) {
log.info("Download [{}]", audioList.joinToString { it.id.toString() })
vkClient.fetchUrls(audioList)
if (!destination.exists() || !destination.isDirectory) {
throw IllegalArgumentException("Destination path is incorrect.")
}
for (audio in audioList) {
executor.execute {
downloadFile(destination, audio)
}
}
}
private fun downloadFile(destination: File, audio: Audio) {
log.info("Download file {}", audio.url)
publisher.publishEvent(DownloadInProgressEvent(this, audio))
try {
val connection = URL(audio.url).openConnection() as HttpURLConnection
connection.connectTimeout = CONNECTION_TIMEOUT
connection.readTimeout = CONNECTION_TIMEOUT
val file = File(destination, audio.filename())
BufferedInputStream(connection.inputStream, CONNECTION_BUFFER_SIZE).use { input ->
BufferedOutputStream(FileOutputStream(file), CONNECTION_BUFFER_SIZE).use { output ->
val buff = ByteArray(CONNECTION_BUFFER_SIZE)
var len = 0
while (len != -1) {
len = input.read(buff)
if (len > 0) output.write(buff, 0, len)
}
}
}
publisher.publishEvent(DownloadSuccessEvent(this, audio, file))
} catch (e: Exception) {
publisher.publishEvent(DownloadFailEvent(this, audio, e))
}
}
companion object {
private val log = LoggerFactory.getLogger(DefaultDownloadService::class.java)
private const val CONNECTION_TIMEOUT = 10000
private const val CONNECTION_BUFFER_SIZE = 5120
}
}
fun Audio.filename(): String {
val regex = "[!\"#$%&'()*+,\\-/:;<=>?@\\[\\]^_`{|}~]".toRegex()
val formattedArtist = artist.trim().replace(regex, "")
val formattedTitle = title.trim().replace(regex, "")
return "${formattedArtist.take(10)} - ${formattedTitle.take(20)}.mp3"
} | mit | bc89e80642acac06e9f4d285b97185bb | 35.010989 | 100 | 0.662393 | 4.59467 | false | false | false | false |
leafclick/intellij-community | java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ConvertToRepositoryLibraryActionBase.kt | 1 | 13651 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration.projectRoot
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RepositoryAttachDialog
import com.intellij.jarRepository.RepositoryLibraryType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.AnnotationOrderRootType
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.roots.libraries.NewLibraryConfiguration
import com.intellij.openapi.roots.libraries.ui.OrderRoot
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable
import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditor
import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditorBase
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.*
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import gnu.trove.THashSet
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.idea.maven.utils.library.RepositoryUtils
import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor
import java.io.File
import java.io.IOException
import java.util.*
private val LOG = logger<ConvertToRepositoryLibraryActionBase>()
abstract class ConvertToRepositoryLibraryActionBase(protected val context: StructureConfigurableContext) : DumbAwareAction(
"Convert to Repository Library...",
"Convert a regular library to a repository library which additionally stores its Maven coordinates, so the IDE can automatically download the library JARs if they are missing",
null) {
protected val project: Project = context.project
protected abstract fun getSelectedLibrary(): LibraryEx?
override fun update(e: AnActionEvent) {
val library = getSelectedLibrary()
e.presentation.isEnabledAndVisible = library != null && library.kind == null
}
override fun actionPerformed(e: AnActionEvent) {
val library = getSelectedLibrary() ?: return
val mavenCoordinates = detectOrSpecifyMavenCoordinates(library) ?: return
downloadLibraryAndReplace(library, mavenCoordinates)
}
private fun downloadLibraryAndReplace(library: LibraryEx,
mavenCoordinates: JpsMavenRepositoryLibraryDescriptor) {
val libraryProperties = RepositoryLibraryProperties(mavenCoordinates.groupId, mavenCoordinates.artifactId, mavenCoordinates.version,
mavenCoordinates.isIncludeTransitiveDependencies, mavenCoordinates.excludedDependencies)
val hasSources = RepositoryUtils.libraryHasSources(library)
val hasJavadoc = RepositoryUtils.libraryHasJavaDocs(library)
LOG.debug("Resolving $mavenCoordinates")
val roots: Collection<OrderRoot> =
JarRepositoryManager.loadDependenciesModal(project, libraryProperties, hasSources, hasJavadoc, null, null)
val downloadedFiles = roots.filter { it.type == OrderRootType.CLASSES }.map { VfsUtilCore.virtualToIoFile(it.file) }
if (downloadedFiles.isEmpty()) {
if (Messages.showYesNoDialog("No files were downloaded. Do you want to try different coordinates?", "Failed to Download Library",
null) != Messages.YES) {
return
}
changeCoordinatesAndRetry(mavenCoordinates, library)
return
}
val libraryFiles = library.getFiles(OrderRootType.CLASSES).map { VfsUtilCore.virtualToIoFile(it) }
val task = ComparingJarFilesTask(project, downloadedFiles, libraryFiles)
task.queue()
if (task.cancelled) return
if (!task.filesAreTheSame) {
val dialog = LibraryJarsDiffDialog(task.libraryFileToCompare, task.downloadedFileToCompare, mavenCoordinates,
LibraryUtil.getPresentableName(library), project)
dialog.show()
task.deleteTemporaryFiles()
when (dialog.exitCode) {
DialogWrapper.CANCEL_EXIT_CODE -> return
LibraryJarsDiffDialog.CHANGE_COORDINATES_CODE -> {
changeCoordinatesAndRetry(mavenCoordinates, library)
return
}
}
}
ApplicationManager.getApplication().invokeLater {
replaceByLibrary(library,
object : NewLibraryConfiguration(library.name ?: "", RepositoryLibraryType.getInstance(), libraryProperties) {
override fun addRoots(editor: LibraryEditor) {
editor.addRoots(roots)
}
})
}
}
private fun changeCoordinatesAndRetry(mavenCoordinates: JpsMavenRepositoryLibraryDescriptor, library: LibraryEx) {
val coordinates = specifyMavenCoordinates(listOf(mavenCoordinates)) ?: return
ApplicationManager.getApplication().invokeLater {
downloadLibraryAndReplace(library, coordinates)
}
}
private fun detectOrSpecifyMavenCoordinates(library: Library): JpsMavenRepositoryLibraryDescriptor? {
val detectedCoordinates = detectMavenCoordinates(library.getFiles(OrderRootType.CLASSES))
LOG.debug("Maven coordinates for ${LibraryUtil.getPresentableName(library)} JARs: $detectedCoordinates")
if (detectedCoordinates.size == 1) {
return detectedCoordinates[0]
}
val message = if (detectedCoordinates.isEmpty()) "Cannot detect Maven coordinates from the library JARs" else "Multiple Maven coordinates are found in the library JARs"
if (Messages.showYesNoDialog(project, "$message. Do you want to search Maven repositories manually?", "Cannot Detect Maven Coordinates", null) != Messages.YES) {
return null
}
return specifyMavenCoordinates(detectedCoordinates)
}
private fun specifyMavenCoordinates(detectedCoordinates: List<JpsMavenRepositoryLibraryDescriptor>): JpsMavenRepositoryLibraryDescriptor? {
val dialog = RepositoryAttachDialog(project, detectedCoordinates.firstOrNull()?.mavenId, RepositoryAttachDialog.Mode.SEARCH)
if (!dialog.showAndGet()) {
return null
}
return dialog.selectedLibraryDescriptor
}
private fun replaceByLibrary(library: Library, configuration: NewLibraryConfiguration) {
val annotationUrls = library.getUrls(AnnotationOrderRootType.getInstance())
ProjectStructureConfigurable.getInstance(project).registerObsoleteLibraryRoots((library.getFiles(OrderRootType.CLASSES) +
library.getFiles(OrderRootType.SOURCES)).asList())
replaceLibrary(library) { editor ->
editor.properties = configuration.properties
editor.removeAllRoots()
configuration.addRoots(editor)
annotationUrls.forEach { editor.addRoot(it, AnnotationOrderRootType.getInstance()) }
}
}
protected abstract fun replaceLibrary(library: Library, configureNewLibrary: (LibraryEditorBase) -> Unit)
companion object {
fun detectMavenCoordinates(libraryRoots: Array<out VirtualFile>): List<JpsMavenRepositoryLibraryDescriptor> =
libraryRoots.flatMap { root ->
val pomPropertiesFiles = root.findFileByRelativePath("META-INF/maven")?.children?.flatMap { groupDir ->
groupDir.children?.mapNotNull { artifactDir ->
artifactDir.findChild("pom.properties")
} ?: emptyList()
} ?: emptyList()
pomPropertiesFiles.mapNotNull { parsePomProperties(it) }
}
private fun parsePomProperties(virtualFile: VirtualFile): JpsMavenRepositoryLibraryDescriptor? {
val properties = Properties()
try {
virtualFile.inputStream.use { properties.load(it) }
}
catch(e: IOException) {
return null
}
val groupId = properties.getProperty("groupId")
val artifactId = properties.getProperty("artifactId")
val version = properties.getProperty("version")
return if (groupId != null && artifactId != null && version != null) JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version) else null
}
}
}
private class ComparingJarFilesTask(project: Project, private val downloadedFiles: List<File>,
private val libraryFiles: List<File>) : Task.Modal(project, "Comparing JAR Files...", true) {
var cancelled = false
var filesAreTheSame = false
lateinit var downloadedFileToCompare: VirtualFile
lateinit var libraryFileToCompare: VirtualFile
val filesToDelete = ArrayList<File>()
override fun run(indicator: ProgressIndicator) {
filesAreTheSame = filesAreTheSame()
if (!filesAreTheSame) {
val libraryIoFileToCompare: File
val downloadedIoFileToCompare: File
if (libraryFiles.size == 1 && downloadedFiles.size == 1) {
libraryIoFileToCompare = libraryFiles[0]
//ensure that the files have the same name so DirDiffViewer will show differences between them properly
if (downloadedFiles[0].name == libraryFiles[0].name) {
downloadedIoFileToCompare = downloadedFiles[0]
}
else {
val downloadedFilesIoDir = FileUtil.createTempDirectory("downloaded_file", "", true)
downloadedIoFileToCompare = File(downloadedFilesIoDir, libraryFiles[0].name)
FileUtil.copy(downloadedFiles[0], downloadedIoFileToCompare)
filesToDelete += downloadedFilesIoDir
}
}
else {
//probably we can enhance DirDiffViewer to accept set of files to avoid copying files into temporary directory
libraryIoFileToCompare = FileUtil.createTempDirectory("library_files", "", true)
filesToDelete += libraryIoFileToCompare
libraryFiles.forEach { FileUtil.copy(it, File(libraryIoFileToCompare, it.name)) }
downloadedIoFileToCompare = FileUtil.createTempDirectory("downloaded_files", "", true)
downloadedFiles.forEach { FileUtil.copy(it, File(downloadedIoFileToCompare, it.name)) }
filesToDelete += downloadedIoFileToCompare
}
WriteAction.computeAndWait(ThrowableComputable<Unit, RuntimeException> {
libraryFileToCompare = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(libraryIoFileToCompare)!!
downloadedFileToCompare = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(downloadedIoFileToCompare)!!
})
RefreshQueue.getInstance().refresh(false, false, null, libraryFileToCompare, downloadedFileToCompare)
val jarFilesToRefresh = ArrayList<VirtualFile>()
WriteAction.computeAndWait(ThrowableComputable<Unit, RuntimeException> {
collectNestedJars(libraryFileToCompare, jarFilesToRefresh)
collectNestedJars(downloadedFileToCompare, jarFilesToRefresh)
})
RefreshQueue.getInstance().refresh(false, true, null, jarFilesToRefresh)
}
}
private fun collectNestedJars(file: VirtualFile, result: MutableList<VirtualFile>) {
if (file.isDirectory) {
file.children.forEach { collectNestedJars(it, result) }
}
else if (file.fileType == ArchiveFileType.INSTANCE) {
val jarRootUrl = VfsUtil.getUrlForLibraryRoot(VfsUtil.virtualToIoFile(file))
VirtualFileManager.getInstance().refreshAndFindFileByUrl(jarRootUrl)?.let { result.add(it) }
}
}
fun deleteTemporaryFiles() {
FileUtil.asyncDelete(filesToDelete)
}
override fun onCancel() {
cancelled = true
}
private fun filesAreTheSame(): Boolean {
LOG.debug {"Downloaded files: ${downloadedFiles.joinToString { "${it.name} (${it.length()} bytes)" }}"}
LOG.debug {"Library files: ${libraryFiles.joinToString { "${it.name} (${it.length()} bytes)" }}"}
if (downloadedFiles.size != libraryFiles.size) {
return false
}
val contentHashing = object : TObjectHashingStrategy<File> {
override fun computeHashCode(file: File) = file.length().toInt()
override fun equals(o1: File, o2: File): Boolean {
val equal = contentEqual(o1, o2)
LOG.debug(" comparing files: ${o1.absolutePath}${if (equal) "==" else "!="}${o2.absolutePath}")
return equal
}
}
return THashSet(downloadedFiles, contentHashing) == THashSet(libraryFiles, contentHashing)
}
private fun contentEqual(file1: File, file2: File): Boolean {
if (file1.length() != file2.length()) return false
file1.inputStream().use { input1 ->
file2.inputStream().use { input2 ->
val buffer1 = ByteArray(4096)
val buffer2 = ByteArray(4096)
while (true) {
val len1 = input1.read(buffer1)
val len2 = input2.read(buffer2)
if (len1 != len2) return false
if (len1 <= 0) break
for (i in 0 until len1) {
if (buffer1[i] != buffer2[i]) return false
}
}
return true
}
}
}
}
| apache-2.0 | d1b297bfb52974b5f6893ce8e657e955 | 45.431973 | 178 | 0.727273 | 4.964 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/exports/ExportedDataReference.kt | 1 | 817 | package org.purescript.psi.exports
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReferenceBase
class ExportedDataReference(exportedData: PSExportedData) : PsiReferenceBase<PSExportedData>(
exportedData,
exportedData.properName.textRangeInParent,
false
) {
override fun getVariants(): Array<PsiNamedElement> =
candidates.distinctBy { it.name }
.toTypedArray()
override fun resolve(): PsiElement? =
candidates.firstOrNull { it.name == myElement.name }
private val candidates: Array<PsiNamedElement>
get() =
myElement.module?.run {
arrayOf(
*dataDeclarations,
*newTypeDeclarations,
)
} ?: emptyArray()
}
| bsd-3-clause | afc22e5a2b74bd6fd0309e6dc7103d91 | 29.259259 | 93 | 0.648715 | 5.01227 | false | false | false | false |
JuliusKunze/kotlin-native | Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/Indexer.kt | 1 | 36243 | /*
* Copyright 2010-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 org.jetbrains.kotlin.native.interop.indexer
import clang.*
import clang.CXIdxEntityKind.*
import clang.CXTypeKind.*
import kotlinx.cinterop.*
private class StructDeclImpl(spelling: String, override val location: Location) : StructDecl(spelling) {
override var def: StructDefImpl? = null
}
private class StructDefImpl(
size: Long, align: Int, decl: StructDecl,
hasNaturalLayout: Boolean
) : StructDef(
size, align, decl,
hasNaturalLayout = hasNaturalLayout
) {
override val fields = mutableListOf<Field>()
override val bitFields = mutableListOf<BitField>()
}
private class EnumDefImpl(spelling: String, type: Type, override val location: Location) : EnumDef(spelling, type) {
override val constants = mutableListOf<EnumConstant>()
}
private interface ObjCContainerImpl {
val protocols: MutableList<ObjCProtocol>
val methods: MutableList<ObjCMethod>
val properties: MutableList<ObjCProperty>
}
private class ObjCProtocolImpl(
name: String,
override val location: Location,
override val isForwardDeclaration: Boolean
) : ObjCProtocol(name), ObjCContainerImpl {
override val protocols = mutableListOf<ObjCProtocol>()
override val methods = mutableListOf<ObjCMethod>()
override val properties = mutableListOf<ObjCProperty>()
}
private class ObjCClassImpl(
name: String,
override val location: Location,
override val isForwardDeclaration: Boolean
) : ObjCClass(name), ObjCContainerImpl {
override val protocols = mutableListOf<ObjCProtocol>()
override val methods = mutableListOf<ObjCMethod>()
override val properties = mutableListOf<ObjCProperty>()
override var baseClass: ObjCClass? = null
}
private class ObjCCategoryImpl(
name: String, clazz: ObjCClass
) : ObjCCategory(name, clazz), ObjCContainerImpl {
override val protocols = mutableListOf<ObjCProtocol>()
override val methods = mutableListOf<ObjCMethod>()
override val properties = mutableListOf<ObjCProperty>()
}
internal class NativeIndexImpl(val library: NativeLibrary) : NativeIndex() {
private sealed class DeclarationID {
data class USR(val usr: String) : DeclarationID()
object VaList : DeclarationID()
object VaListTag : DeclarationID()
object BuiltinVaList : DeclarationID()
object Protocol : DeclarationID()
}
private inner class TypeDeclarationRegistry<D : TypeDeclaration> {
private val all = mutableMapOf<DeclarationID, D>()
val included = mutableListOf<D>()
inline fun getOrPut(cursor: CValue<CXCursor>, create: () -> D) = getOrPut(cursor, create, configure = {})
inline fun getOrPut(cursor: CValue<CXCursor>, create: () -> D, configure: (D) -> Unit): D {
val key = getDeclarationId(cursor)
return all.getOrElse(key) {
val value = create()
all[key] = value
val headerId = getHeaderId(getContainingFile(cursor))
if (!library.headerInclusionPolicy.excludeAll(headerId)) {
// This declaration is used, and thus should be included:
included.add(value)
}
configure(value)
value
}
}
}
internal fun getHeaderId(file: CXFile?): HeaderId {
if (file == null) {
return HeaderId("builtins")
}
val filePath = clang_getFileName(file).convertAndDispose()
return library.headerToIdMapper.getHeaderId(filePath)
}
private fun getContainingFile(cursor: CValue<CXCursor>): CXFile? {
return clang_getCursorLocation(cursor).getContainingFile()
}
private fun getLocation(cursor: CValue<CXCursor>): Location {
val headerId = getHeaderId(getContainingFile(cursor))
return Location(headerId)
}
override val structs: List<StructDecl> get() = structRegistry.included
private val structRegistry = TypeDeclarationRegistry<StructDeclImpl>()
override val enums: List<EnumDef> get() = enumRegistry.included
private val enumRegistry = TypeDeclarationRegistry<EnumDefImpl>()
override val objCClasses: List<ObjCClass> get() = objCClassRegistry.included
private val objCClassRegistry = TypeDeclarationRegistry<ObjCClassImpl>()
override val objCProtocols: List<ObjCProtocol> get() = objCProtocolRegistry.included
private val objCProtocolRegistry = TypeDeclarationRegistry<ObjCProtocolImpl>()
override val objCCategories: Collection<ObjCCategory> get() = objCCategoryById.values
private val objCCategoryById = mutableMapOf<DeclarationID, ObjCCategoryImpl>()
override val typedefs get() = typedefRegistry.included
private val typedefRegistry = TypeDeclarationRegistry<TypedefDef>()
private val functionById = mutableMapOf<DeclarationID, FunctionDecl>()
override val functions: Collection<FunctionDecl>
get() = functionById.values
override val macroConstants = mutableListOf<ConstantDef>()
private val globalById = mutableMapOf<DeclarationID, GlobalDecl>()
override val globals: Collection<GlobalDecl>
get() = globalById.values
override lateinit var includedHeaders: List<HeaderId>
private fun getDeclarationId(cursor: CValue<CXCursor>): DeclarationID {
val usr = clang_getCursorUSR(cursor).convertAndDispose()
if (usr == "") {
val kind = cursor.kind
val spelling = getCursorSpelling(cursor)
return when (kind to spelling) {
CXCursorKind.CXCursor_StructDecl to "__va_list_tag" -> DeclarationID.VaListTag
CXCursorKind.CXCursor_StructDecl to "__va_list" -> DeclarationID.VaList
CXCursorKind.CXCursor_TypedefDecl to "__builtin_va_list" -> DeclarationID.BuiltinVaList
CXCursorKind.CXCursor_ObjCInterfaceDecl to "Protocol" -> DeclarationID.Protocol
else -> error(kind to spelling)
}
}
return DeclarationID.USR(usr)
}
private fun getStructDeclAt(
cursor: CValue<CXCursor>
): StructDeclImpl = structRegistry.getOrPut(cursor, { createStructDecl(cursor) }) { decl ->
val definitionCursor = clang_getCursorDefinition(cursor)
if (clang_Cursor_isNull(definitionCursor) == 0) {
assert(clang_isCursorDefinition(definitionCursor) != 0)
createStructDef(decl, cursor)
}
}
private fun createStructDecl(cursor: CValue<CXCursor>): StructDeclImpl {
val cursorType = clang_getCursorType(cursor)
val typeSpelling = clang_getTypeSpelling(cursorType).convertAndDispose()
return StructDeclImpl(typeSpelling, getLocation(cursor))
}
private fun createStructDef(structDecl: StructDeclImpl, cursor: CValue<CXCursor>) {
val type = clang_getCursorType(cursor)
val size = clang_Type_getSizeOf(type)
val align = clang_Type_getAlignOf(type).toInt()
val structDef = StructDefImpl(
size, align, structDecl,
hasNaturalLayout = structHasNaturalLayout(cursor)
)
structDecl.def = structDef
addDeclaredFields(structDef, type, type)
}
private fun addDeclaredFields(structDef: StructDefImpl, structType: CValue<CXType>, containerType: CValue<CXType>) {
getFields(containerType).forEach { fieldCursor ->
val name = getCursorSpelling(fieldCursor)
if (name.isNotEmpty()) {
val fieldType = convertCursorType(fieldCursor)
val offset = clang_Type_getOffsetOf(structType, name)
if (clang_Cursor_isBitField(fieldCursor) == 0) {
val typeAlign = clang_Type_getAlignOf(clang_getCursorType(fieldCursor))
structDef.fields.add(Field(name, fieldType, offset, typeAlign))
} else {
val size = clang_getFieldDeclBitWidth(fieldCursor)
structDef.bitFields.add(BitField(name, fieldType, offset, size))
}
} else {
// Unnamed field.
val fieldType = clang_getCursorType(fieldCursor)
when (fieldType.kind) {
CXTypeKind.CXType_Record -> {
// Unnamed struct fields also contribute their fields:
addDeclaredFields(structDef, structType, fieldType)
}
else -> {
// Nothing.
}
}
}
}
}
private fun getEnumDefAt(cursor: CValue<CXCursor>): EnumDefImpl {
if (clang_isCursorDefinition(cursor) == 0) {
TODO("support enum forward declarations")
}
return enumRegistry.getOrPut(cursor) {
val cursorType = clang_getCursorType(cursor)
val typeSpelling = clang_getTypeSpelling(cursorType).convertAndDispose()
val baseType = convertType(clang_getEnumDeclIntegerType(cursor))
val enumDef = EnumDefImpl(typeSpelling, baseType, getLocation(cursor))
visitChildren(cursor) { childCursor, _ ->
if (clang_getCursorKind(childCursor) == CXCursorKind.CXCursor_EnumConstantDecl) {
val name = clang_getCursorSpelling(childCursor).convertAndDispose()
val value = clang_getEnumConstantDeclValue(childCursor)
val constant = EnumConstant(name, value, isExplicitlyDefined = !childCursor.isLeaf())
enumDef.constants.add(constant)
}
CXChildVisitResult.CXChildVisit_Continue
}
enumDef
}
}
private fun getObjCCategoryClassCursor(cursor: CValue<CXCursor>): CValue<CXCursor> {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCCategoryDecl)
var classRef: CValue<CXCursor>? = null
visitChildren(cursor) { child, _ ->
if (child.kind == CXCursorKind.CXCursor_ObjCClassRef) {
classRef = child
CXChildVisitResult.CXChildVisit_Break
} else {
CXChildVisitResult.CXChildVisit_Continue
}
}
return clang_getCursorReferenced(classRef!!).apply {
assert(this.kind == CXCursorKind.CXCursor_ObjCInterfaceDecl)
}
}
private fun isObjCInterfaceDeclForward(cursor: CValue<CXCursor>): Boolean {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCInterfaceDecl) { cursor.kind }
// It is forward declaration <=> the first child is reference to it:
var result = false
visitChildren(cursor) { child, _ ->
result = (child.kind == CXCursorKind.CXCursor_ObjCClassRef && clang_getCursorReferenced(child) == cursor)
CXChildVisitResult.CXChildVisit_Break
}
return result
}
private fun getObjCClassAt(cursor: CValue<CXCursor>): ObjCClassImpl {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCInterfaceDecl) { cursor.kind }
val name = clang_getCursorDisplayName(cursor).convertAndDispose()
if (isObjCInterfaceDeclForward(cursor)) {
return objCClassRegistry.getOrPut(cursor) {
ObjCClassImpl(name, getLocation(cursor), isForwardDeclaration = true)
}
}
return objCClassRegistry.getOrPut(cursor, {
ObjCClassImpl(name, getLocation(cursor), isForwardDeclaration = false)
}) {
addChildrenToObjCContainer(cursor, it)
}
}
private fun getObjCProtocolAt(cursor: CValue<CXCursor>): ObjCProtocolImpl {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCProtocolDecl) { cursor.kind }
val name = clang_getCursorDisplayName(cursor).convertAndDispose()
if (clang_isCursorDefinition(cursor) == 0) {
val definition = clang_getCursorDefinition(cursor)
return if (clang_isCursorDefinition(definition) != 0) {
getObjCProtocolAt(definition)
} else {
objCProtocolRegistry.getOrPut(cursor) {
ObjCProtocolImpl(name, getLocation(cursor), isForwardDeclaration = true)
}
}
}
return objCProtocolRegistry.getOrPut(cursor, {
ObjCProtocolImpl(name, getLocation(cursor), isForwardDeclaration = false)
}) {
addChildrenToObjCContainer(cursor, it)
}
}
private fun getObjCCategoryAt(cursor: CValue<CXCursor>): ObjCCategoryImpl? {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCCategoryDecl) { cursor.kind }
val classCursor = getObjCCategoryClassCursor(cursor)
if (!isAvailable(classCursor)) return null
val name = clang_getCursorDisplayName(cursor).convertAndDispose()
val declarationId = getDeclarationId(cursor)
return objCCategoryById.getOrPut(declarationId) {
val clazz = getObjCClassAt(classCursor)
val category = ObjCCategoryImpl(name, clazz)
addChildrenToObjCContainer(cursor, category)
category
}
}
private fun addChildrenToObjCContainer(cursor: CValue<CXCursor>, result: ObjCContainerImpl) {
visitChildren(cursor) { child, _ ->
when (child.kind) {
CXCursorKind.CXCursor_ObjCSuperClassRef -> {
assert(cursor.kind == CXCursorKind.CXCursor_ObjCInterfaceDecl)
result as ObjCClassImpl
assert(result.baseClass == null)
result.baseClass = getObjCClassAt(clang_getCursorReferenced(child))
}
CXCursorKind.CXCursor_ObjCProtocolRef -> {
val protocol = getObjCProtocolAt(clang_getCursorReferenced(child))
if (protocol !in result.protocols) {
result.protocols.add(protocol)
}
}
CXCursorKind.CXCursor_ObjCClassMethodDecl, CXCursorKind.CXCursor_ObjCInstanceMethodDecl -> {
getObjCMethod(child)?.let { method ->
result.methods.removeAll { method.replaces(it) }
result.methods.add(method)
}
}
else -> {
}
}
CXChildVisitResult.CXChildVisit_Continue
}
}
fun getTypedef(type: CValue<CXType>): Type {
val declCursor = clang_getTypeDeclaration(type)
val name = getCursorSpelling(declCursor)
val underlying = convertType(clang_getTypedefDeclUnderlyingType(declCursor))
if (underlying == UnsupportedType) return underlying
if (clang_getCursorLexicalParent(declCursor).kind != CXCursorKind.CXCursor_TranslationUnit) {
// Objective-C type parameters are represented as non-top-level typedefs.
// Erase for now:
return underlying
}
if (library.language == Language.OBJECTIVE_C) {
if (name == "BOOL" || name == "Boolean") {
assert(clang_Type_getSizeOf(type) == 1L)
return BoolType
}
if (underlying is ObjCPointer && (name == "Class" || name == "id") ||
underlying is PointerType && name == "SEL") {
// Ignore implicit Objective-C typedefs:
return underlying
}
}
if ((underlying is RecordType && underlying.decl.spelling.split(' ').last() == name) ||
(underlying is EnumType && underlying.def.spelling.split(' ').last() == name)) {
// special handling for:
// typedef struct { ... } name;
// typedef enum { ... } name;
// FIXME: implement better solution
return underlying
}
val typedefDef = typedefRegistry.getOrPut(declCursor) {
TypedefDef(underlying, name, getLocation(declCursor))
}
return Typedef(typedefDef)
}
/**
* Computes [StructDef.hasNaturalLayout] property.
*/
fun structHasNaturalLayout(structDefCursor: CValue<CXCursor>): Boolean {
val defKind = structDefCursor.kind
when (defKind) {
CXCursorKind.CXCursor_UnionDecl -> return false
CXCursorKind.CXCursor_StructDecl -> {
var hasAttributes = false
visitChildren(structDefCursor) { cursor, _ ->
if (clang_isAttribute(cursor.kind) != 0) {
hasAttributes = true
}
CXChildVisitResult.CXChildVisit_Continue
}
return !hasAttributes
}
else -> throw IllegalArgumentException(defKind.toString())
}
}
private fun convertCursorType(cursor: CValue<CXCursor>) =
convertType(clang_getCursorType(cursor), clang_getDeclTypeAttributes(cursor))
private inline fun objCType(supplier: () -> ObjCPointer) = when (library.language) {
Language.C -> UnsupportedType
Language.OBJECTIVE_C -> supplier()
}
fun convertType(type: CValue<CXType>, typeAttributes: CValue<CXTypeAttributes>? = null): Type {
val primitiveType = convertUnqualifiedPrimitiveType(type)
if (primitiveType != UnsupportedType) {
return primitiveType
}
val kind = type.kind
return when (kind) {
CXType_Elaborated -> convertType(clang_Type_getNamedType(type))
CXType_Unexposed -> {
if (clang_getResultType(type).kind != CXTypeKind.CXType_Invalid) {
convertFunctionType(type)
} else {
val canonicalType = clang_getCanonicalType(type)
if (canonicalType.kind != CXType_Unexposed) {
convertType(canonicalType)
} else {
UnsupportedType
}
}
}
CXType_Void -> VoidType
CXType_Typedef -> {
val declCursor = clang_getTypeDeclaration(type)
val declSpelling = getCursorSpelling(declCursor)
val underlying = convertType(clang_getTypedefDeclUnderlyingType(declCursor))
when {
declSpelling == "instancetype" && underlying is ObjCPointer ->
ObjCInstanceType(getNullability(type, typeAttributes))
else -> getTypedef(type)
}
}
CXType_Record -> RecordType(getStructDeclAt(clang_getTypeDeclaration(type)))
CXType_Enum -> EnumType(getEnumDefAt(clang_getTypeDeclaration(type)))
CXType_Pointer -> {
val pointeeType = clang_getPointeeType(type)
val pointeeIsConst =
(clang_isConstQualifiedType(clang_getCanonicalType(pointeeType)) != 0)
val convertedPointeeType = convertType(pointeeType)
PointerType(
if (convertedPointeeType == UnsupportedType) VoidType else convertedPointeeType,
pointeeIsConst = pointeeIsConst
)
}
CXType_ConstantArray -> {
val elemType = convertType(clang_getArrayElementType(type))
val length = clang_getArraySize(type)
ConstArrayType(elemType, length)
}
CXType_IncompleteArray -> {
val elemType = convertType(clang_getArrayElementType(type))
IncompleteArrayType(elemType)
}
CXType_FunctionProto -> {
convertFunctionType(type)
}
CXType_ObjCObjectPointer -> objCType {
val declaration = clang_getTypeDeclaration(clang_getPointeeType(type))
val declarationKind = declaration.kind
val nullability = getNullability(type, typeAttributes)
when (declarationKind) {
CXCursorKind.CXCursor_NoDeclFound -> ObjCIdType(nullability, getProtocols(type))
CXCursorKind.CXCursor_ObjCInterfaceDecl ->
ObjCObjectPointer(getObjCClassAt(declaration), nullability, getProtocols(type))
CXCursorKind.CXCursor_TypedefDecl ->
// typedef to Objective-C class itself, e.g. `typedef NSObject Object;`,
// (as opposed to `typedef NSObject* Object;`).
// Note: it is not yet represented as Kotlin `typealias`.
ObjCObjectPointer(
getObjCClassAt(getTypedefUnderlyingObjCClass(declaration)),
nullability,
getProtocols(type)
)
else -> TODO("${declarationKind.toString()} ${clang_getTypeSpelling(type).convertAndDispose()}")
}
}
CXType_ObjCId -> objCType { ObjCIdType(getNullability(type, typeAttributes), getProtocols(type)) }
CXType_ObjCClass -> objCType { ObjCClassPointer(getNullability(type, typeAttributes), getProtocols(type)) }
CXType_ObjCSel -> PointerType(VoidType)
CXType_BlockPointer -> objCType { convertBlockPointerType(type, typeAttributes) }
else -> UnsupportedType
}
}
private tailrec fun getTypedefUnderlyingObjCClass(typedefDecl: CValue<CXCursor>): CValue<CXCursor> {
assert(typedefDecl.kind == CXCursorKind.CXCursor_TypedefDecl)
val underlyingType = clang_getTypedefDeclUnderlyingType(typedefDecl)
val underlyingTypeDecl = clang_getTypeDeclaration(underlyingType)
return when (underlyingTypeDecl.kind) {
CXCursorKind.CXCursor_TypedefDecl -> getTypedefUnderlyingObjCClass(underlyingTypeDecl)
CXCursorKind.CXCursor_ObjCInterfaceDecl -> underlyingTypeDecl
else -> TODO(
"""typedef = ${getCursorSpelling(typedefDecl)}
|underlying decl kind = ${underlyingTypeDecl.kind}
|underlying = ${clang_getTypeSpelling(underlyingType).convertAndDispose()}""".trimMargin()
)
}
}
private fun getNullability(
type: CValue<CXType>, typeAttributes: CValue<CXTypeAttributes>?
): ObjCPointer.Nullability {
if (typeAttributes == null) return ObjCPointer.Nullability.Unspecified
return when (clang_Type_getNullabilityKind(type, typeAttributes)) {
CXNullabilityKind.CXNullabilityKind_Nullable -> ObjCPointer.Nullability.Nullable
CXNullabilityKind.CXNullabilityKind_NonNull -> ObjCPointer.Nullability.NonNull
CXNullabilityKind.CXNullabilityKind_Unspecified -> ObjCPointer.Nullability.Unspecified
}
}
private fun getProtocols(type: CValue<CXType>): List<ObjCProtocol> {
val num = clang_Type_getNumProtocols(type)
return (0 until num).map { index ->
getObjCProtocolAt(clang_Type_getProtocol(type, index))
}
}
private fun convertFunctionType(type: CValue<CXType>): Type {
val kind = type.kind
assert(kind == CXType_Unexposed || kind == CXType_FunctionProto)
if (clang_isFunctionTypeVariadic(type) != 0) {
return VoidType // make this function pointer opaque.
} else {
val returnType = convertType(clang_getResultType(type))
val numArgs = clang_getNumArgTypes(type)
val paramTypes = (0..numArgs - 1).map {
convertType(clang_getArgType(type, it))
}
return if (returnType == UnsupportedType || paramTypes.any { it == UnsupportedType }) {
VoidType
} else {
FunctionType(paramTypes, returnType)
}
}
}
private fun convertBlockPointerType(type: CValue<CXType>, typeAttributes: CValue<CXTypeAttributes>?): ObjCPointer {
val kind = type.kind
assert(kind == CXType_BlockPointer)
val pointee = clang_getPointeeType(type)
val nullability = getNullability(type, typeAttributes)
// TODO: also use nullability attributes of parameters and return value.
val functionType = convertFunctionType(pointee) as? FunctionType
?: return ObjCIdType(nullability, protocols = emptyList())
return ObjCBlockPointer(nullability, functionType.parameterTypes, functionType.returnType)
}
private val TARGET_ATTRIBUTE = "__target__"
internal fun tokenizeExtent(cursor: CValue<CXCursor>): List<String> {
val translationUnit = clang_Cursor_getTranslationUnit(cursor)!!
val cursorExtent = clang_getCursorExtent(cursor)
memScoped {
val tokensVar = alloc<CPointerVar<CXToken>>()
val numTokensVar = alloc<IntVar>()
clang_tokenize(translationUnit, cursorExtent, tokensVar.ptr, numTokensVar.ptr)
val numTokens = numTokensVar.value
val tokens = tokensVar.value
if (tokens == null) return emptyList<String>()
try {
return (0 until numTokens).map {
clang_getTokenSpelling(translationUnit, tokens[it].readValue()).convertAndDispose()
}
} finally {
clang_disposeTokens(translationUnit, tokens, numTokens)
}
}
}
private fun isSuitableFunction(cursor: CValue<CXCursor>): Boolean {
if (!isAvailable(cursor)) return false
// If function is specific for certain target, ignore that, as we may be
// unable to generate machine code for bridge from the bitcode.
// TODO: this must be implemented with hasAttribute(), but hasAttribute()
// works for Mac hosts only so far.
var suitable = true
visitChildren(cursor) { child, _ ->
if (clang_isAttribute(child.kind) != 0) {
suitable = !tokenizeExtent(child).any { it == TARGET_ATTRIBUTE }
}
if (suitable)
CXChildVisitResult.CXChildVisit_Continue
else
CXChildVisitResult.CXChildVisit_Break
}
return suitable
}
fun indexDeclaration(info: CXIdxDeclInfo): Unit {
val cursor = info.cursor.readValue()
val entityInfo = info.entityInfo!!.pointed
val entityName = entityInfo.name?.toKString()
val kind = entityInfo.kind
if (!this.library.includesDeclaration(cursor)) {
return
}
when (kind) {
CXIdxEntity_Struct, CXIdxEntity_Union -> {
if (entityName == null) {
// Skip anonymous struct.
// (It gets included anyway if used as a named field type).
} else {
getStructDeclAt(cursor)
}
}
CXIdxEntity_Typedef -> {
val type = clang_getCursorType(cursor)
getTypedef(type)
}
CXIdxEntity_Function -> {
if (isSuitableFunction(cursor)) {
functionById.getOrPut(getDeclarationId(cursor)) {
getFunction(cursor)
}
}
}
CXIdxEntity_Enum -> {
getEnumDefAt(cursor)
}
CXIdxEntity_Variable -> {
if (info.semanticContainer!!.pointed.cursor.kind == CXCursorKind.CXCursor_TranslationUnit) {
// Top-level variable.
globalById.getOrPut(getDeclarationId(cursor)) {
GlobalDecl(
name = entityName!!,
type = convertCursorType(cursor),
isConst = clang_isConstQualifiedType(clang_getCursorType(cursor)) != 0
)
}
}
}
CXIdxEntity_ObjCClass -> {
if (isAvailable(cursor) &&
cursor.kind != CXCursorKind.CXCursor_ObjCClassRef /* not a forward declaration */) {
getObjCClassAt(cursor)
}
}
CXIdxEntity_ObjCCategory -> {
if (isAvailable(cursor)) {
getObjCCategoryAt(cursor)
}
}
CXIdxEntity_ObjCProtocol -> {
if (isAvailable(cursor) &&
cursor.kind != CXCursorKind.CXCursor_ObjCProtocolRef /* not a forward declaration */) {
getObjCProtocolAt(cursor)
}
}
CXIdxEntity_ObjCProperty -> {
val container = clang_getCursorSemanticParent(cursor)
if (isAvailable(cursor) && isAvailable(container)) {
val propertyInfo = clang_index_getObjCPropertyDeclInfo(info.ptr)!!.pointed
val getter = getObjCMethod(propertyInfo.getter!!.pointed.cursor.readValue())
val setter = propertyInfo.setter?.let {
getObjCMethod(it.pointed.cursor.readValue())
}
if (getter != null) {
val property = ObjCProperty(entityName!!, getter, setter)
val objCContainer: ObjCContainerImpl? = when (container.kind) {
CXCursorKind.CXCursor_ObjCCategoryDecl -> getObjCCategoryAt(container)
CXCursorKind.CXCursor_ObjCInterfaceDecl -> getObjCClassAt(container)
CXCursorKind.CXCursor_ObjCProtocolDecl -> getObjCProtocolAt(container)
else -> error(container.kind)
}
if (objCContainer != null) {
objCContainer.properties.removeAll { property.replaces(it) }
objCContainer.properties.add(property)
}
}
}
}
else -> {
// Ignore declaration.
}
}
}
private fun getFunction(cursor: CValue<CXCursor>): FunctionDecl {
val name = clang_getCursorSpelling(cursor).convertAndDispose()
val returnType = convertType(clang_getCursorResultType(cursor), clang_getCursorResultTypeAttributes(cursor))
val parameters = getFunctionParameters(cursor)
val binaryName = when (library.language) {
Language.C, Language.OBJECTIVE_C -> clang_Cursor_getMangling(cursor).convertAndDispose()
}
val definitionCursor = clang_getCursorDefinition(cursor)
val isDefined = (clang_Cursor_isNull(definitionCursor) == 0)
val isVararg = clang_Cursor_isVariadic(cursor) != 0
return FunctionDecl(name, parameters, returnType, binaryName, isDefined, isVararg)
}
private fun getObjCMethod(cursor: CValue<CXCursor>): ObjCMethod? {
if (!isAvailable(cursor)) {
return null
}
val selector = clang_getCursorDisplayName(cursor).convertAndDispose()
// Ignore some very special methods:
when (selector) {
"dealloc", "retain", "release", "autorelease", "retainCount", "self" -> return null
}
val encoding = clang_getDeclObjCTypeEncoding(cursor).convertAndDispose()
val returnType = convertType(clang_getCursorResultType(cursor), clang_getCursorResultTypeAttributes(cursor))
val parameters = getFunctionParameters(cursor)
if (returnType == UnsupportedType || parameters.any { it.type == UnsupportedType }) {
return null // TODO: make a more universal fix.
}
val isClass = when (cursor.kind) {
CXCursorKind.CXCursor_ObjCClassMethodDecl -> true
CXCursorKind.CXCursor_ObjCInstanceMethodDecl -> false
else -> error(cursor.kind)
}
return ObjCMethod(selector, encoding, parameters, returnType,
isClass = isClass,
nsConsumesSelf = hasAttribute(cursor, NS_CONSUMES_SELF),
nsReturnsRetained = hasAttribute(cursor, NS_RETURNS_RETAINED),
isOptional = (clang_Cursor_isObjCOptional(cursor) != 0),
isInit = (clang_Cursor_isObjCInitMethod(cursor) != 0))
}
// TODO: unavailable declarations should be imported as deprecated.
private fun isAvailable(cursor: CValue<CXCursor>): Boolean = when (clang_getCursorAvailability(cursor)) {
CXAvailabilityKind.CXAvailability_Available,
CXAvailabilityKind.CXAvailability_Deprecated -> true
CXAvailabilityKind.CXAvailability_NotAvailable,
CXAvailabilityKind.CXAvailability_NotAccessible -> false
}
private fun getFunctionParameters(cursor: CValue<CXCursor>): List<Parameter> {
val argNum = clang_Cursor_getNumArguments(cursor)
val args = (0..argNum - 1).map {
val argCursor = clang_Cursor_getArgument(cursor, it)
val argName = getCursorSpelling(argCursor)
val type = convertCursorType(argCursor)
Parameter(argName, type,
nsConsumed = hasAttribute(argCursor, NS_CONSUMED))
}
return args
}
private val NS_CONSUMED = "ns_consumed"
private val NS_CONSUMES_SELF = "ns_consumes_self"
private val NS_RETURNS_RETAINED = "ns_returns_retained"
private fun hasAttribute(cursor: CValue<CXCursor>, name: String): Boolean {
var result = false
visitChildren(cursor) { child, _ ->
if (clang_isAttribute(child.kind) != 0 && clang_Cursor_getAttributeSpelling(child)?.toKString() == name) {
result = true
CXChildVisitResult.CXChildVisit_Break
} else {
CXChildVisitResult.CXChildVisit_Continue
}
}
return result
}
}
fun buildNativeIndexImpl(library: NativeLibrary): NativeIndex {
val result = NativeIndexImpl(library)
indexDeclarations(result)
findMacroConstants(result)
return result
}
private fun indexDeclarations(nativeIndex: NativeIndexImpl) {
val index = clang_createIndex(0, 0)!!
try {
val translationUnit = nativeIndex.library.parse(index, options = CXTranslationUnit_DetailedPreprocessingRecord)
try {
translationUnit.ensureNoCompileErrors()
val headers = getFilteredHeaders(nativeIndex, index, translationUnit)
nativeIndex.includedHeaders = headers.map {
nativeIndex.getHeaderId(it)
}
indexTranslationUnit(index, translationUnit, 0, object : Indexer {
override fun indexDeclaration(info: CXIdxDeclInfo) {
val file = memScoped {
val fileVar = alloc<CXFileVar>()
clang_indexLoc_getFileLocation(info.loc.readValue(), null, fileVar.ptr, null, null, null)
fileVar.value
}
if (file in headers) {
nativeIndex.indexDeclaration(info)
}
}
})
} finally {
clang_disposeTranslationUnit(translationUnit)
}
} finally {
clang_disposeIndex(index)
}
}
| apache-2.0 | 677a388b09ec7ff1ee1a495252113341 | 38.181622 | 120 | 0.604475 | 5.199857 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/expressions/UObjectLiteralExpression.kt | 13 | 1482 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import com.intellij.psi.PsiType
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents an object literal expression, e.g. `new Runnable() {}` in Java.
*/
interface UObjectLiteralExpression : UCallExpression {
/**
* Returns the class declaration.
*/
val declaration: UClass
override val methodIdentifier: UIdentifier?
get() = null
override val kind: UastCallKind
get() = UastCallKind.CONSTRUCTOR_CALL
override val methodName: String?
get() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val returnType: PsiType?
get() = null
override fun accept(visitor: UastVisitor) {
if (visitor.visitObjectLiteralExpression(this)) return
uAnnotations.acceptList(visitor)
valueArguments.acceptList(visitor)
declaration.accept(visitor)
visitor.afterVisitObjectLiteralExpression(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitObjectLiteralExpression(this, data)
override fun asLogString(): String = log()
override fun asRenderString(): String = "anonymous " + declaration.text
} | apache-2.0 | b5f14c612acbec2d05835799a4b2dede | 27.519231 | 140 | 0.740891 | 4.490909 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/ThreeDropdownDateField.kt | 1 | 2991 | package alraune
import pieces100.*
import vgrechka.*
import java.util.*
class ThreeDropdownDateField(
var title: String,
val minYear: Int,
val maxYear: Int)
: FormField<JsonizableLocalDate>, Retupd.With, Retupd.Helpers<ThreeDropdownDateField> {
private var _name by notNull<String>()
private var value by notNull<JsonizableLocalDate>()
private var error by maybeNull<String>()
private var used = false
override val retupd = Retupd<JsonizableLocalDate>()
override fun setName(name: String) {_name = name;}
override fun error() = error
override fun value() = value
fun set(x: JsonizableLocalDate) {value = x}
override fun debug_shitIntoBogusRequestModel_asIfItCameFromClient(model: BogusRequestModel) =
imf()
override fun used() = used
override fun use(source: FieldSource) {
used = true
exhaustive =when (source) {
is FieldSource.Initial -> {
value = initialValue()
error = null
}
is FieldSource.Post -> {
try {
val string = rctx0.ftb.data!![_name] as String
value = dejsonize(JsonizableLocalDate::class, string)!!
val maxDay = GregorianCalendar(value.year, value.month - 1, 1).getActualMaximum(Calendar.DAY_OF_MONTH)
error = when {
value.day > maxDay -> t("TOTE", "Нет такого дня")
else -> null
}
} catch (e: Throwable) {
e.printStackTrace()
value = initialValue()
error = t("TOTE", "Отстойное значение какое-то")
}
}
is FieldSource.DB -> {
value = retupd.retrieve(source.entity)
error = null
}
}
}
private fun initialValue() = JsonizableLocalDate().fill(year = minYear, month = 1, day = 1)
override fun name() = _name
fun compose(): Renderable {
val c1 = Context1.get()
val controlContainerDomid = nextDomid()
val jsControl = "${jsByIdSingle(controlContainerDomid)}[0]._control"
c1.formSubmissionIife("""
ftb.data[${jsStringLiteral(_name)}] = JSON.stringify($jsControl.getValue())
""")
c1.jsOnDomReady.appendIife("""
$jsControl = new ${TS.alraune.ThreeDropdownDatePicker}({
containerDomid: "$controlContainerDomid",
minYear: $minYear,
maxYear: $maxYear,
initialValue: ${jsonize(value)}})
""")
return composeFormGroupWithMaybeError(title, error) {
oo(div().id(controlContainerDomid))
}
}
fun title(x: String) = run {title = x; this}
override fun update(entity: Any) = retupd.update(entity, value)
override fun isOnlyForAdmin() = imf()
}
| apache-2.0 | e12acdf51b04fd66e77c6d27157e12bb | 28.848485 | 122 | 0.562437 | 4.443609 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/test-cases/1/output-expected/json/decoding/DefaultAnnotatedConstructorJsonCodec.kt | 1 | 2123 | package json.decoding
import codecProvider.CustomCodingContext
import io.fluidsonic.json.AbstractJsonCodec
import io.fluidsonic.json.JsonCodingType
import io.fluidsonic.json.JsonDecoder
import io.fluidsonic.json.JsonEncoder
import io.fluidsonic.json.missingPropertyError
import io.fluidsonic.json.readBooleanOrNull
import io.fluidsonic.json.readByteOrNull
import io.fluidsonic.json.readCharOrNull
import io.fluidsonic.json.readDoubleOrNull
import io.fluidsonic.json.readFloatOrNull
import io.fluidsonic.json.readFromMapByElementValue
import io.fluidsonic.json.readIntOrNull
import io.fluidsonic.json.readLongOrNull
import io.fluidsonic.json.readShortOrNull
import io.fluidsonic.json.readStringOrNull
import io.fluidsonic.json.readValueOfType
import io.fluidsonic.json.readValueOfTypeOrNull
import io.fluidsonic.json.writeBooleanOrNull
import io.fluidsonic.json.writeByteOrNull
import io.fluidsonic.json.writeCharOrNull
import io.fluidsonic.json.writeDoubleOrNull
import io.fluidsonic.json.writeFloatOrNull
import io.fluidsonic.json.writeIntOrNull
import io.fluidsonic.json.writeIntoMap
import io.fluidsonic.json.writeLongOrNull
import io.fluidsonic.json.writeMapElement
import io.fluidsonic.json.writeShortOrNull
import io.fluidsonic.json.writeStringOrNull
import io.fluidsonic.json.writeValueOrNull
import kotlin.Unit
internal object DefaultAnnotatedConstructorJsonCodec :
AbstractJsonCodec<DefaultAnnotatedConstructor, CustomCodingContext>() {
public override
fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<DefaultAnnotatedConstructor>):
DefaultAnnotatedConstructor {
var _value = 0L
var value_isPresent = false
readFromMapByElementValue { key ->
when (key) {
"value" -> {
_value = readLong()
value_isPresent = true
}
else -> skipValue()
}
}
value_isPresent || missingPropertyError("value")
return DefaultAnnotatedConstructor(
`value` = _value
)
}
public override fun JsonEncoder<CustomCodingContext>.encode(`value`: DefaultAnnotatedConstructor):
Unit {
writeIntoMap {
writeMapElement("value", string = value.`value`)
}
}
}
| apache-2.0 | f221353f912df6ca7cc37d79da16e290 | 31.166667 | 103 | 0.821008 | 4.615217 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/mapper/impl/PictureMapperImpl.kt | 1 | 1155 | package com.github.vhromada.catalog.mapper.impl
import com.github.vhromada.catalog.common.provider.UuidProvider
import com.github.vhromada.catalog.domain.Picture
import com.github.vhromada.catalog.entity.ChangePictureRequest
import com.github.vhromada.catalog.mapper.PictureMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for pictures.
*
* @author Vladimir Hromada
*/
@Component("pictureMapper")
class PictureMapperImpl(
/**
* Provider for UUID
*/
private val uuidProvider: UuidProvider
) : PictureMapper {
override fun mapPicture(source: Picture): com.github.vhromada.catalog.entity.Picture {
return com.github.vhromada.catalog.entity.Picture(
uuid = source.uuid,
content = source.content
)
}
override fun mapPictures(source: List<Picture>): List<String> {
return source.map { it.uuid }
}
override fun mapRequest(source: ChangePictureRequest): Picture {
return Picture(
id = null,
uuid = uuidProvider.getUuid(),
content = source.content!!
)
}
}
| mit | 3c61ff5054e57f2cb21d4ac465c8f649 | 27.170732 | 90 | 0.690909 | 4.325843 | false | false | false | false |
nrizzio/Signal-Android | app/src/test/java/org/thoughtcrime/securesms/MockCursor.kt | 1 | 673 | package org.thoughtcrime.securesms
import android.database.Cursor
abstract class MockCursor : Cursor {
private var _position: Int = -1
private var _count: Int = 0
override fun getPosition(): Int {
return _position
}
override fun moveToPosition(position: Int): Boolean {
_position = position
return true
}
override fun getCount(): Int {
return _count
}
override fun moveToNext(): Boolean {
_position++
if (_position >= count) {
return false
}
return true
}
override fun isLast(): Boolean {
return _position == count - 1
}
override fun isAfterLast(): Boolean {
return _position >= count
}
}
| gpl-3.0 | ddaafaf6465ef5087e9bd11d0fb942d1 | 16.25641 | 55 | 0.643388 | 4.37013 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinPropertyAccessorBodyFixer.kt | 4 | 1948 | // 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class KotlinPropertyAccessorBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) {
if (psiElement !is KtPropertyAccessor) return
if (psiElement.bodyExpression != null || psiElement.equalsToken != null) return
val parentDeclaration = psiElement.getStrictParentOfType<KtDeclaration>()
if (parentDeclaration is KtClassOrObject) {
if (KtPsiUtil.isTrait(parentDeclaration) || psiElement.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
return
}
}
// accessor without parameter and body is valid
if (psiElement.namePlaceholder.endOffset == psiElement.endOffset) return
val doc = editor.document
var endOffset = psiElement.range.end
if (psiElement.isGetter && psiElement.rightParenthesis == null) {
doc.insertString(endOffset, ")")
endOffset++
}
if (psiElement.text?.last() == ';') {
doc.deleteString(endOffset - 1, endOffset)
endOffset--
}
doc.insertString(endOffset, "{\n}")
}
} | apache-2.0 | 500262876fa461d98a5cfb8c52c9ac8d | 39.604167 | 158 | 0.724846 | 4.982097 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/DelegateSourcePosition.kt | 6 | 1158 | // 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
import com.intellij.debugger.SourcePosition
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
abstract class DelegateSourcePosition(private var delegate: SourcePosition) : SourcePosition() {
override fun getFile(): PsiFile = delegate.file
override fun getElementAt(): PsiElement? = delegate.elementAt
override fun getLine(): Int = delegate.line
override fun getOffset(): Int = delegate.offset
override fun openEditor(requestFocus: Boolean): Editor = delegate.openEditor(requestFocus)
override fun canNavigate() = delegate.canNavigate()
override fun canNavigateToSource() = delegate.canNavigateToSource()
override fun navigate(requestFocus: Boolean) {
delegate.navigate(requestFocus)
}
override fun hashCode(): Int = delegate.hashCode()
override fun equals(other: Any?) = delegate == other
override fun toString() = "DSP($delegate)"
} | apache-2.0 | 2cd1050842d614183929e5a14089f987 | 38.965517 | 158 | 0.756477 | 4.804979 | false | false | false | false |
MyCollab/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/ui/format/TaskFieldFormatter.kt | 3 | 4341 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.ui.format
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum
import com.mycollab.core.utils.HumanTime
import com.mycollab.core.utils.StringUtils
import com.mycollab.module.project.domain.Task
import com.mycollab.module.project.i18n.MilestoneI18nEnum
import com.mycollab.module.project.i18n.OptionI18nEnum.Priority
import com.mycollab.module.project.i18n.TaskI18nEnum
import com.mycollab.module.user.domain.SimpleUser
import com.mycollab.vaadin.UserUIContext
import com.mycollab.vaadin.ui.formatter.FieldGroupFormatter
import com.mycollab.vaadin.ui.formatter.HistoryFieldFormat
import com.mycollab.vaadin.ui.formatter.I18nHistoryFieldFormat
import org.slf4j.LoggerFactory
/**
* @author MyCollab Ltd
* @since 5.1.4
*/
class TaskFieldFormatter private constructor() : FieldGroupFormatter() {
init {
generateFieldDisplayHandler(Task.Field.name.name, GenericI18Enum.FORM_NAME)
generateFieldDisplayHandler(Task.Field.startdate.name, GenericI18Enum.FORM_START_DATE, FieldGroupFormatter.DATE_FIELD)
generateFieldDisplayHandler(Task.Field.enddate.name, GenericI18Enum.FORM_END_DATE, FieldGroupFormatter.DATE_FIELD)
generateFieldDisplayHandler(Task.Field.duedate.name, GenericI18Enum.FORM_DUE_DATE, FieldGroupFormatter.DATE_FIELD)
generateFieldDisplayHandler(Task.Field.priority.name, GenericI18Enum.FORM_PRIORITY,
I18nHistoryFieldFormat(Priority::class.java))
generateFieldDisplayHandler(Task.Field.status.name, GenericI18Enum.FORM_STATUS,
I18nHistoryFieldFormat(StatusI18nEnum::class.java))
generateFieldDisplayHandler(Task.Field.isestimated.name, TaskI18nEnum.FORM_IS_ESTIMATED)
generateFieldDisplayHandler(Task.Field.remainestimate.name, TaskI18nEnum.FORM_REMAIN_ESTIMATE)
generateFieldDisplayHandler(Task.Field.originalestimate.name, TaskI18nEnum.FORM_ORIGINAL_ESTIMATE)
generateFieldDisplayHandler(Task.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE, ProjectMemberHistoryFieldFormat())
generateFieldDisplayHandler(Task.Field.milestoneid.name, MilestoneI18nEnum.SINGLE, MilestoneHistoryFieldFormat())
generateFieldDisplayHandler(Task.Field.percentagecomplete.name, TaskI18nEnum.FORM_PERCENTAGE_COMPLETE)
generateFieldDisplayHandler(Task.Field.description.name, GenericI18Enum.FORM_DESCRIPTION, TRIM_HTMLS)
generateFieldDisplayHandler(Task.Field.duration.name, GenericI18Enum.FORM_DURATION, DurationFieldFormat())
}
private class DurationFieldFormat : HistoryFieldFormat {
override fun toString(value: String): String =
toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY))
override fun toString(currentViewUser:SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String =
when {
StringUtils.isNotBlank(value) -> try {
val duration = java.lang.Long.parseLong(value)
val humanTime = HumanTime(duration)
humanTime.exactly
} catch (e: Exception) {
LOG.error("Parse value failed $value", e)
msgIfBlank
}
else -> msgIfBlank
}
}
companion object {
private val LOG = LoggerFactory.getLogger(TaskFieldFormatter::class.java)
private val _instance = TaskFieldFormatter()
fun instance(): TaskFieldFormatter = _instance
}
}
| agpl-3.0 | 3a2ea675fe6267d824272b8c65b509aa | 50.666667 | 128 | 0.73871 | 4.254902 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/main/java/androidx/core/os/Bundle.kt | 1 | 4208 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.os
import android.os.Binder
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.util.Size
import android.util.SizeF
import java.io.Serializable
/**
* Returns a new [Bundle] with the given key/value pairs as elements.
*
* @throws IllegalArgumentException When a value is not a supported type of [Bundle].
*/
fun bundleOf(vararg pairs: Pair<String, Any?>) = Bundle(pairs.size).apply {
for ((key, value) in pairs) {
when (value) {
null -> putString(key, null) // Any nullable type will suffice.
// Scalars
is Boolean -> putBoolean(key, value)
is Byte -> putByte(key, value)
is Char -> putChar(key, value)
is Double -> putDouble(key, value)
is Float -> putFloat(key, value)
is Int -> putInt(key, value)
is Long -> putLong(key, value)
is Short -> putShort(key, value)
// References
is Bundle -> putBundle(key, value)
is CharSequence -> putCharSequence(key, value)
is Parcelable -> putParcelable(key, value)
// Scalar arrays
is BooleanArray -> putBooleanArray(key, value)
is ByteArray -> putByteArray(key, value)
is CharArray -> putCharArray(key, value)
is DoubleArray -> putDoubleArray(key, value)
is FloatArray -> putFloatArray(key, value)
is IntArray -> putIntArray(key, value)
is LongArray -> putLongArray(key, value)
is ShortArray -> putShortArray(key, value)
// Reference arrays
is Array<*> -> {
val componentType = value::class.java.componentType
@Suppress("UNCHECKED_CAST") // Checked by reflection.
when {
Parcelable::class.java.isAssignableFrom(componentType) -> {
putParcelableArray(key, value as Array<Parcelable>)
}
String::class.java.isAssignableFrom(componentType) -> {
putStringArray(key, value as Array<String>)
}
CharSequence::class.java.isAssignableFrom(componentType) -> {
putCharSequenceArray(key, value as Array<CharSequence>)
}
Serializable::class.java.isAssignableFrom(componentType) -> {
putSerializable(key, value)
}
else -> {
val valueType = componentType.canonicalName
throw IllegalArgumentException(
"Illegal value array type $valueType for key \"$key\"")
}
}
}
// Last resort. Also we must check this after Array<*> as all arrays are serializable.
is Serializable -> putSerializable(key, value)
else -> {
if (Build.VERSION.SDK_INT >= 18 && value is Binder) {
putBinder(key, value)
} else if (Build.VERSION.SDK_INT >= 21 && value is Size) {
putSize(key, value)
} else if (Build.VERSION.SDK_INT >= 21 && value is SizeF) {
putSizeF(key, value)
} else {
val valueType = value.javaClass.canonicalName
throw IllegalArgumentException("Illegal value type $valueType for key \"$key\"")
}
}
}
}
}
| apache-2.0 | 97efe158ff6221511ee3fefd3ce29978 | 39.461538 | 100 | 0.563688 | 4.997625 | false | false | false | false |
MaTriXy/gradle-play-publisher-1 | play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/InstallInternalSharingArtifact.kt | 1 | 5393 | package com.github.triplet.gradle.play.tasks
import com.android.build.gradle.AppExtension
import com.android.build.gradle.internal.LoggerWrapper
import com.android.build.gradle.internal.testing.ConnectedDeviceProvider
import com.android.builder.testing.api.DeviceProvider
import com.android.ddmlib.MultiLineReceiver
import com.google.api.client.json.jackson2.JacksonFactory
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.logging.Logging
import org.gradle.api.provider.Property
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.submit
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
internal abstract class InstallInternalSharingArtifact @Inject constructor(
private val extension: AppExtension
) : DefaultTask() {
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputDirectory
abstract val uploadedArtifacts: DirectoryProperty
init {
// Always out-of-date since we don't know anything about the target device
outputs.upToDateWhen { false }
}
@TaskAction
fun install() {
val uploads = uploadedArtifacts
project.serviceOf<WorkerExecutor>().noIsolation().submit(Installer::class) {
uploadedArtifacts.set(uploads)
adbExecutable.set(extension.adbExecutable)
timeOutInMs.set(extension.adbOptions.timeOutInMs)
}
}
abstract class Installer : WorkAction<Installer.Params> {
override fun execute() {
val uploads = parameters.uploadedArtifacts.get().asFileTree
val latestUpload = checkNotNull(
uploads.maxBy { it.nameWithoutExtension.toLong() }
) { "Failed to find uploaded artifacts in ${uploads.joinToString()}" }
val launchUrl = latestUpload.inputStream().use {
JacksonFactory.getDefaultInstance().createJsonParser(it).parse(Map::class.java)
}["downloadUrl"] as String
val shell = AdbShell(
parameters.adbExecutable.get().asFile, parameters.timeOutInMs.get())
val result = shell.executeShellCommand(
"am start -a \"android.intent.action.VIEW\" -d $launchUrl")
check(result) {
"Failed to install on any devices."
}
}
interface Params : WorkParameters {
val uploadedArtifacts: DirectoryProperty
val adbExecutable: RegularFileProperty
val timeOutInMs: Property<Int>
}
}
interface AdbShell {
fun executeShellCommand(command: String): Boolean
interface Factory {
fun create(adbExecutable: File, timeOutInMs: Int): AdbShell
}
companion object {
private var factory: Factory = DefaultAdbShell
internal fun setFactory(factory: Factory) {
Companion.factory = factory
}
operator fun invoke(
adbExecutable: File,
timeOutInMs: Int
): AdbShell = factory.create(adbExecutable, timeOutInMs)
}
}
private class DefaultAdbShell(
private val deviceProvider: DeviceProvider,
private val timeOutInMs: Long
) : AdbShell {
override fun executeShellCommand(command: String): Boolean {
return deviceProvider.use {
launchIntents(deviceProvider, command)
}
}
private fun launchIntents(deviceProvider: DeviceProvider, command: String): Boolean {
var successfulLaunches = 0
for (device in deviceProvider.devices) {
val receiver = object : MultiLineReceiver() {
private var _hasErrored = false
val hasErrored get() = _hasErrored
override fun processNewLines(lines: Array<out String>) {
if (lines.any { it.contains("error", true) }) {
_hasErrored = true
}
}
override fun isCancelled() = false
}
device.executeShellCommand(
command,
receiver,
timeOutInMs,
TimeUnit.MILLISECONDS
)
if (!receiver.hasErrored) successfulLaunches++
}
return successfulLaunches > 0
}
companion object : AdbShell.Factory {
override fun create(adbExecutable: File, timeOutInMs: Int): AdbShell {
val deviceProvider = ConnectedDeviceProvider(
adbExecutable,
timeOutInMs,
LoggerWrapper(Logging.getLogger(
InstallInternalSharingArtifact::class.java))
)
return DefaultAdbShell(deviceProvider, timeOutInMs.toLong())
}
}
}
}
| mit | a280e3eb68a16d71a109a6b425f7cf75 | 35.687075 | 95 | 0.617838 | 5.230844 | false | false | false | false |
Goyatuzo/LurkerBot | plyd/plyd-core/src/test/kotlin/com/lurkerbot/core/gameTime/TimerServiceTest.kt | 1 | 7177 | package com.lurkerbot.core.gameTime
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.google.common.truth.Truth.assertThat
import com.lurkerbot.core.currentlyPlaying.CurrentlyPlaying
import com.lurkerbot.core.currentlyPlaying.CurrentlyPlayingService
import com.lurkerbot.core.error.*
import io.mockk.*
import java.time.LocalDateTime
import org.junit.After
import org.junit.Test
class TimerServiceTest {
private val serverId = "test server"
private val timerRepository = mockk<TimerRepository>()
private val currentlyPlayingService = mockk<CurrentlyPlayingService>()
private val gameTimer = TimerService(timerRepository, currentlyPlayingService)
private val basicTimeRecord =
TimeRecord(
sessionBegin = LocalDateTime.now(),
sessionEnd = LocalDateTime.now(),
gameName = "game",
userId = "test",
gameDetail = "Detail",
gameState = "State",
largeAssetText = "",
smallAssetText = ""
)
@After
fun teardown() {
clearMocks(timerRepository)
clearMocks(currentlyPlayingService)
}
private fun setupCurrentlyPlayingService(currentlyPlaying: CurrentlyPlaying) {
every {
currentlyPlayingService.isUserCurrentlyPlayingById(currentlyPlaying.userId)
} returns true
every { currentlyPlayingService.getByUserId(currentlyPlaying.userId) } returns
Ok(currentlyPlaying)
every { currentlyPlayingService.removeByUserId(currentlyPlaying.userId) } returns Unit
}
@Test
fun `A person can start playing a game and an hour later, successfully ends logging`() {
val later = LocalDateTime.now().plusHours(1)
val toInsert = basicTimeRecord.copy()
val toPlaying = CurrentlyPlaying.from(toInsert, serverId)
setupCurrentlyPlayingService(toPlaying)
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, toInsert)
val actual = gameTimer.endLogging("test", serverId, later)
assertThat(actual).isEqualTo(Ok(Unit))
verify(exactly = 1) { timerRepository.saveTimeRecord(toInsert.copy(sessionEnd = later)) }
confirmVerified(timerRepository)
}
@Test
fun `When duplicate user and game beings logging, error is returned`() {
val toInsert = basicTimeRecord.copy()
val secondGame = basicTimeRecord.copy(gameState = "Updated State")
val toPlaying = CurrentlyPlaying.from(toInsert, serverId)
setupCurrentlyPlayingService(toPlaying)
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, toInsert)
val error = gameTimer.beginLogging("test", serverId, secondGame)
assertThat(error).isEqualTo(Err(GameIsAlreadyLogging("test", secondGame)))
}
@Test
fun `When two servers start logging for same user, only the first is added`() {
val firstToInsert = basicTimeRecord.copy()
val fakeTime = LocalDateTime.of(2020, 1, 1, 1, 0, 0)
val secondToInsert = basicTimeRecord.copy(sessionBegin = fakeTime)
val toPlayingFirst = CurrentlyPlaying.from(firstToInsert, serverId)
val toPlayingSecond = CurrentlyPlaying.from(secondToInsert, serverId)
setupCurrentlyPlayingService(toPlayingFirst)
setupCurrentlyPlayingService(toPlayingSecond)
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, firstToInsert)
val error = gameTimer.beginLogging("test", "test server 2", secondToInsert)
assertThat(error).isEqualTo(Err(GameIsAlreadyLogging("test", secondToInsert)))
}
@Test
fun `When two servers start logging for same user and ends, only the first is saved to database`() {
val firstToInsert = basicTimeRecord.copy()
val later = LocalDateTime.now().plusHours(1)
val fakeTime = LocalDateTime.of(2020, 1, 1, 1, 0, 0)
val secondToInsert = basicTimeRecord.copy(sessionBegin = fakeTime)
val toPlayingFirst = CurrentlyPlaying.from(firstToInsert, serverId)
val toPlayingSecond = CurrentlyPlaying.from(secondToInsert, serverId)
setupCurrentlyPlayingService(toPlayingFirst)
setupCurrentlyPlayingService(toPlayingSecond)
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, firstToInsert)
gameTimer.beginLogging("test", "test server 2", secondToInsert)
gameTimer.endLogging("test", serverId, later)
gameTimer.endLogging("test", "test server 2", later)
verify(exactly = 1) {
timerRepository.saveTimeRecord(record = not(firstToInsert.copy(sessionEnd = later)))
timerRepository.saveTimeRecord(record = secondToInsert.copy(sessionEnd = later))
}
confirmVerified(timerRepository)
}
@Test
fun `Should not be be able to save logging that never started`() {
every { timerRepository.saveTimeRecord(any()) } returns Unit
every { currentlyPlayingService.getByUserId(any()) } returns
Err(NeverStartedPlaying("test"))
val actual =
gameTimer.endLogging(
"test",
serverId,
)
assertThat(actual).isEqualTo(Err(NeverStartedPlaying("test")))
verify { timerRepository wasNot Called }
confirmVerified(timerRepository)
}
@Test
fun `When logging ends, a new one should be able to start`() {
val now = LocalDateTime.now().plusHours(1)
val toInsert = basicTimeRecord.copy()
val toPlaying = CurrentlyPlaying.from(toInsert, serverId)
every { currentlyPlayingService.isUserCurrentlyPlayingById(toPlaying.userId) } returns
true andThen
false
every { currentlyPlayingService.getByUserId(toPlaying.userId) } returns Ok(toPlaying)
every { currentlyPlayingService.removeByUserId(toPlaying.userId) } returns Unit
every { currentlyPlayingService.save(any()) } returns Unit
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, toInsert)
gameTimer.endLogging("test", serverId, now)
val begin = gameTimer.beginLogging("test", serverId, toInsert)
assertThat(begin).isEqualTo(Ok(Unit))
}
@Test
fun `Playing a game for milliseconds is not valid`() {
val now = LocalDateTime.now()
val toInsert = basicTimeRecord.copy()
val toPlaying = CurrentlyPlaying.from(toInsert, serverId)
setupCurrentlyPlayingService(toPlaying)
every { timerRepository.saveTimeRecord(any()) } returns Unit
gameTimer.beginLogging("test", serverId, toInsert)
val actual = gameTimer.endLogging("test", serverId, now)
assertThat(actual)
.isEqualTo(Err(StateChangedTooFast("test", toInsert.copy(sessionEnd = now))))
verify { timerRepository wasNot called }
confirmVerified(timerRepository)
}
}
| apache-2.0 | 94cb93cf743505454d516b7b0fafaa8e | 38.005435 | 104 | 0.687056 | 4.75298 | false | true | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/book/PrefaceItemViewBinder.kt | 1 | 1549 | package com.orgzly.android.ui.notes.book
import android.content.Context
import android.graphics.Typeface
import android.view.View
import com.orgzly.R
import com.orgzly.android.App
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.usecase.BookUpdatePreface
import com.orgzly.android.usecase.UseCaseRunner
class PrefaceItemViewBinder(private val context: Context) {
fun bind(holder: BookAdapter.PrefaceViewHolder, bookId: Long, preface: String?, isPrefaceDisplayed: Boolean) {
holder.binding.itemPrefaceText.apply {
if (!isPrefaceDisplayed) {
visibility = View.GONE
return
}
if (context.getString(R.string.pref_value_preface_in_book_few_lines) == AppPreferences.prefaceDisplay(context)) {
setMaxLines(3)
} else {
setMaxLines(Integer.MAX_VALUE)
}
if (preface != null) {
if (AppPreferences.isFontMonospaced(context)) {
setTypeface(Typeface.MONOSPACE)
}
setSourceText(preface)
/* If content changes (for example by toggling the checkbox), update the note. */
setOnUserTextChangeListener { text ->
val useCase = BookUpdatePreface(bookId, text)
App.EXECUTORS.diskIO().execute {
UseCaseRunner.run(useCase)
}
}
}
visibility = View.VISIBLE
}
}
} | gpl-3.0 | 99f2c4849fd44a997ccca92f72cf2dc7 | 33.444444 | 125 | 0.597805 | 4.722561 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/twitter/TwitterTimelineFragment.kt | 1 | 2718 | package com.openconference.twitter
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import android.widget.TextView
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateFragment
import com.openconference.R
import com.openconference.model.Speaker
import com.openconference.util.findView
import com.openconference.util.lce.LceAnimatable
import com.openconference.util.lce.LceViewState
import com.twitter.sdk.android.core.models.Tweet
import com.twitter.sdk.android.tweetui.Timeline
import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter
/**
* Displays a list of tweets
*
* @author Hannes Dorfmann
*/
@FragmentWithArgs
class TwitterTimelineFragment : TwitterTimelineView, LceAnimatable<Int>, MvpViewStateFragment<TwitterTimelineView, TwitterTimelinePresenter>() {
override lateinit var content_view: View
override lateinit var errorView: TextView
override lateinit var loadingView: View
override lateinit var emptyView: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_twitter_timeline,
container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
content_view = view.findView(R.id.contentView)
errorView = view.findView(R.id.errorView)
loadingView = view.findView(R.id.loadingView)
emptyView = view.findView(R.id.emptyView)
errorView.setOnClickListener { loadData() }
super.onViewCreated(view, savedInstanceState)
}
override fun setTimeline(timeline: Timeline<Tweet>) {
(content_view as ListView).adapter = TweetTimelineListAdapter.Builder(activity).setTimeline(
timeline).build()
}
override fun showLoading() {
super.showLoading()
}
override fun showError(@StringRes errorRes: Int) {
super.showError(errorRes)
}
override fun showContent(data: Int) {
super.showContent(data)
}
override fun isDataEmpty(data: Int): Boolean = false // Not needed here
private inline fun loadData() = presenter.loadNextTweets()
override fun onNewViewStateInstance() = loadData()
override
fun createViewState(): LceViewState<List<Speaker>> = LceViewState()
override fun getViewState(): LceViewState<Int>? = super.getViewState() as LceViewState<Int>?
override fun createPresenter(): TwitterTimelinePresenter = TwitterTimelinePresenter()
} | apache-2.0 | a9c1e7e15b994a597d3dfea8df3ca367 | 30.988235 | 144 | 0.782193 | 4.53 | false | false | false | false |
Stargamers/FastHub | app/src/main/java/com/fastaccess/ui/modules/repos/extras/locking/LockIssuePrBottomSheetDialog.kt | 4 | 1324 | package com.fastaccess.ui.modules.repos.extras.locking
import android.content.Context
import android.os.Bundle
import android.view.View
import com.fastaccess.R
import com.fastaccess.ui.base.BaseBottomSheetDialog
import kotlinx.android.synthetic.main.lock_issue_pr_dialog.*
/**
* Created by Kosh on 10.02.18.
*/
class LockIssuePrBottomSheetDialog : BaseBottomSheetDialog() {
private var lockIssuePrCallback: LockIssuePrCallback? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
lockIssuePrCallback = when {
parentFragment is LockIssuePrCallback -> parentFragment as LockIssuePrCallback
context is LockIssuePrCallback -> context
else -> null
}
}
override fun onDetach() {
lockIssuePrCallback = null
super.onDetach()
}
override fun layoutRes(): Int = R.layout.lock_issue_pr_dialog
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
cancel.setOnClickListener { dismiss() }
ok.setOnClickListener {
lockIssuePrCallback?.onLock(lockReason.selectedItem as String)
dismiss()
}
}
companion object {
fun newInstance() = LockIssuePrBottomSheetDialog()
}
} | gpl-3.0 | 2220f749e105a3998cc3397d2137e68a | 27.804348 | 90 | 0.691843 | 4.581315 | false | false | false | false |
VerifAPS/verifaps-lib | geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/print/DSLTablePrinter.kt | 1 | 6070 | package edu.kit.iti.formal.automation.testtables.print
import edu.kit.iti.formal.automation.st.StructuredTextPrinter
import edu.kit.iti.formal.automation.st.ast.FunctionDeclaration
import edu.kit.iti.formal.automation.testtables.model.*
import edu.kit.iti.formal.automation.testtables.rtt.pauseVariableTT
import edu.kit.iti.formal.automation.testtables.rtt.resetVariableTT
import edu.kit.iti.formal.automation.testtables.rtt.setVariableTT
import edu.kit.iti.formal.smv.SMVTypes
import edu.kit.iti.formal.smv.ast.SLiteral
import edu.kit.iti.formal.smv.ast.SVariable
import edu.kit.iti.formal.smv.conjunction
import edu.kit.iti.formal.util.CodeWriter
/**
*
* @author Alexander Weigl
* @version 1 (13.07.18)
*/
class DSLTablePrinter(val stream: CodeWriter) {
lateinit var gtt: GeneralizedTestTable
//lateinit var controlFields: List<String>
fun print(gtt: GeneralizedTestTable) {
this.gtt = gtt
/*controlFields = gtt.programRuns.map { pauseVariableTT(it) } +
gtt.chapterMarksForProgramRuns.flatMap { (run, rows) ->
rows.map { setVariableTT(it, gtt.programRuns[run]) }
} +
gtt.chapterMarksForProgramRuns.flatMap { (run, rows) ->
rows.map { resetVariableTT(it, gtt.programRuns[run]) }
}*/
stream.printf("table ${gtt.name} {")
stream.increaseIndent()
gtt.programVariables.forEach(this::print)
stream.nl()
gtt.constraintVariables.forEach(this::print)
stream.nl()
print(gtt.properties)
stream.nl()
print(gtt.region)
stream.nl()
gtt.functions.forEach(this::print)
stream.decreaseIndent().nl().printf("}")
}
fun print(v: ColumnVariable) {
if (v is ProgramVariable) print(v)
if (v is ProjectionVariable) print(v)
}
fun print(v: ProjectionVariable) {
if (v.category == ColumnCategory.ASSUME)
stream.print("assume ")
else
stream.print("assert ")
}
fun print(v: ProgramVariable) {
stream.nl().printf("column ")
if (v.isState) {
stream.print("state ")
if (v.category == ColumnCategory.ASSUME)
stream.print("assume ")
else
stream.print("assert ")
if (v.isNext)
stream.print("next")
} else {
if (v.category == ColumnCategory.ASSERT)
if (v.isNext)
stream.print("output ")
else
stream.print("assert ")
else
if (v.isNext)
stream.print("assume next")
else
stream.print("input")
}
if (v.realName == v.name) {
stream.printf(v.name).printf(" : ").print(v.dataType)
} else {
stream.printf(v.realName).printf(" : ").print(v.dataType).printf(" as ")
.printf(v.name)
}
}
fun print(v: ConstraintVariable) {
stream.nl().printf("gvar ").printf(v.name).printf(" : ").print(v.dataType)
if (v.constraint != null) {
stream.printf(" with ").printf(v.constraint!!.text)
}
}
fun print(p: MutableMap<String, String>) {
if (p.isEmpty()) return
stream.nl().printf("options {").increaseIndent()
p.forEach { t, u ->
stream.nl().printf("$t = $u")
}
stream.nl().decreaseIndent().printf("}")
}
fun print(r: TableNode) {
stream.nl()
when (r) {
is Region -> {
stream.printf("group ${r.id} ")
print(r.duration)
stream.printf(" {").increaseIndent()
r.children.forEach { print(it) }
stream.decreaseIndent().nl().printf("}")
}
is TableRow -> {
stream.printf("row ${r.id} ")
print(r.duration)
stream.printf("{").increaseIndent()
val play = (gtt.programRuns.indices) - r.pauseProgramRuns
stream.nl().printf("\\play: %s", play.joinToString(", "))
if (r.pauseProgramRuns.isNotEmpty())
stream.nl().printf("\\pause: %s", r.pauseProgramRuns.joinToString(", "))
r.controlCommands.filterIsInstance<ControlCommand.Backward>()
.forEach {
stream.nl().printf("\\backward(%s): %s", it.jumpToRow, it.affectedProgramRun)
}
/*controlFields.forEach { it ->
stream.nl().printf("// $it: ${r.inputExpr[it]?.repr()}")
}*/
gtt.programVariables.forEach {
val raw = r.rawFields[it]
val smvName = it.internalVariable(gtt.programRuns).name
val unfolded = r.inputExpr[smvName]?.repr() ?: r.outputExpr[smvName]?.repr() ?: ""
val name = when (it) {
is ProgramVariable -> "${gtt.programRuns[it.programRun]}::${it.name}"
else -> it.name
}
stream.nl().printf("$name: ${raw?.text} //$unfolded")
}
val input = r.inputExpr.values.conjunction(SLiteral.TRUE)
val output = r.outputExpr.values.conjunction(SLiteral.TRUE)
stream.nl().printf("// input: ${input.repr()}")
stream.nl().printf("// output: ${output.repr()}")
stream.decreaseIndent().nl().printf("}")
}
}
}
fun print(d: Duration) = stream.write(when (d) {
is Duration.Omega -> "omega"
is Duration.ClosedInterval -> "[${d.lower}, ${d.upper}]" + d.modifier.repr()
is Duration.OpenInterval -> ">= ${d.lower}" + d.modifier.repr()
})
fun print(fs: FunctionDeclaration) {
val stp = StructuredTextPrinter()
stp.sb = stream
fs.accept(stp)
}
}
| gpl-3.0 | dc6c9b2f6d28e709b07b34121340f2e6 | 34.91716 | 105 | 0.533114 | 4.123641 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/categories/UploadCategoryAdapterDelegates.kt | 5 | 1514 | package fr.free.nrw.commons.upload.categories
import android.view.View
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
import fr.free.nrw.commons.R
import fr.free.nrw.commons.category.CategoryItem
import fr.free.nrw.commons.databinding.LayoutUploadCategoriesItemBinding
fun uploadCategoryDelegate(onCategoryClicked: (CategoryItem) -> Unit) =
adapterDelegateViewBinding<CategoryItem, CategoryItem,
LayoutUploadCategoriesItemBinding>({ layoutInflater, root ->
LayoutUploadCategoriesItemBinding.inflate(layoutInflater, root, false)
}) {
val onClickListener = { _: View? ->
item.isSelected = !item.isSelected
binding.uploadCategoryCheckbox.isChecked = item.isSelected
onCategoryClicked(item)
}
binding.root.setOnClickListener(onClickListener)
binding.uploadCategoryCheckbox.setOnClickListener(onClickListener)
bind {
binding.uploadCategoryCheckbox.isChecked = item.isSelected
binding.categoryLabel.text = item.name
if(item.thumbnail != "null") {
binding.categoryImage.setImageURI(item.thumbnail)
} else {
binding.categoryImage.setActualImageResource(R.drawable.commons)
}
if(item.description != "null") {
binding.categoryDescription.text = item.description
} else {
binding.categoryDescription.text = ""
}
}
}
| apache-2.0 | dcbf1273ba44ae81f16854378df6389c | 38.842105 | 80 | 0.676354 | 5.080537 | false | false | false | false |
dreamkas/start-utils | versions-utils/src/main/java/ru/dreamkas/semver/prerelease/PreRelease.kt | 1 | 847 | package ru.dreamkas.semver.prerelease
import java.util.ArrayList
class PreRelease internal constructor(
val preRelease: String? = null
) {
val identifiers: List<PreReleaseId> = preRelease?.split(".")?.map {
it.toIntOrNull()?.let { number -> PreReleaseNumericId(number) } ?: PreReleaseStringId(it)
} ?: ArrayList()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as PreRelease
if (identifiers != other.identifiers) return false
return true
}
override fun hashCode(): Int {
return identifiers.hashCode()
}
override fun toString(): String {
return preRelease?.let { "-$preRelease" } ?: ""
}
companion object {
val EMPTY = PreRelease()
}
}
| mit | aa387becee1249e1c073676377c890f2 | 23.911765 | 97 | 0.622196 | 4.505319 | false | false | false | false |
square/kotlinpoet | kotlinpoet/src/main/java/com/squareup/kotlinpoet/NameAllocator.kt | 1 | 4847 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.kotlinpoet
import java.util.UUID
/**
* Assigns Kotlin identifier names to avoid collisions, keywords, and invalid characters. To use,
* first create an instance and allocate all of the names that you need. Typically this is a
* mix of user-supplied names and constants:
*
* ```kotlin
* val nameAllocator = NameAllocator()
* for (property in properties) {
* nameAllocator.newName(property.name, property)
* }
* nameAllocator.newName("sb", "string builder")
* ```
*
* Pass a unique tag object to each allocation. The tag scopes the name, and can be used to look up
* the allocated name later. Typically the tag is the object that is being named. In the above
* example we use `property` for the user-supplied property names, and `"string builder"` for our
* constant string builder.
*
* Once we've allocated names we can use them when generating code:
*
* ```kotlin
* val builder = FunSpec.builder("toString")
* .addModifiers(KModifier.OVERRIDE)
* .returns(String::class)
*
* builder.addStatement("val %N = %T()",
* nameAllocator.get("string builder"), StringBuilder::class)
*
* for (property in properties) {
* builder.addStatement("%N.append(%N)",
* nameAllocator.get("string builder"), nameAllocator.get(property))
* }
* builder.addStatement("return %N.toString()", nameAllocator.get("string builder"))
* return builder.build()
* ```
*
* The above code generates unique names if presented with conflicts. Given user-supplied properties
* with names `ab` and `sb` this generates the following:
*
* ```kotlin
* override fun toString(): kotlin.String {
* val sb_ = java.lang.StringBuilder()
* sb_.append(ab)
* sb_.append(sb)
* return sb_.toString()
* }
* ```
*
* The underscore is appended to `sb` to avoid conflicting with the user-supplied `sb` property.
* Underscores are also prefixed for names that start with a digit, and used to replace name-unsafe
* characters like space or dash.
*
* When dealing with multiple independent inner scopes, use a [copy][NameAllocator.copy] of the
* NameAllocator used for the outer scope to further refine name allocation for a specific inner
* scope.
*/
public class NameAllocator private constructor(
private val allocatedNames: MutableSet<String>,
private val tagToName: MutableMap<Any, String>,
) {
public constructor() : this(mutableSetOf(), mutableMapOf())
/**
* Return a new name using `suggestion` that will not be a Java identifier or clash with other
* names. The returned value can be queried multiple times by passing `tag` to
* [NameAllocator.get].
*/
@JvmOverloads public fun newName(
suggestion: String,
tag: Any = UUID.randomUUID().toString(),
): String {
var result = toJavaIdentifier(suggestion)
while (result.isKeyword || !allocatedNames.add(result)) {
result += "_"
}
val replaced = tagToName.put(tag, result)
if (replaced != null) {
tagToName[tag] = replaced // Put things back as they were!
throw IllegalArgumentException("tag $tag cannot be used for both '$replaced' and '$result'")
}
return result
}
/** Retrieve a name created with [NameAllocator.newName]. */
public operator fun get(tag: Any): String = requireNotNull(tagToName[tag]) { "unknown tag: $tag" }
/**
* Create a deep copy of this NameAllocator. Useful to create multiple independent refinements
* of a NameAllocator to be used in the respective definition of multiples, independently-scoped,
* inner code blocks.
*
* @return A deep copy of this NameAllocator.
*/
public fun copy(): NameAllocator {
return NameAllocator(allocatedNames.toMutableSet(), tagToName.toMutableMap())
}
}
private fun toJavaIdentifier(suggestion: String) = buildString {
var i = 0
while (i < suggestion.length) {
val codePoint = suggestion.codePointAt(i)
if (i == 0 &&
!Character.isJavaIdentifierStart(codePoint) &&
Character.isJavaIdentifierPart(codePoint)
) {
append("_")
}
val validCodePoint: Int = if (Character.isJavaIdentifierPart(codePoint)) {
codePoint
} else {
'_'.code
}
appendCodePoint(validCodePoint)
i += Character.charCount(codePoint)
}
}
| apache-2.0 | 3643d182ac93ef2e313bead494a4f112 | 33.870504 | 100 | 0.700021 | 4.139197 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/annotations/proxy/AnnotationProxyGenerator.kt | 1 | 16295 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.annotations.proxy
import io.michaelrocks.grip.ClassRegistry
import io.michaelrocks.grip.mirrors.ClassMirror
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getArrayType
import io.michaelrocks.grip.mirrors.getObjectType
import io.michaelrocks.grip.mirrors.isPrimitive
import io.michaelrocks.lightsaber.processor.commons.GeneratorAdapter
import io.michaelrocks.lightsaber.processor.commons.StandaloneClassWriter
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.descriptors.FieldDescriptor
import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor
import io.michaelrocks.lightsaber.processor.descriptors.descriptor
import io.michaelrocks.lightsaber.processor.watermark.WatermarkClassVisitor
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Label
import org.objectweb.asm.Opcodes.ACC_FINAL
import org.objectweb.asm.Opcodes.ACC_PRIVATE
import org.objectweb.asm.Opcodes.ACC_PUBLIC
import org.objectweb.asm.Opcodes.ACC_SUPER
import org.objectweb.asm.Opcodes.V1_6
import org.objectweb.asm.commons.GeneratorAdapter.ADD
import org.objectweb.asm.commons.GeneratorAdapter.EQ
import org.objectweb.asm.commons.GeneratorAdapter.MUL
import org.objectweb.asm.commons.GeneratorAdapter.NE
import org.objectweb.asm.commons.GeneratorAdapter.XOR
import java.util.Arrays
class AnnotationProxyGenerator(
private val classRegistry: ClassRegistry,
private val annotation: ClassMirror,
private val proxyType: Type
) {
companion object {
private val ARRAYS_TYPE = getObjectType<Arrays>()
private val OBJECT_ARRAY_TYPE = getArrayType<Array<Any>>()
private val STRING_BUILDER_TYPE = getObjectType<StringBuilder>()
private val HASH_CODE_METHOD = MethodDescriptor.forMethod("hashCode", Type.Primitive.Int)
private val EQUALS_METHOD = MethodDescriptor.forMethod("equals", Type.Primitive.Boolean, Types.OBJECT_TYPE)
private val TO_STRING_METHOD = MethodDescriptor.forMethod("toString", Types.STRING_TYPE)
private val FLOAT_TO_INT_BITS_METHOD =
MethodDescriptor.forMethod("floatToIntBits", Type.Primitive.Int, Type.Primitive.Float)
private val DOUBLE_TO_LONG_BITS_METHOD =
MethodDescriptor.forMethod("doubleToLongBits", Type.Primitive.Long, Type.Primitive.Double)
private val ANNOTATION_TYPE_METHOD = MethodDescriptor.forMethod("annotationType", Types.CLASS_TYPE)
private val CACHED_HASH_CODE_FIELD = FieldDescriptor("\$cachedHashCode", Types.BOXED_INT_TYPE)
private val CACHED_TO_STRING_FIELD = FieldDescriptor("\$cachedToString", Types.STRING_TYPE)
private val STRING_BUILDER_APPEND_METHOD_RESOLVER = StringBuilderAppendMethodResolver()
}
fun generate(): ByteArray {
val classWriter = StandaloneClassWriter(ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES, classRegistry)
val classVisitor = WatermarkClassVisitor(classWriter, true)
classVisitor.visit(
V1_6,
ACC_PUBLIC or ACC_SUPER,
proxyType.internalName,
null,
Types.OBJECT_TYPE.internalName,
arrayOf(annotation.type.internalName)
)
generateFields(classVisitor)
generateConstructor(classVisitor)
generateEqualsMethod(classVisitor)
generateHashCodeMethod(classVisitor)
generateToStringMethod(classVisitor)
generateAnnotationTypeMethod(classVisitor)
generateGetters(classVisitor)
classVisitor.visitEnd()
return classWriter.toByteArray()
}
private fun generateFields(classVisitor: ClassVisitor) {
for (method in annotation.methods) {
val fieldVisitor = classVisitor.visitField(
ACC_PRIVATE or ACC_FINAL,
method.name,
method.type.returnType.descriptor,
null,
null
)
fieldVisitor.visitEnd()
}
val cachedHashCodeField = classVisitor.visitField(
ACC_PRIVATE,
CACHED_HASH_CODE_FIELD.name,
CACHED_HASH_CODE_FIELD.descriptor,
null,
null
)
cachedHashCodeField.visitEnd()
val cachedToStringField = classVisitor.visitField(
ACC_PRIVATE,
CACHED_TO_STRING_FIELD.name,
CACHED_TO_STRING_FIELD.descriptor,
null,
null
)
cachedToStringField.visitEnd()
}
private fun generateConstructor(classVisitor: ClassVisitor) {
val fieldTypes = annotation.methods.map { it.type.returnType }
val argumentTypes = fieldTypes.toTypedArray()
val constructor = MethodDescriptor.forConstructor(*argumentTypes)
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, constructor)
generator.visitCode()
// Call the constructor of the super class.
generator.loadThis()
generator.invokeConstructor(Types.OBJECT_TYPE, MethodDescriptor.forDefaultConstructor())
// Initialize fields with arguments passed to the constructor.
annotation.methods.forEachIndexed { localPosition, method ->
generator.loadThis()
generator.loadArg(localPosition)
generator.putField(proxyType, method.name, method.type.returnType)
}
generator.returnValue()
generator.endMethod()
}
private fun generateEqualsMethod(classVisitor: ClassVisitor) {
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, EQUALS_METHOD)
generator.visitCode()
// if (this == object) return true;
generator.loadThis()
generator.loadArg(0)
val referencesNotEqualLabel = generator.newLabel()
generator.ifCmp(Types.OBJECT_TYPE, NE, referencesNotEqualLabel)
generator.push(true)
generator.returnValue()
generator.visitLabel(referencesNotEqualLabel)
// if (!(object instanceof *AnnotationType*)) return false;
generator.loadArg(0)
generator.instanceOf(annotation.type)
val objectHasSameTypeLabel = generator.newLabel()
generator.ifZCmp(NE, objectHasSameTypeLabel)
generator.push(false)
generator.returnValue()
generator.visitLabel(objectHasSameTypeLabel)
// Cast the object to *AnnotationType*.
val annotationLocal = generator.newLocal(annotation.type)
generator.loadArg(0)
generator.checkCast(annotation.type)
generator.storeLocal(annotationLocal)
val fieldsNotEqualLabel = generator.newLabel()
for (method in annotation.methods) {
generateEqualsInvocationForField(
generator, method.name, method.type.returnType, annotationLocal, fieldsNotEqualLabel
)
}
generator.push(true)
val returnLabel = generator.newLabel()
generator.goTo(returnLabel)
generator.visitLabel(fieldsNotEqualLabel)
generator.push(false)
generator.visitLabel(returnLabel)
generator.returnValue()
generator.endMethod()
}
private fun generateEqualsInvocationForField(
generator: GeneratorAdapter,
fieldName: String,
fieldType: Type,
annotationLocal: Int,
fieldsNotEqualLabel: Label
) {
val fieldAccessor = MethodDescriptor.forMethod(fieldName, fieldType)
generator.loadThis()
generator.invokeVirtual(proxyType, fieldAccessor)
convertFieldValue(generator, fieldType)
generator.loadLocal(annotationLocal)
generator.invokeInterface(annotation.type, fieldAccessor)
convertFieldValue(generator, fieldType)
if (fieldType is Type.Array) {
// Call Arrays.equals() with a corresponding signature.
val elementType = fieldType.elementType
val argumentType = if (elementType.isPrimitive) fieldType else OBJECT_ARRAY_TYPE
val equalsMethod =
MethodDescriptor.forMethod(EQUALS_METHOD.name, Type.Primitive.Boolean, argumentType, argumentType)
generator.invokeStatic(ARRAYS_TYPE, equalsMethod)
generator.ifZCmp(EQ, fieldsNotEqualLabel)
} else if (fieldType is Type.Primitive) {
when (fieldType) {
Type.Primitive.Double, Type.Primitive.Long -> generator.ifCmp(Type.Primitive.Long, NE, fieldsNotEqualLabel)
else -> generator.ifICmp(NE, fieldsNotEqualLabel)
}
} else {
// Call equals() on the instances on the stack.
generator.invokeVirtual(Types.OBJECT_TYPE, EQUALS_METHOD)
generator.ifZCmp(EQ, fieldsNotEqualLabel)
}
}
private fun convertFieldValue(generator: GeneratorAdapter, fieldType: Type) {
when (fieldType) {
is Type.Primitive.Float -> generator.invokeStatic(Types.BOXED_FLOAT_TYPE, FLOAT_TO_INT_BITS_METHOD)
is Type.Primitive.Double -> generator.invokeStatic(Types.BOXED_DOUBLE_TYPE, DOUBLE_TO_LONG_BITS_METHOD)
}
}
private fun generateHashCodeMethod(classVisitor: ClassVisitor) {
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, HASH_CODE_METHOD)
generator.visitCode()
val cacheHashCodeIsNullLabel = generator.newLabel()
generator.loadThis()
generator.getField(proxyType, CACHED_HASH_CODE_FIELD)
generator.dup()
generator.ifNull(cacheHashCodeIsNullLabel)
generator.unbox(Type.Primitive.Int)
generator.returnValue()
generator.visitLabel(cacheHashCodeIsNullLabel)
generator.push(0)
for (method in annotation.methods) {
// Hash code for annotation is the sum of 127 * name.hashCode() ^ value.hashCode().
generateHashCodeComputationForField(generator, method.name, method.type.returnType)
generator.math(ADD, Type.Primitive.Int)
}
generator.dup()
generator.valueOf(Type.Primitive.Int)
generator.loadThis()
generator.swap(Type.Primitive.Int, proxyType)
generator.putField(proxyType, CACHED_HASH_CODE_FIELD)
generator.returnValue()
generator.endMethod()
}
private fun generateHashCodeComputationForField(generator: GeneratorAdapter, fieldName: String, fieldType: Type) {
// Compute hash code of the field name.
generator.push(fieldName)
generator.invokeVirtual(Types.STRING_TYPE, HASH_CODE_METHOD)
// Multiple it by 127.
generator.push(127)
generator.math(MUL, Type.Primitive.Int)
// Load field value on the stack.
generator.loadThis()
val fieldAccessor = MethodDescriptor.forMethod(fieldName, fieldType)
generator.invokeVirtual(proxyType, fieldAccessor)
if (fieldType is Type.Array) {
// Call Arrays.hashCode() with a corresponding signature.
val elementType = fieldType.elementType
val argumentType = if (elementType.isPrimitive) fieldType else OBJECT_ARRAY_TYPE
val hashCodeMethod = MethodDescriptor.forMethod(HASH_CODE_METHOD.name, Type.Primitive.Int, argumentType)
generator.invokeStatic(ARRAYS_TYPE, hashCodeMethod)
} else {
// If the field has primitive type then box it.
generator.valueOf(fieldType)
// Call hashCode() on the instance on the stack.
generator.invokeVirtual(Types.OBJECT_TYPE, HASH_CODE_METHOD)
}
// Xor the field name and the field value hash codes.
generator.math(XOR, Type.Primitive.Int)
}
private fun generateToStringMethod(classVisitor: ClassVisitor) {
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, TO_STRING_METHOD)
generator.visitCode()
val cachedToStringIsNullLabel = generator.newLabel()
generator.loadThis()
generator.getField(proxyType, CACHED_TO_STRING_FIELD)
generator.dup()
generator.ifNull(cachedToStringIsNullLabel)
generator.returnValue()
generator.visitLabel(cachedToStringIsNullLabel)
generator.newInstance(STRING_BUILDER_TYPE)
generator.dup()
generator.invokeConstructor(STRING_BUILDER_TYPE, MethodDescriptor.forDefaultConstructor())
generator.push("@" + annotation.type.className + "(")
generateStringBuilderAppendInvocation(generator, Types.STRING_TYPE)
var addComma = false
for (method in annotation.methods) {
appendFieldName(generator, method.name, addComma)
appendFieldValue(generator, method.name, method.type.returnType)
addComma = true
}
generator.push(')'.toInt())
generateStringBuilderAppendInvocation(generator, Type.Primitive.Char)
generator.invokeVirtual(STRING_BUILDER_TYPE, TO_STRING_METHOD)
generator.dup()
generator.loadThis()
generator.swap()
generator.putField(proxyType, CACHED_TO_STRING_FIELD)
generator.returnValue()
generator.endMethod()
}
private fun appendFieldName(generator: GeneratorAdapter, fieldName: String, addComma: Boolean) {
val prefix = if (addComma) ", " else ""
generator.push("$prefix$fieldName=")
generateStringBuilderAppendInvocation(generator, Types.STRING_TYPE)
}
private fun appendFieldValue(generator: GeneratorAdapter, fieldName: String, fieldType: Type) {
generator.loadThis()
generator.getField(proxyType, fieldName, fieldType)
if (fieldType is Type.Array) {
generateArraysToStringInvocation(generator, fieldType)
generateStringBuilderAppendInvocation(generator, Types.STRING_TYPE)
} else {
generateStringBuilderAppendInvocation(generator, fieldType)
}
}
private fun generateArraysToStringInvocation(generator: GeneratorAdapter, fieldType: Type.Array) {
val elementType = fieldType.elementType
val argumentType = if (elementType.isPrimitive) fieldType else OBJECT_ARRAY_TYPE
val toStringMethod = MethodDescriptor.forMethod(TO_STRING_METHOD.name, Types.STRING_TYPE, argumentType)
generator.invokeStatic(ARRAYS_TYPE, toStringMethod)
}
private fun generateStringBuilderAppendInvocation(generator: GeneratorAdapter, parameterType: Type) {
val appendMethod = STRING_BUILDER_APPEND_METHOD_RESOLVER.resolveMethod(parameterType)
generator.invokeVirtual(STRING_BUILDER_TYPE, appendMethod)
}
private fun generateAnnotationTypeMethod(classVisitor: ClassVisitor) {
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, ANNOTATION_TYPE_METHOD)
generator.visitCode()
generator.push(annotation.type)
generator.returnValue()
generator.endMethod()
}
private fun generateGetters(classVisitor: ClassVisitor) {
for (method in annotation.methods) {
val generator = GeneratorAdapter(classVisitor, ACC_PUBLIC, MethodDescriptor(method.name, method.type))
generator.visitCode()
generator.loadThis()
generator.getField(proxyType, method.name, method.type.returnType)
generator.returnValue()
generator.endMethod()
}
}
private class StringBuilderAppendMethodResolver {
companion object {
private const val METHOD_NAME = "append"
private val BOOLEAN_METHOD = appendMethod(Type.Primitive.Boolean)
private val CHAR_METHOD = appendMethod(Type.Primitive.Char)
private val FLOAT_METHOD = appendMethod(Type.Primitive.Float)
private val DOUBLE_METHOD = appendMethod(Type.Primitive.Double)
private val INT_METHOD = appendMethod(Type.Primitive.Int)
private val LONG_METHOD = appendMethod(Type.Primitive.Long)
private val OBJECT_METHOD = appendMethod(Types.OBJECT_TYPE)
private val STRING_METHOD = appendMethod(Types.STRING_TYPE)
private fun appendMethod(parameterType: Type): MethodDescriptor {
return MethodDescriptor.forMethod(METHOD_NAME, STRING_BUILDER_TYPE, parameterType)
}
}
fun resolveMethod(type: Type): MethodDescriptor {
if (type is Type.Primitive) {
when (type) {
Type.Primitive.Boolean -> return BOOLEAN_METHOD
Type.Primitive.Char -> return CHAR_METHOD
Type.Primitive.Float -> return FLOAT_METHOD
Type.Primitive.Double -> return DOUBLE_METHOD
Type.Primitive.Byte, Type.Primitive.Short, Type.Primitive.Int -> return INT_METHOD
Type.Primitive.Long -> return LONG_METHOD
else -> error("Cannot append $type to StringBuilder")
}
} else {
return if (type == Types.STRING_TYPE) STRING_METHOD else OBJECT_METHOD
}
}
}
}
| apache-2.0 | f8fe7f038d8d5dcfa6d00057a5d548b7 | 37.522459 | 116 | 0.745996 | 4.426786 | false | false | false | false |
nt-ca-aqe/library-app | library-service/src/test/kotlin/utils/extensions/DockerizedDependencies.kt | 1 | 1914 | package utils.extensions
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy
import java.time.Duration
class MongoDbExtension : DockerizedDependencyExtension(
containerCreator = { MongoDbContainer() },
port = 27017,
portProperty = "MONGODB_PORT"
)
class RabbitMqExtension : DockerizedDependencyExtension(
containerCreator = { RabbitMqContainer() },
port = 5672,
portProperty = "RABBITMQ_PORT"
)
open class DockerizedDependencyExtension(
containerCreator: () -> Container,
private val port: Int,
private val portProperty: String
) : BeforeAllCallback, AfterAllCallback {
private val container = containerCreator()
override fun beforeAll(context: ExtensionContext) {
if (isTopClassContext(context) && !container.isRunning) {
container.start()
System.setProperty(portProperty, "${container.getMappedPort(port)}")
}
}
override fun afterAll(context: ExtensionContext) {
if (isTopClassContext(context) && container.isRunning) {
container.stop()
}
}
private fun isTopClassContext(context: ExtensionContext) = context.parent.orElse(null) == context.root
}
sealed class Container(image: String) : GenericContainer<Container>(image)
class MongoDbContainer : Container("mongo:3.5") {
init {
addExposedPort(27017)
}
}
class RabbitMqContainer : Container("rabbitmq:3.6") {
init {
setWaitStrategy(LogMessageWaitStrategy()
.withRegEx(".*Server startup complete.*\n")
.withStartupTimeout(Duration.ofSeconds(30)))
addExposedPort(5672)
}
} | apache-2.0 | c0aa63f05c4522e32e4a5baab44be14a | 29.887097 | 106 | 0.701149 | 4.379863 | false | false | false | false |
FurhatRobotics/example-skills | demo-skill/src/main/kotlin/furhatos/app/demo/flow/partials/functionalHandlers.kt | 1 | 2359 | package furhatos.app.demo.flow.partials
import furhatos.app.demo.flow.Active
import furhatos.app.demo.flow.Sleeping
import furhatos.app.demo.flow.snippetRunner
import furhatos.app.demo.nlu.ExitIntent
import furhatos.app.demo.nlu.NoIntent
import furhatos.app.demo.nlu.WakeupIntent
import furhatos.app.demo.personas.Persona
import furhatos.app.demo.personas.phrases
import furhatos.app.demo.util.AttendUsers
import furhatos.app.demo.util.ExitEvent
import furhatos.flow.kotlin.furhat
import furhatos.flow.kotlin.onResponse
import furhatos.flow.kotlin.partialState
import furhatos.flow.kotlin.raise
import furhatos.nlu.NullIntent
import furhatos.nlu.common.Greeting
import furhatos.nlu.common.RequestRepeat
import furhatos.nlu.common.Yes
import furhatos.snippets.SnippetFallbackTurn
val functionalHandlers = partialState {
onResponse<WakeupIntent> {
goto(Active())
}
onResponse<RequestRepeat> {
val stack = Persona.active.conversationStack
if (stack.isNotEmpty()) {
raise(it, stack.last())
}
furhat.listen()
}
onResponse({ snippetRunner.getUserIntents()}) {
if (it.intent == NullIntent) {
propagate()
} else {
call(SnippetFallbackTurn(snippetRunner, snippetRunner.respond(it.text, it.intent)))
furhat.say("So")
reentry()
}
}
onResponse(cond = { it.intent != NullIntent }){
// Save the intent in our conversation stack so that we can remember it
Persona.active.conversationStack.add(it.intent)
/*
Here we know that the user has performed a successful command,
so we want to open up for alterations in attention, to look at
other users aside from the closest one (our estimated confederate)
*/
send(AttendUsers(shouldAlterAttentionOnSpeech = true))
propagate()
}
onResponse<Yes> {
reentry()
}
onResponse<ExitIntent>(cond = { currentState != Sleeping }) {
raise(ExitEvent())
}
onResponse<NoIntent> {
raise(ExitEvent())
}
onEvent<ExitEvent> {
furhat.say {
+phrases.okay
+","
+phrases.goodbye
}
goto(Sleeping)
}
onResponse<Greeting> {
furhat.say(phrases.greeting)
reentry()
}
} | mit | b721b0e46b64be8a032b0834f68bd68d | 27.433735 | 95 | 0.661297 | 4.175221 | false | false | false | false |
Bombe/Sone | src/test/kotlin/net/pterodactylus/sone/web/pages/WebPageTest.kt | 1 | 9433 | package net.pterodactylus.sone.web.pages
import com.google.common.eventbus.*
import freenet.clients.http.*
import freenet.support.*
import freenet.support.api.*
import net.pterodactylus.sone.core.*
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.freenet.*
import net.pterodactylus.sone.freenet.wot.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.test.deepMock
import net.pterodactylus.sone.test.get
import net.pterodactylus.sone.test.mock
import net.pterodactylus.sone.test.whenever
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException
import net.pterodactylus.util.notify.*
import net.pterodactylus.util.template.*
import net.pterodactylus.util.web.*
import net.pterodactylus.util.web.Method.*
import org.junit.Assert.*
import org.mockito.ArgumentMatchers.*
import org.mockito.ArgumentMatchers.eq
import java.io.*
import java.net.*
import java.nio.charset.*
import java.util.*
import kotlin.text.Charsets.UTF_8
/**
* Base class for web page tests.
*/
open class WebPageTest(pageSupplier: (WebInterface, Loaders, TemplateRenderer) -> SoneTemplatePage = { _, _, _ -> mock() }) {
val currentSone = mock<Sone>()
val loaders = mock<Loaders>()
val templateRenderer = mock<TemplateRenderer>()
val webInterface = deepMock<WebInterface>()
val core = webInterface.core
val eventBus = mock<EventBus>()
val preferences = Preferences(eventBus)
open val page by lazy { pageSupplier(webInterface, loaders, templateRenderer) }
val httpRequest = mock<HTTPRequest>()
val freenetRequest = mock<FreenetRequest>()
init {
whenever(freenetRequest.uri).thenReturn(mock())
}
val soneRequest by lazy { freenetRequest.toSoneRequest(core, webInterface) }
val templateContext = TemplateContext()
val toadletContext = deepMock<ToadletContext>()
val responseContent = ByteArrayOutputStream()
val response = Response(responseContent)
private val requestHeaders = mutableMapOf<String, String>()
private val getRequestParameters = mutableMapOf<String, MutableList<String>>()
private val postRequestParameters = mutableMapOf<String, ByteArray>()
private val uploadedFileNames = mutableMapOf<String, String>()
private val uploadedFileContentTypes = mutableMapOf<String, String>()
private val uploadedFileResources = mutableMapOf<String, String>()
private val ownIdentities = mutableSetOf<OwnIdentity>()
private val allSones = mutableMapOf<String, Sone>()
private val localSones = mutableMapOf<String, Sone>()
private val allPosts = mutableMapOf<String, Post>()
private val allPostReplies = mutableMapOf<String, PostReply>()
private val perPostReplies = mutableMapOf<String, PostReply>()
private val allAlbums = mutableMapOf<String, Album>()
private val allImages = mutableMapOf<String, Image>()
private val notifications = mutableMapOf<String, Notification>()
private val translations = mutableMapOf<String, String>()
private val translation = object : Translation {
override val currentLocale = Locale.ENGLISH
override fun translate(key: String) = translations[key] ?: key
}
init {
setupCore()
setupWebInterface()
setupHttpRequest()
setupFreenetRequest()
}
private fun setupCore() {
whenever(core.preferences).thenReturn(preferences)
whenever(core.identityManager.allOwnIdentities).then { ownIdentities }
whenever(core.sones).then { allSones.values }
whenever(core.getSone(anyString())).then { allSones[it[0]] }
whenever(core.localSones).then { localSones.values }
whenever(core.getLocalSone(anyString())).then { localSones[it[0]] }
whenever(core.getPost(anyString())).then { allPosts[it[0]] }
whenever(core.getPostReply(anyString())).then { allPostReplies[it[0]] }
whenever(core.getReplies(anyString())).then { perPostReplies[it[0]].asList() }
whenever(core.getAlbum(anyString())).then { allAlbums[it[0]] }
whenever(core.getImage(anyString())).then { allImages[it[0]] }
whenever(core.getImage(anyString(), anyBoolean())).then { allImages[it[0]] }
whenever(core.getTemporaryImage(anyString())).thenReturn(null)
}
private fun setupWebInterface() {
whenever(webInterface.getCurrentSone(eq(toadletContext))).thenReturn(currentSone)
whenever(webInterface.getNotifications(currentSone)).then { notifications.values }
whenever(webInterface.getNotification(anyString())).then { notifications[it[0]].asOptional() }
whenever(webInterface.translation).thenReturn(translation)
}
private fun setupHttpRequest() {
whenever(httpRequest.method).thenReturn("GET")
whenever(httpRequest.getHeader(anyString())).then { requestHeaders[it.get<String>(0).toLowerCase()] }
whenever(httpRequest.hasParameters()).then { getRequestParameters.isNotEmpty() }
whenever(httpRequest.parameterNames).then { getRequestParameters.keys }
whenever(httpRequest.isParameterSet(anyString())).then { it[0] in getRequestParameters }
whenever(httpRequest.getParam(anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: "" }
whenever(httpRequest.getParam(anyString(), anyString())).then { getRequestParameters[it[0]]?.firstOrNull() ?: it[1] }
whenever(httpRequest.getIntParam(anyString())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: 0 }
whenever(httpRequest.getIntParam(anyString(), anyInt())).then { getRequestParameters[it[0]]?.first()?.toIntOrNull() ?: it[1] }
whenever(httpRequest.getLongParam(anyString(), anyLong())).then { getRequestParameters[it[0]]?.first()?.toLongOrNull() ?: it[1] }
whenever(httpRequest.getMultipleParam(anyString())).then { getRequestParameters[it[0]]?.toTypedArray() ?: emptyArray<String>() }
whenever(httpRequest.getMultipleIntParam(anyString())).then { getRequestParameters[it[0]]?.map { it.toIntOrNull() ?: 0 } ?: emptyArray<Int>() }
whenever(httpRequest.isPartSet(anyString())).then { it[0] in postRequestParameters }
whenever(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).then { postRequestParameters[it[0]]?.decode()?.take(it[1]) ?: "" }
whenever(httpRequest.getUploadedFile(anyString())).then {
it.get<String>(0).takeIf { it in uploadedFileNames }
?.let { name ->
UploadedFile(uploadedFileNames[name]!!, uploadedFileContentTypes[name]!!, uploadedFileResources[name]!!)
}
}
}
private class UploadedFile(private val filename: String, private val contentType: String, private val resourceName: String) : HTTPUploadedFile {
override fun getFilename() = filename
override fun getContentType() = contentType
override fun getData() = javaClass.getResourceAsStream(resourceName).readBytes().let(::SimpleReadOnlyArrayBucket)
}
private fun ByteArray.decode(charset: Charset = UTF_8) = String(this, charset)
private fun setupFreenetRequest() {
whenever(freenetRequest.method).thenReturn(GET)
whenever(freenetRequest.httpRequest).thenReturn(httpRequest)
whenever(freenetRequest.toadletContext).thenReturn(toadletContext)
}
fun setMethod(method: Method) {
whenever(httpRequest.method).thenReturn(method.name)
whenever(freenetRequest.method).thenReturn(method)
}
fun request(uri: String) {
whenever(httpRequest.path).thenReturn(uri)
whenever(freenetRequest.uri).thenReturn(URI(uri))
}
fun addHttpRequestHeader(name: String, value: String) {
requestHeaders[name.toLowerCase()] = value
}
fun addHttpRequestParameter(name: String, value: String) {
getRequestParameters[name] = getRequestParameters.getOrElse(name) { mutableListOf() }.apply { add(value) }
}
fun addHttpRequestPart(name: String, value: String) {
postRequestParameters[name] = value.toByteArray(UTF_8)
}
fun unsetCurrentSone() {
whenever(webInterface.getCurrentSone(eq(toadletContext))).thenReturn(null)
}
fun addOwnIdentity(ownIdentity: OwnIdentity) {
ownIdentities += ownIdentity
}
fun addSone(id: String, sone: Sone) {
allSones[id] = sone
}
fun addLocalSone(id: String, localSone: Sone) {
localSones[id] = localSone
}
fun addPost(id: String, post: Post) {
allPosts[id] = post
}
fun addPostReply(id: String, postReply: PostReply) {
allPostReplies[id] = postReply
postReply.postId?.also { perPostReplies[it] = postReply }
}
fun addAlbum(id: String, album: Album) {
allAlbums[id] = album
}
fun addImage(id: String, image: Image) {
allImages[id] = image
}
fun addTranslation(key: String, value: String) {
translations[key] = value
}
fun addNotification(id: String, notification: Notification) {
notifications[id] = notification
}
fun addTemporaryImage(id: String, temporaryImage: TemporaryImage) {
whenever(core.getTemporaryImage(id)).thenReturn(temporaryImage)
}
fun addUploadedFile(name: String, filename: String, contentType: String, resource: String) {
uploadedFileNames[name] = filename
uploadedFileContentTypes[name] = contentType
uploadedFileResources[name] = resource
}
fun verifyNoRedirect(assertions: () -> Unit) {
var caughtException: Exception? = null
try {
page.handleRequest(freenetRequest, templateContext)
} catch (e: Exception) {
caughtException = e
}
caughtException?.run { throw this } ?: assertions()
}
fun verifyRedirect(target: String, assertions: () -> Unit = {}) {
try {
page.handleRequest(freenetRequest, templateContext)
fail()
} catch (re: RedirectException) {
if (re.target != target) {
throw re
}
assertions()
} catch (e: Exception) {
throw e
}
}
}
| gpl-3.0 | 0cd5e32a9f96334bcf83b1e8715b947f | 37.190283 | 145 | 0.752465 | 3.858078 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/gallery/GalleryActivity.kt | 1 | 10232 | package com.example.android.eyebody.gallery
import android.content.Intent
import android.content.res.AssetManager
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.example.android.eyebody.R
import com.example.android.eyebody.utility.GoogleDriveManager
import kotlinx.android.synthetic.main.activity_gallery.*
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
class GalleryActivity : AppCompatActivity() {
private val TAG = "mydbg_gallery"
var googleDriveManager: GoogleDriveManager? = null
var toggleItem: MenuItem? = null
var photoList = ArrayList<Photo>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gallery)
googleDriveManager = object : GoogleDriveManager(baseContext, this@GalleryActivity) {
override fun onConnectionStatusChanged() {
if (toggleItem != null) {
if (googleDriveManager?.checkConnection() == true) {
toggleItem?.title = getString(R.string.googleDrive_do_signOut)
Toast.makeText(activity, "connect", Toast.LENGTH_LONG).show()
} else {
toggleItem?.title = getString(R.string.googleDrive_do_signIn)
Toast.makeText(activity, "connect xxx", Toast.LENGTH_LONG).show()
}
}
}
}
//(이미지 리사이징)뷰가 그려지기 전이라서 width, height를 측정해서 가져옴
selectedImage_gallery.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
var measuredWidth = selectedImage_gallery.measuredWidth
var measuredHeight = selectedImage_gallery.measuredHeight
//이미지 불러오기
var state: String = Environment.getExternalStorageState() //외부저장소(SD카드)가 마운트되었는지 확인
if (Environment.MEDIA_MOUNTED.equals(state)) {
//디렉토리 생성
var filedir: String = getExternalFilesDir(null).toString() + "/gallery_body" //Android/data/com.example.android.eyebody/files/gallery_body
var file: File = File(filedir)
if (!file.exists()) {
if (!file.mkdirs()) {
//EXCEPTION 디렉토리가 만들어지지 않음
}
}
assetsToExternalStorage() //assets에 있는 테스트용 이미지를 외부저장소에 복사
for (f in file.listFiles()) {
//TODO 이미지 파일이 아닌경우 예외처리
//TODO 이미지를 암호화해서 저장해놓고 불러올 때만 복호화 하기
photoList.add(Photo(f))
}
if(photoList.size != 0){ //이미지가 하나라도 있어야 selectedImage 세팅
selectedImage_gallery.setImageBitmap(photoList[0].getBitmap(measuredWidth, measuredHeight))
selectedImage_gallery.setTag(0)
}
if(photoList.size > 1){ //이미지가 2개 이상일 때 오른쪽 버튼 보이기
rightButton_gallery.visibility = View.VISIBLE
}
} else{
//EXCEPTION 외부저장소가 마운트되지 않아서 파일을 읽고 쓸 수 없음
}
//RecyclerView
galleryView.hasFixedSize()
galleryView.adapter = GalleryAdapter(this, photoList)
//button onclick listener
leftButton_gallery.setOnClickListener {
rightButton_gallery.visibility = View.VISIBLE
var prePosition: Int = (selectedImage_gallery.getTag() as Int) - 1
if(prePosition == 0){ //이전 사진이 없는 경우
leftButton_gallery.visibility = View.INVISIBLE
}
selectedImage_gallery.setImageBitmap(photoList[prePosition].getBitmap(measuredWidth, measuredHeight))
selectedImage_gallery.setTag(prePosition)
}
rightButton_gallery.setOnClickListener {
leftButton_gallery.visibility = View.VISIBLE
var nextPosition: Int = (selectedImage_gallery.getTag() as Int) + 1
if(nextPosition == photoList.size - 1){ //이후 사진이 없는 경우
rightButton_gallery.visibility = View.INVISIBLE
}
selectedImage_gallery.setImageBitmap(photoList[nextPosition].getBitmap(measuredWidth, measuredHeight))
selectedImage_gallery.setTag(nextPosition)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_gallery, menu)
when (googleDriveManager?.checkConnection()) {
true -> {
menu.findItem(R.id.action_googleDrive_signInOut_togle).title = getString(R.string.googleDrive_do_signOut)
}
false -> {
menu.findItem(R.id.action_googleDrive_signInOut_togle).title = getString(R.string.googleDrive_do_signIn)
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_collage -> { //콜라주 하러가기
var intent = Intent(this, CollageActivity::class.java)
intent.putExtra("photoList", photoList)
startActivity(intent)
}
R.id.action_googleDrive_signInOut_togle -> {//구글드라이브 로그인 토글
toggleItem = item
when (googleDriveManager?.checkConnection()) {
true -> {
googleDriveManager?.signOut()
Log.d(TAG, "do sign out")
}
false -> {
googleDriveManager?.signIn()
Log.d(TAG, "do sign in")
}
}
}
/*
TODO 와이파이가 되있는지 안되어있는지 확인 여부
> wifi / lte
TODO 자동저장을 위한 코딩
> 자동 저장 on 하면 바로 하는 함수 {
내부Query 결과와 현재 리소스파일 전체가 일치하는지 확인
일치하지 않는다면 그 차이를 가지고 update(upload and download)
}
= 접속할 때 마다 동기화가 되어있는지 파악 {
내부Query 결과와 현재 리소스파일 전체가 일치하는지 확인
일치하지 않는다면 그 차이를 가지고 update
}
> 촬영해서 저장할 때 마다 저장 / 선택해서 삭제할 때 마다 삭제 {
단일 파일 저장/불러오기 함수 만들기
}
*/
R.id.action_googleDrive_manualSave -> { //구글드라이브 수동 저장
object : Thread() {
override fun run() {
//TODO 전체 경로를 savelocation 과 savefile 로 나눠서 하는 것이 좋을 듯.
val successPair = googleDriveManager?.saveAllFile(
arrayOf(/* 내부저장소에 있는 모든 .eyebody (백업대상) 파일이름을 array로 구성해야 함. */
"${getExternalFilesDir(null)}/gallery_body/front_week1.jpg",
"${getExternalFilesDir(null)}/gallery_body/front_week2.jpg",
"${getExternalFilesDir(null)}/gallery_body/front_week3.jpg",
"${getExternalFilesDir(null)}/gallery_body/front_week4.jpg")
)
Log.d(TAG, "saving file : (${successPair?.first} / ${successPair?.second})")
}
}.start()
}
R.id.action_googleDrive_manualLoad -> { //구글드라이브 수동 불러오기
object : Thread() {
override fun run() {
val successPair = googleDriveManager?.loadAllFile(
arrayOf(/* 내부저장소에 있는 모든 .eyebody (백업대상) 파일이름을 array로 구성해야 함. */
"${getExternalFilesDir(null)}/gallery_body/front_week1.jpg",
"${getExternalFilesDir(null)}/gallery_body/front_week2.jpg")
)
Log.d(TAG, "loading file : (${successPair?.first} / ${successPair?.second})")
}
}.start()
}
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
//TODO 비트맵 메모리 반환: 이미지 다시 불러오기
}
override fun onStop() {
super.onStop()
//TODO 비트맵 메모리 반환: 하드웨어 가속 끄고 비트맵 반환
}
fun assetsToExternalStorage() {
//assets에 있는 파일을 외부저장소로 복사(테스트용)
for (i in 1..4) {
var filename: String = "front_week" + i + ".jpg"
var assetManager: AssetManager = getAssets()
var input: InputStream = assetManager.open("gallery_body/" + filename)
var outputfile: String = getExternalFilesDir(null).toString() + "/gallery_body/" + filename
var output: OutputStream = FileOutputStream(outputfile)
var buffer: ByteArray = ByteArray(1024)
var length: Int
do {
length = input.read(buffer)
if (length <= 0) break;
output.write(buffer, 0, length)
} while (true)
output.flush();
output.close();
input.close();
}
}
} | mit | bd14c1eff87d3e4e3ce14b71b01bfd3f | 38.386266 | 151 | 0.550458 | 4.054795 | false | false | false | false |
consp1racy/android-commons | commons/src/main/java/net/xpece/android/os/Parcel.kt | 1 | 1595 | @file:JvmName("XpParcel")
package net.xpece.android.os
import android.annotation.SuppressLint
import android.os.Parcel
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.writeBoolean(value: Boolean) {
writeByte(if (value) 1 else 0)
}
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.readBoolean(): Boolean = readByte() != 0.toByte()
/**
* Writes `null` as [Float.NaN]. Only uses 4 bytes.
*/
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.writeFloatOrNan(value: Float?) {
writeFloat(value ?: Float.NaN)
}
/**
* Reads [Float.NaN] as `null`.
*/
@SuppressLint("ParcelClassLoader")
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.readFloatOrNull(): Float? = readFloat().takeIf { it != Float.NaN }
/**
* Writes `null` as [Double.NaN]. Only uses 4 bytes.
*/
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.writeDoubleOrNan(value: Double?) {
writeDouble(value ?: Double.NaN)
}
/**
* Reads [Double.NaN] as `null`.
*/
@SuppressLint("ParcelClassLoader")
@Suppress("NOTHING_TO_INLINE")
inline fun Parcel.readDoubleOrNull(): Double? = readDouble().takeIf { it != Double.NaN }
inline fun <reified E> Parcel.readList(cl: ClassLoader? = E::class.java.classLoader): List<E> =
mutableListOf<E>().apply {
readList(this, cl)
}
inline fun <reified T> Parcel.readTypedValue(cl: ClassLoader? = T::class.java.classLoader): T =
readValue(cl) as T
@Deprecated("Use readTypedValue instead.", replaceWith = ReplaceWith(expression = "readTypedValue"))
inline fun <reified T> Parcel.readValueTyped(cl: ClassLoader? = T::class.java.classLoader): T =
readValue(cl) as T
| apache-2.0 | 09e2073e2e7bf0f962b519220f601b4e | 27.482143 | 100 | 0.702821 | 3.497807 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/parsers/factories/DocTagsFromStringFactory.kt | 1 | 3605 | package org.jetbrains.dokka.base.parsers.factories
import org.jetbrains.dokka.model.doc.*
import org.jetbrains.dokka.links.DRI
import java.lang.NullPointerException
object DocTagsFromStringFactory {
fun getInstance(name: String, children: List<DocTag> = emptyList(), params: Map<String, String> = emptyMap(), body: String? = null, dri: DRI? = null) =
when(name) {
"a" -> A(children, params)
"big" -> Big(children, params)
"b" -> B(children, params)
"blockquote" -> BlockQuote(children, params)
"br" -> Br
"cite" -> Cite(children, params)
"code" -> if(params.isEmpty()) CodeInline(children, params) else CodeBlock(children, params)
"dd" -> Dd(children, params)
"dfn" -> Dfn(children, params)
"dir" -> Dir(children, params)
"div" -> Div(children, params)
"dl" -> Dl(children, params)
"dt" -> Dt(children, params)
"Em" -> Em(children, params)
"font" -> Font(children, params)
"footer" -> Footer(children, params)
"frame" -> Frame(children, params)
"frameset" -> FrameSet(children, params)
"h1" -> H1(children, params)
"h2" -> H2(children, params)
"h3" -> H3(children, params)
"h4" -> H4(children, params)
"h5" -> H5(children, params)
"h6" -> H6(children, params)
"head" -> Head(children, params)
"header" -> Header(children, params)
"html" -> Html(children, params)
"i" -> I(children, params)
"iframe" -> IFrame(children, params)
"img" -> Img(children, params)
"input" -> Input(children, params)
"li" -> Li(children, params)
"link" -> Link(children, params)
"listing" -> Listing(children, params)
"main" -> Main(children, params)
"menu" -> Menu(children, params)
"meta" -> Meta(children, params)
"nav" -> Nav(children, params)
"noframes" -> NoFrames(children, params)
"noscript" -> NoScript(children, params)
"ol" -> Ol(children, params)
"p" -> P(children, params)
"pre" -> Pre(children, params)
"script" -> Script(children, params)
"section" -> Section(children, params)
"small" -> Small(children, params)
"span" -> Span(children, params)
"strong" -> Strong(children, params)
"sub" -> Sub(children, params)
"sup" -> Sup(children, params)
"table" -> Table(children, params)
"#text" -> Text(body ?: throw NullPointerException("Text body should be at least empty string passed to DocNodes factory!"), children, params)
"tBody" -> TBody(children, params)
"td" -> Td(children, params)
"tFoot" -> TFoot(children, params)
"th" -> Th(children, params)
"tHead" -> THead(children, params)
"title" -> Title(children, params)
"tr" -> Tr(children, params)
"tt" -> Tt(children, params)
"u" -> U(children, params)
"ul" -> Ul(children, params)
"var" -> Var(children, params)
"documentationlink" -> DocumentationLink(dri ?: throw NullPointerException("DRI cannot be passed null while constructing documentation link!"), children, params)
"hr" -> HorizontalRule
else -> CustomDocTag(children, params, name)
}
}
| apache-2.0 | 8620a285600cdf425048f2581752abfe | 45.818182 | 173 | 0.535645 | 3.983425 | false | false | false | false |
google/ksp | gradle-plugin/src/test/kotlin/com/google/devtools/ksp/gradle/testing/TestConfig.kt | 1 | 2701 | /*
* Copyright 2021 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.gradle.testing
import java.io.File
import java.util.*
/**
* Test configuration passed down from the main KSP build.
* See the `prepareTestConfiguration` task in the build.gradle.kts file in the `gradle-plugin`.
*/
data class TestConfig(
/**
* The root directory of the main KSP project
*/
val kspProjectDir: File,
/**
* The classpath that can be used to load processors.
* The testing infra allows loading processors from the test classpath of the gradle-plugin.
* This classpath is the output of the test compilation in the main KSP project.
*/
val processorClasspath: String,
/**
* The local maven repository that can be used while running tests
*/
val mavenRepoDir: File,
/**
* The version of KSP.
*/
val kspVersion: String
) {
private val kspProjectProperties by lazy {
Properties().also { props ->
kspProjectDir.resolve("gradle.properties").inputStream().use {
props.load(it)
}
}
}
val kotlinBaseVersion by lazy {
kspProjectProperties["kotlinBaseVersion"] as String
}
val androidBaseVersion by lazy {
kspProjectProperties["agpBaseVersion"] as String
}
val mavenRepoPath = mavenRepoDir.path.replace(File.separatorChar, '/')
companion object {
/**
* Loads the test configuration from resources.
*/
fun read(): TestConfig {
val props = Properties()
TestConfig::class.java.classLoader.getResourceAsStream("testprops.properties").use {
props.load(it)
}
return TestConfig(
kspProjectDir = File(props.get("kspProjectRootDir") as String),
processorClasspath = props.get("processorClasspath") as String,
mavenRepoDir = File(props.get("mavenRepoDir") as String),
kspVersion = props.get("kspVersion") as String
)
}
}
}
| apache-2.0 | 6dcccbb6e8b5409deee85da0c0b0fa29 | 32.7625 | 96 | 0.652721 | 4.625 | false | true | false | false |
jmesserli/discord-bernbot | discord-bot/src/test/kotlin/nu/peg/discord/util/ExtensionsKtTest.kt | 1 | 1203 | package nu.peg.discord.util
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ExtensionsKtTest {
@Test
fun `fromHex works with prefix`() {
val color = fromHex("#FFFFFF")
assertThat(color).extracting("red", "green", "blue")
.containsExactly(255, 255, 255)
}
@Test
fun `fromHex works without prefix`() {
val color = fromHex("FFFFFF")
assertThat(color).extracting("red", "green", "blue")
.containsExactly(255, 255, 255)
}
@Test
fun `fromHex works with three character hex codes`() {
val color = fromHex("ABC")
assertThat(color).extracting("red", "green", "blue")
.containsExactly(170, 187, 204)
}
@Test
fun `fromHex works with six character hex codes`() {
val color = fromHex("AABBCC")
assertThat(color).extracting("red", "green", "blue")
.containsExactly(170, 187, 204)
}
@Test
fun `fromHex works with lower case hex codes`() {
val color = fromHex("aabbcc")
assertThat(color).extracting("red", "green", "blue")
.containsExactly(170, 187, 204)
}
} | mit | 4ee3c1ef24c55bdd94fa28d2408c31b4 | 25.173913 | 60 | 0.58271 | 4.191638 | false | true | false | false |
mkAndroDev/SimpleRemoteController | app/src/main/java/com/krawczyk/maciej/simpleremotecontroller/android/fragments/ImmediatelyOnOffFragment.kt | 1 | 4363 | package com.krawczyk.maciej.simpleremotecontroller.android.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.krawczyk.maciej.simpleremotecontroller.R
import com.krawczyk.maciej.simpleremotecontroller.data.model.AiringModel
import com.krawczyk.maciej.simpleremotecontroller.data.model.FurnaceModel
import kotlinx.android.synthetic.main.fragment_immediately_on_off.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ImmediatelyOnOffFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_immediately_on_off, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
}
private fun setupViews() {
val airingOnOff = weatherService.airingOnOff
airingOnOff.enqueue(getAiringCallback())
val furnaceOnOff = weatherService.furnaceOnOff
furnaceOnOff.enqueue(getFurnaceCallback())
setupFurnaceChangeListener(false)
setupAiringChangeListener(false)
}
private fun getAiringCallback(): Callback<AiringModel> {
return object : Callback<AiringModel> {
override fun onResponse(call: Call<AiringModel>, response: Response<AiringModel>) {
if (response.isSuccessful && response.body() != null) {
setupAiringChangeListener(true)
switch_start_airing.isChecked = response.body()?.isLaunched == 1
setupAiringChangeListener(false)
}
}
override fun onFailure(call: Call<AiringModel>, t: Throwable) {
Log.d("Airing Response: ", t.message)
if (isAdded) {
Toast.makeText(context, "Airing Response: " + t.message, Toast.LENGTH_LONG).show()
setupAiringChangeListener(true)
switch_start_airing.isChecked = !switch_start_airing.isChecked
setupAiringChangeListener(false)
}
}
}
}
private fun getFurnaceCallback(): Callback<FurnaceModel> {
return object : Callback<FurnaceModel> {
override fun onResponse(call: Call<FurnaceModel>, response: Response<FurnaceModel>) {
if (response.isSuccessful && response.body() != null) {
setupFurnaceChangeListener(true)
switch_start_furnace.isChecked = response.body()?.isLaunched == 1
setupFurnaceChangeListener(false)
}
}
override fun onFailure(call: Call<FurnaceModel>, t: Throwable) {
Log.d("Airing Response: ", t.message)
if (isAdded) {
Toast.makeText(context, "Airing Response: " + t.message, Toast.LENGTH_LONG).show()
setupFurnaceChangeListener(true)
switch_start_furnace.isChecked = !switch_start_furnace.isChecked
setupFurnaceChangeListener(false)
}
}
}
}
private fun setupAiringChangeListener(listenerNull: Boolean) {
if (listenerNull) {
switch_start_airing.setOnCheckedChangeListener(null)
} else {
this.switch_start_airing.setOnCheckedChangeListener { _, isChecked ->
val putAiringOnOff = weatherService.putAiringOffNow()
putAiringOnOff.enqueue(getAiringCallback())
}
}
}
private fun setupFurnaceChangeListener(listenerNull: Boolean) {
if (listenerNull) {
switch_start_furnace.setOnCheckedChangeListener(null)
} else {
switch_start_furnace.setOnCheckedChangeListener { _, isChecked ->
val putFurnaceOnOff = weatherService.putFurnaceOnOff()
putFurnaceOnOff.enqueue(getFurnaceCallback())
}
}
}
companion object {
fun newInstance(): ImmediatelyOnOffFragment {
return ImmediatelyOnOffFragment()
}
}
}
| apache-2.0 | 8d915953b6d24c0695105bdf32365713 | 37.27193 | 102 | 0.630071 | 4.946712 | false | false | false | false |
actions-on-google/actions-on-google-java | src/main/kotlin/com/google/actions/api/ActionsSdkApp.kt | 1 | 2052 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.actions.api
import com.google.actions.api.impl.AogRequest
import com.google.actions.api.response.ResponseBuilder
import org.slf4j.LoggerFactory
/**
* Implementation of App for ActionsSDK based webhook. Developers must extend
* this class if they are using the ActionsSDK (as against Dialogflow) to handle
* requests.
*
* Note that the value of the @ForIntent annotation must match (case-sensitive)
* the name of the intent.
*
* Usage:
* ``` Java
* class MyActionsApp extends ActionsSdkApp {
*
* @ForIntent("welcome")
* public CompletableFuture<ActionResponse> showWelcomeMessage(
* ActionRequest request) {
* // Intent handler implementation here.
* }
* ```
*/
open class ActionsSdkApp : DefaultApp() {
private companion object {
val LOG = LoggerFactory.getLogger(ActionsSdkApp::class.java.name)
}
override fun createRequest(inputJson: String, headers: Map<*, *>?): ActionRequest {
LOG.info("ActionsSdkApp.createRequest..")
return AogRequest.create(inputJson, headers)
}
override fun getResponseBuilder(request: ActionRequest): ResponseBuilder {
val responseBuilder = ResponseBuilder(
usesDialogflow = false,
sessionId = request.sessionId,
conversationData = request.conversationData,
userStorage = request.userStorage)
return responseBuilder
}
}
| apache-2.0 | c2bd9d5f164759d763a5618b91a9aa86 | 32.639344 | 87 | 0.70614 | 4.384615 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/feature/backup/BackupAdapter.kt | 3 | 2305 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.backup
import android.content.Context
import android.text.format.Formatter
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.FlowableAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.DateFormatter
import com.moez.QKSMS.model.BackupFile
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.backup_list_item.*
import javax.inject.Inject
class BackupAdapter @Inject constructor(
private val context: Context,
private val dateFormatter: DateFormatter
) : FlowableAdapter<BackupFile>() {
val backupSelected: Subject<BackupFile> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.backup_list_item, parent, false)
return QkViewHolder(view).apply {
view.setOnClickListener { backupSelected.onNext(getItem(adapterPosition)) }
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val backup = getItem(position)
val count = backup.messages
holder.title.text = dateFormatter.getDetailedTimestamp(backup.date)
holder.messages.text = context.resources.getQuantityString(R.plurals.backup_message_count, count, count)
holder.size.text = Formatter.formatFileSize(context, backup.size)
}
} | gpl-3.0 | d26557dbc29e99d4c4fdd8e4566eef2f | 36.803279 | 112 | 0.753579 | 4.244936 | false | false | false | false |
googlecodelabs/fido2-codelab | android/app/src/main/java/com/example/android/fido2/repository/AuthRepository.kt | 1 | 12207 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fido2.repository
import android.app.PendingIntent
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import com.example.android.fido2.api.ApiException
import com.example.android.fido2.api.ApiResult
import com.example.android.fido2.api.AuthApi
import com.example.android.fido2.api.Credential
import com.example.android.fido2.toBase64
import com.google.android.gms.fido.fido2.Fido2ApiClient
import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
import javax.inject.Singleton
/**
* Works with the API, the local data store, and FIDO2 API.
*/
@Singleton
class AuthRepository @Inject constructor(
private val api: AuthApi,
private val dataStore: DataStore<Preferences>,
scope: CoroutineScope
) {
private companion object {
const val TAG = "AuthRepository"
// Keys for SharedPreferences
val USERNAME = stringPreferencesKey("username")
val SESSION_ID = stringPreferencesKey("session_id")
val CREDENTIALS = stringSetPreferencesKey("credentials")
val LOCAL_CREDENTIAL_ID = stringPreferencesKey("local_credential_id")
suspend fun <T> DataStore<Preferences>.read(key: Preferences.Key<T>): T? {
return data.map { it[key] }.first()
}
}
private var fido2ApiClient: Fido2ApiClient? = null
fun setFido2APiClient(client: Fido2ApiClient?) {
fido2ApiClient = client
}
private val signInStateMutable = MutableSharedFlow<SignInState>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
/** The current [SignInState]. */
val signInState = signInStateMutable.asSharedFlow()
/**
* The list of credentials this user has registered on the server. This is only populated when
* the sign-in state is [SignInState.SignedIn].
*/
val credentials =
dataStore.data.map { it[CREDENTIALS] ?: emptySet() }.map { parseCredentials(it) }
init {
scope.launch {
val username = dataStore.read(USERNAME)
val sessionId = dataStore.read(SESSION_ID)
val initialState = when {
username.isNullOrBlank() -> SignInState.SignedOut
sessionId.isNullOrBlank() -> SignInState.SigningIn(username)
else -> SignInState.SignedIn(username)
}
signInStateMutable.emit(initialState)
if (initialState is SignInState.SignedIn) {
refreshCredentials()
}
}
}
/**
* Sends the username to the server. If it succeeds, the sign-in state will proceed to
* [SignInState.SigningIn].
*/
suspend fun username(username: String) {
when (val result = api.username(username)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
dataStore.edit { prefs ->
prefs[USERNAME] = username
prefs[SESSION_ID] = result.sessionId!!
}
signInStateMutable.emit(SignInState.SigningIn(username))
}
}
}
/**
* Signs in with a password. This should be called only when the sign-in state is
* [SignInState.SigningIn]. If it succeeds, the sign-in state will proceed to
* [SignInState.SignedIn].
*/
suspend fun password(password: String) {
val username = dataStore.read(USERNAME)!!
val sessionId = dataStore.read(SESSION_ID)!!
try {
when (val result = api.password(sessionId, password)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
if (result.sessionId != null) {
dataStore.edit { prefs ->
prefs[SESSION_ID] = result.sessionId
}
}
signInStateMutable.emit(SignInState.SignedIn(username))
refreshCredentials()
}
}
} catch (e: ApiException) {
Log.e(TAG, "Invalid login credentials", e)
// start login over again
dataStore.edit { prefs ->
prefs.remove(USERNAME)
prefs.remove(SESSION_ID)
prefs.remove(CREDENTIALS)
}
signInStateMutable.emit(
SignInState.SignInError(e.message ?: "Invalid login credentials")
)
}
}
private suspend fun refreshCredentials() {
val sessionId = dataStore.read(SESSION_ID)!!
when (val result = api.getKeys(sessionId)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
dataStore.edit { prefs ->
result.sessionId?.let { prefs[SESSION_ID] = it }
prefs[CREDENTIALS] = result.data.toStringSet()
}
}
}
}
private fun List<Credential>.toStringSet(): Set<String> {
return mapIndexed { index, credential ->
"$index;${credential.id};${credential.publicKey}"
}.toSet()
}
private fun parseCredentials(set: Set<String>): List<Credential> {
return set.map { s ->
val (index, id, publicKey) = s.split(";")
index to Credential(id, publicKey)
}.sortedBy { (index, _) -> index }
.map { (_, credential) -> credential }
}
/**
* Clears the credentials. The sign-in state will proceed to [SignInState.SigningIn].
*/
suspend fun clearCredentials() {
val username = dataStore.read(USERNAME)!!
dataStore.edit { prefs ->
prefs.remove(CREDENTIALS)
}
signInStateMutable.emit(SignInState.SigningIn(username))
}
/**
* Clears all the sign-in information. The sign-in state will proceed to
* [SignInState.SignedOut].
*/
suspend fun signOut() {
dataStore.edit { prefs ->
prefs.remove(USERNAME)
prefs.remove(SESSION_ID)
prefs.remove(CREDENTIALS)
}
signInStateMutable.emit(SignInState.SignedOut)
}
private suspend fun forceSignOut() {
dataStore.edit { prefs ->
prefs.remove(USERNAME)
prefs.remove(SESSION_ID)
prefs.remove(CREDENTIALS)
}
signInStateMutable.emit(SignInState.SignInError("Signed out by server"))
}
/**
* Starts to register a new credential to the server. This should be called only when the
* sign-in state is [SignInState.SignedIn].
*/
suspend fun registerRequest(): PendingIntent? {
fido2ApiClient?.let { client ->
try {
val sessionId = dataStore.read(SESSION_ID)!!
when (val apiResult = api.registerRequest(sessionId)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
if (apiResult.sessionId != null) {
dataStore.edit { prefs ->
prefs[SESSION_ID] = apiResult.sessionId
}
}
val task = client.getRegisterPendingIntent(apiResult.data)
return task.await()
}
}
} catch (e: Exception) {
Log.e(TAG, "Cannot call registerRequest", e)
}
}
return null
}
/**
* Finishes registering a new credential to the server. This should only be called after
* a call to [registerRequest] and a local FIDO2 API for public key generation.
*/
suspend fun registerResponse(credential: PublicKeyCredential) {
try {
val sessionId = dataStore.read(SESSION_ID)!!
val credentialId = credential.rawId.toBase64()
when (val result = api.registerResponse(sessionId, credential)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
dataStore.edit { prefs ->
result.sessionId?.let { prefs[SESSION_ID] = it }
prefs[CREDENTIALS] = result.data.toStringSet()
prefs[LOCAL_CREDENTIAL_ID] = credentialId
}
}
}
} catch (e: ApiException) {
Log.e(TAG, "Cannot call registerResponse", e)
}
}
/**
* Removes a credential registered on the server.
*/
suspend fun removeKey(credentialId: String) {
try {
val sessionId = dataStore.read(SESSION_ID)!!
when (api.removeKey(sessionId, credentialId)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> refreshCredentials()
}
} catch (e: ApiException) {
Log.e(TAG, "Cannot call removeKey", e)
}
}
/**
* Starts to sign in with a FIDO2 credential. This should only be called when the sign-in state
* is [SignInState.SigningIn].
*/
suspend fun signinRequest(): PendingIntent? {
fido2ApiClient?.let { client ->
val sessionId = dataStore.read(SESSION_ID)!!
val credentialId = dataStore.read(LOCAL_CREDENTIAL_ID)
if (credentialId != null) {
when (val apiResult = api.signinRequest(sessionId, credentialId)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
val task = client.getSignPendingIntent(apiResult.data)
return task.await()
}
}
}
}
return null
}
/**
* Finishes to signing in with a FIDO2 credential. This should only be called after a call to
* [signinRequest] and a local FIDO2 API for key assertion.
*/
suspend fun signinResponse(credential: PublicKeyCredential) {
try {
val username = dataStore.read(USERNAME)!!
val sessionId = dataStore.read(SESSION_ID)!!
val credentialId = credential.rawId.toBase64()
when (val result = api.signinResponse(sessionId, credential)) {
ApiResult.SignedOutFromServer -> forceSignOut()
is ApiResult.Success -> {
dataStore.edit { prefs ->
result.sessionId?.let { prefs[SESSION_ID] = it }
prefs[CREDENTIALS] = result.data.toStringSet()
prefs[LOCAL_CREDENTIAL_ID] = credentialId
}
signInStateMutable.emit(SignInState.SignedIn(username))
refreshCredentials()
}
}
} catch (e: ApiException) {
Log.e(TAG, "Cannot call registerResponse", e)
}
}
}
| apache-2.0 | 37a3384b5dacf270f282b41fb85bdfe7 | 36.103343 | 99 | 0.591054 | 4.834455 | false | false | false | false |
geckour/Egret | app/src/main/java/com/geckour/egret/util/AuthInterceptor.kt | 1 | 622 | package com.geckour.egret.util
import okhttp3.Interceptor
import okhttp3.Response
class AuthInterceptor: Interceptor {
private var token: String? = null
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val builder = original.newBuilder()
if (token.isNullOrEmpty()) builder.method(original.method(), original.body())
else builder.header("Authorization", "Bearer $token")
return chain.proceed(builder.build())
}
fun setToken(token: String) {
this.token = token
}
fun getToken(): String? = this.token
} | gpl-3.0 | db8aac19714e556f54819953cabdb95f | 23.92 | 85 | 0.673633 | 4.47482 | false | false | false | false |
msebire/intellij-community | platform/script-debugger/backend/src/debugger/BreakpointManagerBase.kt | 2 | 5014 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.debugger
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.containers.ContainerUtil
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.all
import org.jetbrains.concurrency.nullPromise
import org.jetbrains.concurrency.rejectedPromise
import java.util.concurrent.ConcurrentMap
abstract class BreakpointManagerBase<T : BreakpointBase<*>> : BreakpointManager {
override val breakpoints: MutableSet<T> = ContainerUtil.newConcurrentSet<T>()
protected val breakpointDuplicationByTarget: ConcurrentMap<T, T> = ConcurrentCollectionFactory.createMap<T, T>(object : TObjectHashingStrategy<T> {
override fun computeHashCode(b: T): Int {
var result = b.line
result *= 31 + b.column
if (b.condition != null) {
result *= 31 + b.condition!!.hashCode()
}
result *= 31 + b.target.hashCode()
return result
}
override fun equals(b1: T, b2: T) =
b1.target.javaClass == b2.target.javaClass &&
b1.target == b2.target &&
b1.line == b2.line &&
b1.column == b2.column &&
StringUtil.equals(b1.condition, b2.condition)
})
protected val dispatcher: EventDispatcher<BreakpointListener> = EventDispatcher.create(BreakpointListener::class.java)
protected abstract fun createBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): T
protected abstract fun doSetBreakpoint(target: BreakpointTarget, url: Url?, breakpoint: T): Promise<out Breakpoint>
override fun setBreakpoint(target: BreakpointTarget,
line: Int,
column: Int,
url: Url?,
condition: String?,
ignoreCount: Int): BreakpointManager.SetBreakpointResult {
val breakpoint = createBreakpoint(target, line, column, condition, ignoreCount, true)
val existingBreakpoint = breakpointDuplicationByTarget.putIfAbsent(breakpoint, breakpoint)
if (existingBreakpoint != null) {
return BreakpointManager.BreakpointExist(existingBreakpoint)
}
breakpoints.add(breakpoint)
val promise = doSetBreakpoint(target, url, breakpoint)
.onError { dispatcher.multicaster.errorOccurred(breakpoint, it.message ?: it.toString()) }
return BreakpointManager.BreakpointCreated(breakpoint, promise)
}
final override fun remove(breakpoint: Breakpoint): Promise<*> {
@Suppress("UNCHECKED_CAST")
val b = breakpoint as T
val existed = breakpoints.remove(b)
if (existed) {
breakpointDuplicationByTarget.remove(b)
}
return if (!existed || !b.isVmRegistered()) nullPromise() else doClearBreakpoint(b)
}
final override fun removeAll(): Promise<*> {
val list = breakpoints.toList()
breakpoints.clear()
breakpointDuplicationByTarget.clear()
val promises = SmartList<Promise<*>>()
for (b in list) {
if (b.isVmRegistered()) {
promises.add(doClearBreakpoint(b))
}
}
return promises.all()
}
protected abstract fun doClearBreakpoint(breakpoint: T): Promise<*>
final override fun addBreakpointListener(listener: BreakpointListener) {
dispatcher.addListener(listener)
}
protected fun notifyBreakpointResolvedListener(breakpoint: T) {
if (breakpoint.isResolved) {
dispatcher.multicaster.resolved(breakpoint)
}
}
@Suppress("UNCHECKED_CAST")
override fun flush(breakpoint: Breakpoint): Promise<*> = (breakpoint as T).flush(this)
override fun enableBreakpoints(enabled: Boolean): Promise<*> = rejectedPromise<Any?>("Unsupported")
override fun setBreakOnFirstStatement() {
}
override fun isBreakOnFirstStatement(context: SuspendContext<*>): Boolean = false
}
// used in goland
@Suppress("unused")
class DummyBreakpointManager : BreakpointManager {
override val breakpoints: Iterable<Breakpoint>
get() = emptyList()
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, url: Url?, condition: String?, ignoreCount: Int): BreakpointManager.SetBreakpointResult {
throw UnsupportedOperationException()
}
override fun remove(breakpoint: Breakpoint): Promise<*> = nullPromise()
override fun addBreakpointListener(listener: BreakpointListener) {
}
override fun removeAll(): Promise<*> = nullPromise()
override fun flush(breakpoint: Breakpoint): Promise<*> = nullPromise()
override fun enableBreakpoints(enabled: Boolean): Promise<*> = nullPromise()
override fun setBreakOnFirstStatement() {
}
override fun isBreakOnFirstStatement(context: SuspendContext<*>): Boolean = false
} | apache-2.0 | c874c6a62c258afa3fccadaa6f12fe97 | 36.425373 | 168 | 0.719186 | 4.616943 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/IterableEx.kt | 1 | 3216 | package kotlin.sql
public interface SizedIterable<out T>: Iterable<T> {
fun limit(n: Int): SizedIterable<T>
fun count(): Int
fun empty(): Boolean
fun forUpdate(): SizedIterable<T> = this
fun notForUpdate(): SizedIterable<T> = this
}
fun <T> emptySized() : SizedIterable<T> {
return EmptySizedIterable()
}
class EmptySizedIterable<T> : SizedIterable<T>, Iterator<T> {
override fun count(): Int {
return 0
}
override fun limit(n: Int): SizedIterable<T> {
return this;
}
override fun empty(): Boolean {
return true
}
operator override fun iterator(): Iterator<T> {
return this
}
operator override fun next(): T {
throw UnsupportedOperationException()
}
override fun hasNext(): Boolean {
return false;
}
}
public class SizedCollection<out T>(val delegate: Collection<T>): SizedIterable<T> {
override fun limit(n: Int): SizedIterable<T> {
return SizedCollection(delegate.take(n))
}
operator override fun iterator() = delegate.iterator()
override fun count() = delegate.size
override fun empty() = delegate.isEmpty()
}
public class LazySizedCollection<out T>(val delegate: SizedIterable<T>): SizedIterable<T> {
private var _wrapper: List<T>? = null
private var _size: Int? = null
private var _empty: Boolean? = null
val wrapper: List<T> get() {
if (_wrapper == null) {
_wrapper = delegate.toList()
}
return _wrapper!!
}
override fun limit(n: Int): SizedIterable<T> = delegate.limit(n)
operator override fun iterator() = wrapper.iterator()
override fun count() = _wrapper?.size ?: _count()
override fun empty() = _wrapper?.isEmpty() ?: _empty()
override fun forUpdate(): SizedIterable<T> = delegate.forUpdate()
override fun notForUpdate(): SizedIterable<T> = delegate.notForUpdate()
private fun _count(): Int {
if (_size == null) {
_size = delegate.count()
_empty = (_size == 0)
}
return _size!!
}
private fun _empty(): Boolean {
if (_empty == null) {
_empty = delegate.empty()
if (_empty == true) _size = 0
}
return _empty!!
}
}
infix fun <T, R> SizedIterable<T>.mapLazy(f:(T)->R):SizedIterable<R> {
val source = this
return object : SizedIterable<R> {
override fun limit(n: Int): SizedIterable<R> = source.limit(n).mapLazy(f)
override fun forUpdate(): SizedIterable<R> = source.forUpdate().mapLazy(f)
override fun notForUpdate(): SizedIterable<R> = source.notForUpdate().mapLazy(f)
override fun count(): Int = source.count()
override fun empty(): Boolean = source.empty()
operator public override fun iterator(): Iterator<R> {
val sourceIterator = source.iterator()
return object: Iterator<R> {
operator public override fun next(): R {
return f(sourceIterator.next())
}
public override fun hasNext(): Boolean {
return sourceIterator.hasNext()
}
}
}
}
}
| agpl-3.0 | 10e2fc13cde5931dbc76a7ff55b0d099 | 27.972973 | 91 | 0.591107 | 4.328398 | false | false | false | false |
ankidroid/Anki-Android | lint-rules/src/main/java/com/ichi2/anki/lint/rules/NonPositionalFormatSubstitutions.kt | 1 | 6000 | /*
* Copyright (c) 2022 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:Suppress("UnstableApiUsage")
package com.ichi2.anki.lint.rules
import com.android.SdkConstants
import com.android.resources.ResourceFolderType
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.ResourceXmlDetector
import com.android.tools.lint.detector.api.Scope.Companion.ALL_RESOURCES_SCOPE
import com.android.tools.lint.detector.api.XmlContext
import com.ichi2.anki.lint.utils.Aapt2Util
import com.ichi2.anki.lint.utils.Aapt2Util.FormatData
import com.ichi2.anki.lint.utils.Constants
import com.ichi2.anki.lint.utils.StringFormatDetector
import com.ichi2.anki.lint.utils.childrenSequence
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.lang.IllegalStateException
/**
* Fix for "Multiple substitutions specified in non-positional format"
* [Issue 10347](https://github.com/ankidroid/Anki-Android/issues/10347)
* [Issue 11072: Plurals](https://github.com/ankidroid/Anki-Android/issues/11072)
*/
class NonPositionalFormatSubstitutions : ResourceXmlDetector() {
companion object {
private val IMPLEMENTATION_XML = Implementation(NonPositionalFormatSubstitutions::class.java, ALL_RESOURCES_SCOPE)
/**
* Whether there are any duplicate strings, including capitalization adjustments.
*/
val ISSUE = Issue.create(
"NonPositionalFormatSubstitutions",
"Multiple substitutions specified in non-positional format",
"An XML string contains ambiguous format parameters " +
"for example: %s %s. These should be positional (%1\$s %2\$s) to allow" +
"translators to select the ordering.",
Constants.ANKI_CROWDIN_CATEGORY,
Constants.ANKI_CROWDIN_PRIORITY,
Constants.ANKI_CROWDIN_SEVERITY,
IMPLEMENTATION_XML
)
}
override fun appliesTo(folderType: ResourceFolderType): Boolean = folderType == ResourceFolderType.VALUES
override fun getApplicableElements() = listOf(SdkConstants.TAG_STRING, SdkConstants.TAG_PLURALS)
override fun visitElement(context: XmlContext, element: Element) {
val elementsToCheck = when (element.tagName) {
SdkConstants.TAG_PLURALS -> element.childrenSequence()
// skip if the item was not a plural (style, etc...)
.filter { it.nodeName == SdkConstants.TAG_ITEM }
.filter { it.nodeType == Node.ELEMENT_NODE }
.map { it as Element }
.toList()
SdkConstants.TAG_STRING -> listOf(element)
else -> throw IllegalStateException("Unsupported tag: ${element.tagName}")
}
val validFormatData =
elementsToCheck.mapNotNull { getStringFromElement(it) }
.filter { it.isNotEmpty() }
// Filter to only string format data
.mapNotNull {
Aapt2Util.verifyJavaStringFormat(it).let { formatData ->
when (formatData) {
is FormatData.DateFormatData -> null
is FormatData.StringFormatData -> formatData
}
}
}
validFormatData.filter { it.argCount > 0 }.also { formatData ->
// for plurals: report if some have positional args, but not others.
// This may not trigger the second check, see unit tests
if (formatData.any { !it.hasNonPositionalArguments } && !formatData.all { !it.hasNonPositionalArguments }) {
reportPositionalArgumentMismatch(context, element)
}
}
// report the invalid nodes
for (unused in validFormatData.filter { it.isInvalid }) {
reportInvalidPositionalArguments(context, element)
}
}
private fun getStringFromElement(element: Element): String? {
// Check both the translated text and the "values" directory.
val childNodes = element.childNodes
if (childNodes.length <= 0) return null
if (childNodes.length == 1) {
val child = childNodes.item(0)
return if (child.nodeType != Node.TEXT_NODE && child.nodeType != Node.CDATA_SECTION_NODE) {
null
} else {
StringFormatDetector.stripQuotes(child.nodeValue)
}
}
val sb = StringBuilder()
StringFormatDetector.addText(sb, element)
return sb.toString()
}
private fun reportPositionalArgumentMismatch(context: XmlContext, element: Element) {
val location = context.createLocationHandle(element).resolve()
// For clarity, the unescaped string is: "%s to %1$s"
context.report(ISSUE, location, "Some, but not all plurals have positional arguments. Convert \"%s\" to \"%1\$s\"")
}
private fun reportInvalidPositionalArguments(context: XmlContext, element: Element) {
val location = context.createLocationHandle(element).resolve()
// For clarity, the unescaped string is: "%s to %1$s"
context.report(ISSUE, location, "Multiple substitutions specified in non-positional format. Convert \"%s\" to \"%1\$s\"")
}
}
| gpl-3.0 | 792fd5fc3de9be0b522b91209d9ec5c7 | 42.79562 | 129 | 0.660833 | 4.474273 | false | false | false | false |
SergeySave/SpaceGame | desktop/src/com/sergey/spacegame/client/ecs/system/VisualUpdateSystem.kt | 1 | 2841 | package com.sergey.spacegame.client.ecs.system
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.EntityListener
import com.badlogic.ashley.core.EntitySystem
import com.badlogic.ashley.core.Family
import com.badlogic.gdx.graphics.Color
import com.sergey.spacegame.client.data.ClientVisualData
import com.sergey.spacegame.client.ecs.component.SelectedComponent
import com.sergey.spacegame.common.ecs.component.InContructionComponent
import com.sergey.spacegame.common.ecs.component.VisualComponent
/**
* Represents the system that updates visual data
*
* @author sergeys
*
* @constructor Creates a new VisualUpdateSystem
*/
class VisualUpdateSystem : EntitySystem(2) {
//The entity listeners for efficient colorization
lateinit var selectedListener: EntityListener
lateinit var inConstructionListener: EntityListener
init {
//This system doesnt need to do any processing
setProcessing(false)
}
override fun addedToEngine(engine: Engine) {
selectedListener = Colorizer(SELECTED_MULT, SELECTED_ADD).also { listener ->
engine.addEntityListener(Family.all(VisualComponent::class.java, SelectedComponent::class.java).get(), listener)
}
inConstructionListener = Colorizer(INCONSTRUCTION_MULT, INCONSTRUCTION_ADD).also { listener ->
engine.addEntityListener(Family.all(VisualComponent::class.java, InContructionComponent::class.java).get(), listener)
}
}
override fun removedFromEngine(engine: Engine) {
engine.removeEntityListener(selectedListener)
engine.removeEntityListener(inConstructionListener)
}
override fun update(deltaTime: Float) = Unit
private companion object {
val SELECTED_MULT = Color.toFloatBits(0.5f, 0.5f, 0.5f, 1.0f)
val SELECTED_ADD = Color.toFloatBits(0.5f, 0.5f, 0.5f, 0.0f)
val INCONSTRUCTION_MULT = Color.toFloatBits(1f, 1f, 1f, 0.5f)
val INCONSTRUCTION_ADD = Color.toFloatBits(0f, 0f, 0f, 0f)
}
private class Colorizer(val mult: Float, val add: Float) : EntityListener {
override fun entityAdded(entity: Entity) {
val visualData = VisualComponent.MAPPER.get(entity).visualData
if (visualData is ClientVisualData) {
visualData.multColor = mult
visualData.addColor = add
}
}
override fun entityRemoved(entity: Entity) {
val visualData = VisualComponent.MAPPER.get(entity).visualData
if (visualData is ClientVisualData) {
visualData.multColor = ClientVisualData.MULT_DEFAULT
visualData.addColor = ClientVisualData.ADD_DEFAULT
}
}
}
}
| mit | c841b89416da131aa0077e6c0ef961f9 | 36.381579 | 129 | 0.688138 | 4.265766 | false | false | false | false |
googlecodelabs/optimized-for-chromeos | complete/src/main/java/com/google/sample/optimizedforchromeos/complete/DinoViewModel.kt | 1 | 2192 | /*
* Copyright (c) 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.optimizedforchromeos.complete
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.*
class DinoViewModel : ViewModel() {
private val undoStack = ArrayDeque<Int>()
private val redoStack = ArrayDeque<Int>()
private val messagesSent = MutableLiveData<Int>().apply { value = 0 }
private val dinosClicked = MutableLiveData<Int>().apply { value = 0 }
private val dropText = MutableLiveData<String>().apply { value = "Drop Things Here!" }
fun getUndoStack(): ArrayDeque<Int> {
return undoStack
}
fun getRedoStack(): ArrayDeque<Int> {
return redoStack
}
fun getDinosClicked(): LiveData<Int> {
return dinosClicked
}
fun getDinosClickedInt(): Int {
return dinosClicked.value ?: 0
}
fun setDinosClicked(newNumClicks: Int): LiveData<Int> {
dinosClicked.value = newNumClicks
return dinosClicked
}
fun getMessagesSent(): LiveData<Int> {
return messagesSent
}
fun getMessagesSentInt(): Int {
return messagesSent.value ?: 0
}
fun setMessagesSent(newMessagesSent: Int): LiveData<Int> {
messagesSent.value = newMessagesSent
return messagesSent
}
fun getDropText(): LiveData<String> {
return dropText
}
fun setDropText(newDropText: String): LiveData<String> {
dropText.value = newDropText
return dropText
}
} | apache-2.0 | 58943a116d0c54883983681e51627384 | 28.635135 | 90 | 0.668796 | 4.28125 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/util/UserBlockingHandler.kt | 1 | 4102 | /*
* 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.util
import android.content.Context
import android.content.DialogInterface
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
import com.toshi.R
import com.toshi.viewModel.BlockingAction
class UserBlockingHandler(
private val context: Context,
private val onBlock: () -> Unit,
private val onUnblock: () -> Unit) {
private var blockedUserDialog: AlertDialog? = null
private var confirmationDialog: AlertDialog? = null
fun showDialog(isBlocked: Boolean) {
if (isBlocked) showUnblockedDialog()
else showBlockedDialog()
}
private fun showUnblockedDialog() {
showBlockingDialog(
R.string.unblock_user_dialog_title,
R.string.unblock_user_dialog_message,
R.string.unblock,
R.string.cancel,
DialogInterface.OnClickListener { dialog, _ ->
dialog.dismiss()
onUnblock()
}
)
}
private fun showBlockedDialog() {
showBlockingDialog(
R.string.block_user_dialog_title,
R.string.block_user_dialog_message,
R.string.block,
R.string.cancel,
DialogInterface.OnClickListener { dialog, _ ->
dialog.dismiss()
onBlock()
}
)
}
private fun showBlockingDialog(@StringRes title: Int,
@StringRes message: Int,
@StringRes positiveButtonText: Int,
@StringRes negativeButtonText: Int,
listener: DialogInterface.OnClickListener) {
val builder = DialogUtil.getBaseDialog(
this.context,
title,
message,
positiveButtonText,
negativeButtonText,
listener
)
this.blockedUserDialog = builder.create()
this.blockedUserDialog?.show()
}
fun showConfirmationDialog(blockedAction: BlockingAction) {
if (blockedAction == BlockingAction.BLOCKED) handleBlockerUser()
else handleUnblockUser()
}
private fun handleBlockerUser() {
showConfirmationDialog(
R.string.block_user_confirmation_dialog_title,
R.string.block_user_confirmation_dialog_message,
R.string.dismiss
)
}
private fun handleUnblockUser() {
showConfirmationDialog(
R.string.unblock_user_confirmation_dialog_title,
R.string.unblock_user_confirmation_dialog_message,
R.string.dismiss
)
}
private fun showConfirmationDialog(@StringRes title: Int,
@StringRes message: Int,
@StringRes negativeButtonText: Int) {
val baseDialog = DialogUtil.getBaseDialog(
this.context,
title,
message,
negativeButtonText
)
this.confirmationDialog = baseDialog.create()
this.confirmationDialog?.show()
}
fun clear() {
this.blockedUserDialog?.dismiss()
this.confirmationDialog?.dismiss()
}
} | gpl-3.0 | 9db3f9706b519d1f06898c05c69bed31 | 32.357724 | 79 | 0.582155 | 5.114713 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/cbor/jvmTest/src/kotlinx/serialization/cbor/TestUtilities.kt | 1 | 1336 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.cbor
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.dataformat.cbor.*
import com.fasterxml.jackson.module.kotlin.*
import kotlinx.serialization.*
internal val cborJackson = ObjectMapper(CBORFactory()).apply { registerKotlinModule() }
internal val defaultCbor = Cbor { encodeDefaults = true }
internal inline fun <reified T : Any> dumpCborCompare(it: T, alwaysPrint: Boolean = false): Boolean {
var parsed: T?
val c = try {
val bytes = defaultCbor.encodeToByteArray(it)
parsed = cborJackson.readValue<T>(bytes)
it == parsed
} catch (e: Exception) {
e.printStackTrace()
parsed = null
false
}
if (!c || alwaysPrint) println("Expected: $it\nfound: $parsed")
return c
}
internal inline fun <reified T: Any> readCborCompare(it: T, alwaysPrint: Boolean = false): Boolean {
var obj: T?
val c = try {
val hex = cborJackson.writeValueAsBytes(it)
obj = defaultCbor.decodeFromByteArray(hex)
obj == it
} catch (e: Exception) {
obj = null
e.printStackTrace()
false
}
if (!c || alwaysPrint) println("Expected: $it\nfound: $obj")
return c
}
| apache-2.0 | eae7639e23ac36dc273f266f8f415f4f | 30.069767 | 102 | 0.66018 | 3.817143 | false | false | false | false |
rusinikita/movies-shmoovies | app/src/main/kotlin/com/nikita/movies_shmoovies/movies/MoviesInfoActivity.kt | 1 | 7471 | package com.nikita.movies_shmoovies.movies
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.nikita.movies_shmoovies.R
import com.nikita.movies_shmoovies.actors.ActorInfoActivity
import com.nikita.movies_shmoovies.appModule
import com.nikita.movies_shmoovies.common.mvp.BaseMvpActivity
import com.nikita.movies_shmoovies.common.utils.findView
import com.nikita.movies_shmoovies.common.utils.inflate
import com.nikita.movies_shmoovies.common.utils.loadWithPlaceholder
import com.nikita.movies_shmoovies.common.widgets.CircleDisplay
import com.nikita.movies_shmoovies.movies.adapters.*
import kotlinx.android.synthetic.main.activity_movies_info.*
import kotlinx.android.synthetic.main.mis_header.*
import kotlinx.android.synthetic.main.movie_info.*
import kotlinx.android.synthetic.main.movie_info_about.*
class MoviesInfoActivity : BaseMvpActivity<MovieInformation>(), MoviesInfoView{
override val layout: Int
get() = R.layout.activity_movies_info
@InjectPresenter
lateinit var presenter: MovieInfoPresenter
@ProvidePresenter
fun providePresenter(): MovieInfoPresenter {
var id: String
try {
id = intent.extras.getString("id")
} catch (e: Exception) {
id = "315837"
}
return MovieInfoPresenter(appModule.movieInfoInteractor, id)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
movie_crew_recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
movie_cast_recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
movie_genres_recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
}
override fun setContent(content: MovieInformation, pagination: Boolean) {
super.setContent(content, pagination)
content_view.visibility = View.VISIBLE
if (content.movieDetails.poster_path != null){
movie_poster.loadWithPlaceholder(content.movieDetails.poster_path, R.drawable.mis_poster_placeholder)
}
if (content.movieDetails.backdrop_path != null) {
movie_background.loadWithPlaceholder(content.movieDetails.backdrop_path, R.drawable.mis_back_placeholder)
}
mis_toolbar.title = content.movieDetails.original_title
movie_year.text = content.movieDetails.release_date.substring(0,4)
movie_overview.text = content.movieDetails.overview
movie_budget.text = content.movieDetails.budget.toString()
movie_revenue.text = content.movieDetails.revenue.toString()
movie_runtime.text = content.movieDetails.runtime.toString()
movie_release.text = content.movieDetails.release_date.replace("-",".")
movie_status.text = content.movieDetails.status
movie_url.text = content.movieDetails.homepage
// TODO: REFACTOR THIS
if (content.crewAndCast.crew == null || content.crewAndCast.crew.isEmpty()){
movie_crew_recycler.adapter = CrewAdapter(listOf(ErrorContent(resources.getString(R.string.empty_list_error))))
} else {
movie_crew_recycler.adapter = CrewAdapter(content.crewAndCast.crew)
}
if (content.crewAndCast.cast == null || content.crewAndCast.cast.isEmpty()){
movie_cast_recycler.adapter = CastAdapter(listOf(ErrorContent(resources.getString(R.string.empty_list_error))))
} else {
movie_cast_recycler.adapter = CastAdapter(content.crewAndCast.cast)
}
if (content.movieDetails.genres == null || content.movieDetails.genres.isEmpty()){
movie_genres_recycler.adapter = GenresAdapter(listOf(ErrorContent(resources.getString(R.string.empty_list_error))))
} else {
movie_genres_recycler.adapter = GenresAdapter(content.movieDetails.genres)
}
if(!content.movieDetails.homepage.isEmpty()){
movie_url.setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(content.movieDetails.homepage)))
}
}
val userScore = findViewById(R.id.user_score) as CircleDisplay
userScore.visibility = View.VISIBLE
userScore.setAnimDuration(500)
userScore.setValueWidthPercent(30f)
userScore.setTextSize(14f)
userScore.setColor(resources.getColor(R.color.TMDB_green))
userScore.setDrawText(true)
userScore.setDrawInnerCircle(true)
userScore.setFormatDigits(0)
userScore.setUnit("")
userScore.setStepSize(0.5f)
userScore.showValue(content.movieDetails.vote_average*10, 100f, true)
}
// Adapter class for Cast list
inner class CastAdapter(val data: List<RecyclerItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val ERROR_VIEW = 0
val CAST_VIEW = 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
CAST_VIEW -> return CastHolder(parent.inflate(R.layout.cast_item))
ERROR_VIEW -> return ErrorHolder(parent.inflate(R.layout.emty_error_item))
else -> return ErrorHolder(parent.inflate(R.layout.emty_error_item))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType){
CAST_VIEW -> {
(holder as CastHolder).name.text = (data[position] as MovieInformation.CrewAndCast.Cast).name
holder.character.text = (data[position] as MovieInformation.CrewAndCast.Cast).character
try {
holder.image.loadWithPlaceholder((data[position] as MovieInformation.CrewAndCast.Cast).profile_path, R.drawable.mis_actor_placeholder)
} catch (e: Exception){
Log.e("CastAdapter", e.message)
}
holder.root.setOnClickListener { startActivity(
Intent(this@MoviesInfoActivity, ActorInfoActivity::class.java)
.putExtra("actor_id", (data[position] as MovieInformation.CrewAndCast.Cast).id)) }
}
ERROR_VIEW -> (holder as ErrorHolder).errorTxt.text = (data[position] as ErrorContent).errorTxt
}
}
override fun getItemViewType(position: Int): Int {
if (data[position] is RegularItem) return CAST_VIEW
if (data[position] is ErrorItem) return ERROR_VIEW
else return ERROR_VIEW
}
override fun getItemCount() = data.size
}
class CastHolder(view: View) : RecyclerView.ViewHolder(view) {
val image = view.findView<ImageView>(R.id.actor_photo)
val name = view.findView<TextView>(R.id.actor_name)
val character = view.findView<TextView>(R.id.actor_character)
val root = view.findView<LinearLayout>(R.id.cast_root)
}
}
| apache-2.0 | f145453c350faf90b355142a6cb57d62 | 44.278788 | 158 | 0.68612 | 4.37925 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/browser/PathAdapter.kt | 1 | 4352 | package org.videolan.vlc.gui.browser
import android.content.Context
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.resources.AndroidDevices
import org.videolan.vlc.viewmodels.browser.IPathOperationDelegate
import org.videolan.vlc.viewmodels.browser.PathOperationDelegate
class PathAdapter(val browser: PathAdapterListener, media: MediaWrapper) : RecyclerView.Adapter<PathAdapter.ViewHolder>() {
private val pathOperationDelegate = browser.getPathOperationDelegate()
init {
//we save Base64 encoded strings to be used in substitutions to avoid false positives if a user directory is named as the media title
// ie "SDCARD", "Internal Memory" and so on
if (media.hasStateFlags(MediaLibraryItem.FLAG_STORAGE)) PathOperationDelegate.storages.put(Uri.decode(media.uri.path), pathOperationDelegate.makePathSafe(media.title))
PathOperationDelegate.storages.put(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY, pathOperationDelegate.makePathSafe(browser.currentContext().getString(R.string.internal_memory)))
}
private val browserTitle = browser.currentContext().getString(R.string.browser)
private val otgDevice = browser.currentContext().getString(R.string.otg_device_title)
private val segments = prepareSegments(media.uri)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.browser_path_item, parent, false) as TextView)
}
override fun getItemCount() = segments.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.root.text = when {
//substitute a storage path to its name. See [replaceStoragePath]
PathOperationDelegate.storages.containsKey(Uri.parse(segments[position]).path) -> pathOperationDelegate.retrieveSafePath(PathOperationDelegate.storages.valueAt(PathOperationDelegate.storages.indexOfKey(Uri.parse(segments[position]).path)))
else -> Uri.parse(segments[position]).lastPathSegment
}
}
inner class ViewHolder(val root: TextView) : RecyclerView.ViewHolder(root) {
init {
root.setOnClickListener {
browser.backTo(adapterPosition.let {
when (it) {
0 -> "root"
else -> segments[it]
}
})
}
}
}
/**
* Splits an [Uri] in a list of string used as the adapter items
* Each item is a string representing a valid path
*
* @param uri the [Uri] that has to be split
* @return a list of strings representing the items
*/
private fun prepareSegments(uri: Uri): MutableList<String> {
val path = Uri.decode(uri.path)
val isOtg = path.startsWith("/tree/")
val string = when {
isOtg -> if (path.endsWith(':')) "" else path.substringAfterLast(':')
else -> pathOperationDelegate.replaceStoragePath(path)
}
val list: MutableList<String> = mutableListOf()
if (isOtg) list.add(otgDevice)
//list of all the path chunks
val pathParts = string.split('/').filter { it.isNotEmpty() }
for (index in pathParts.indices) {
//start creating the Uri
val currentPathUri = Uri.Builder().scheme(uri.scheme).encodedAuthority(uri.authority)
//append all the previous paths and the current one
for (i in 0..index) pathOperationDelegate.appendPathToUri(pathParts[i], currentPathUri)
list.add(currentPathUri.toString())
}
if (BuildConfig.DEBUG) list.forEach { Log.d(this::class.java.simpleName, "Added in breadcrumb: $it") }
if (browser.showRoot()) list.add(0, browserTitle)
return list
}
}
interface PathAdapterListener {
fun backTo(tag: String)
fun currentContext(): Context
fun showRoot(): Boolean
fun getPathOperationDelegate(): IPathOperationDelegate
} | gpl-2.0 | a5f54f3371171ae1b37526dbd302b0c7 | 42.53 | 251 | 0.696232 | 4.528616 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/viewholder/BaseViewHolder.kt | 1 | 3876 | package com.didichuxing.doraemonkit.widget.brvah.viewholder
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.*
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
/**
* ViewHolder 基类
*/
@Keep
open class BaseViewHolder(view: View) : RecyclerView.ViewHolder(view) {
/**
* Views indexed with their IDs
*/
private val views: SparseArray<View> = SparseArray()
/**
* 如果使用了 DataBinding 绑定 View,可调用此方法获取 [ViewDataBinding]
*
* Deprecated, Please use [BaseDataBindingHolder]
*
* @return B?
*/
@Deprecated("Please use BaseDataBindingHolder class", ReplaceWith("DataBindingUtil.getBinding(itemView)", "androidx.databinding.DataBindingUtil"))
open fun <B : ViewDataBinding> getBinding(): B? = DataBindingUtil.getBinding(itemView)
fun <T : View> getView(@IdRes viewId: Int): T {
val view = getViewOrNull<T>(viewId)
checkNotNull(view) { "No view found with id $viewId" }
return view
}
@Suppress("UNCHECKED_CAST")
fun <T : View> getViewOrNull(@IdRes viewId: Int): T? {
val view = views.get(viewId)
if (view == null) {
itemView.findViewById<T>(viewId)?.let {
views.put(viewId, it)
return it
}
}
return view as? T
}
fun <T : View> Int.findView(): T? {
return itemView.findViewById(this)
}
open fun setText(@IdRes viewId: Int, value: CharSequence?): BaseViewHolder {
getView<TextView>(viewId).text = value
return this
}
open fun setText(@IdRes viewId: Int, @StringRes strId: Int): BaseViewHolder? {
getView<TextView>(viewId).setText(strId)
return this
}
open fun setTextColor(@IdRes viewId: Int, @ColorInt color: Int): BaseViewHolder {
getView<TextView>(viewId).setTextColor(color)
return this
}
open fun setTextColorRes(@IdRes viewId: Int, @ColorRes colorRes: Int): BaseViewHolder {
getView<TextView>(viewId).setTextColor(itemView.resources.getColor(colorRes))
return this
}
open fun setImageResource(@IdRes viewId: Int, @DrawableRes imageResId: Int): BaseViewHolder {
getView<ImageView>(viewId).setImageResource(imageResId)
return this
}
open fun setImageDrawable(@IdRes viewId: Int, drawable: Drawable?): BaseViewHolder {
getView<ImageView>(viewId).setImageDrawable(drawable)
return this
}
open fun setImageBitmap(@IdRes viewId: Int, bitmap: Bitmap?): BaseViewHolder {
getView<ImageView>(viewId).setImageBitmap(bitmap)
return this
}
open fun setBackgroundColor(@IdRes viewId: Int, @ColorInt color: Int): BaseViewHolder {
getView<View>(viewId).setBackgroundColor(color)
return this
}
open fun setBackgroundResource(@IdRes viewId: Int, @DrawableRes backgroundRes: Int): BaseViewHolder {
getView<View>(viewId).setBackgroundResource(backgroundRes)
return this
}
open fun setVisible(@IdRes viewId: Int, isVisible: Boolean): BaseViewHolder {
val view = getView<View>(viewId)
view.visibility = if (isVisible) View.VISIBLE else View.INVISIBLE
return this
}
open fun setGone(@IdRes viewId: Int, isGone: Boolean): BaseViewHolder {
val view = getView<View>(viewId)
view.visibility = if (isGone) View.GONE else View.VISIBLE
return this
}
open fun setEnabled(@IdRes viewId: Int, isEnabled: Boolean): BaseViewHolder {
getView<View>(viewId).isEnabled = isEnabled
return this
}
}
| apache-2.0 | 6c4c3ac26e4ebe59a5816e5f60a84f87 | 30.735537 | 150 | 0.671094 | 4.671533 | false | false | false | false |
NextFaze/dev-fun | demo/src/main/java/com/nextfaze/devfun/demo/Base.kt | 1 | 1290 | package com.nextfaze.devfun.demo
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import com.nextfaze.devfun.demo.inject.ActivityInjector
import com.nextfaze.devfun.demo.inject.DaggerActivity
import com.nextfaze.devfun.demo.inject.DaggerFragment
import com.nextfaze.devfun.demo.kotlin.defaultTag
import com.nextfaze.devfun.demo.kotlin.findOrCreate
import com.nextfaze.devfun.function.DeveloperFunction
abstract class BaseActivity : DaggerActivity() {
override fun inject(injector: ActivityInjector) = Unit
inline fun <reified T : Fragment> setContentFragment(@IdRes containerViewId: Int = R.id.activity_fragment_view, factory: () -> T) {
supportFragmentManager.beginTransaction().replace(containerViewId, findOrCreate { factory() }, T::class.defaultTag).commit()
}
@DeveloperFunction
protected fun showToast(msg: String) =
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
abstract class BaseFragment : DaggerFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
protected fun showToast(msg: String) =
Toast.makeText(activity!!, msg, Toast.LENGTH_LONG).show()
}
| apache-2.0 | 0cce1a5baada4a0b8d11fde56beed1bc | 36.941176 | 135 | 0.764341 | 4.417808 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ParataskActions.kt | 1 | 11326 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.project
import com.eclipsesource.json.Json
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import com.eclipsesource.json.PrettyPrint
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import uk.co.nickthecoder.paratask.util.child
import java.io.*
object ParataskActions {
val nameToActionMap = mutableMapOf<String, ParataskAction>()
// ProjectWindow
val PROJECT_OPEN = ParataskAction("project.open", KeyCode.O, alt = true, tooltip = "Open Project")
val PROJECT_SAVE = ParataskAction("project.save", KeyCode.S, alt = true, tooltip = "Save Project")
val QUIT = ParataskAction("application.quit", KeyCode.Q, alt = true, label = "Quit", tooltip = "Quit Para Task")
val WINDOW_NEW = ParataskAction("window.new", KeyCode.N, control = true, tooltip = "New Window")
val TAB_NEW = ParataskAction("tab.new", KeyCode.T, control = true, label = "New Tab")
val TAB_RESTORE = ParataskAction("tab.restore", KeyCode.T, shift = true, control = true, label = "Restore Tab")
val APPLICATION_ABOUT = ParataskAction("application.about", KeyCode.F1, tooltip = "About ParaTask")
// ProjectTab
val TAB_PROPERTIES = ParataskAction("tab.properties", null, label = "Properties")
val TAB_DUPLICATE = ParataskAction("tab.duplicate", KeyCode.D, alt = true, label = "Duplicate Tab", tooltip = "Duplicate Tab")
val TAB_CLOSE = ParataskAction("tab.close", KeyCode.W, control = true, label = "Close Tab")
// HalfTab
val RESULTS_TAB_CLOSE = ParataskAction("results-tab.close", KeyCode.W, alt = true, label = "Close Results Tab")
val TOOL_STOP = ParataskAction("tool.stop", KeyCode.ESCAPE, shift = true, tooltip = "Stop the Tool")
val TOOL_RUN = ParataskAction("tool.run", KeyCode.F5, tooltip = "(Re) Run the Tool")
val TOOL_SELECT = ParataskAction("tool.select", KeyCode.HOME, control = true, tooltip = "Select a Tool")
val TOOL_CLOSE = ParataskAction("tool.close", KeyCode.W, control = true, shift = true, tooltip = "Close Tool")
val HISTORY_BACK = ParataskAction("history.back", KeyCode.LEFT, alt = true, tooltip = "Back")
val HISTORY_FORWARD = ParataskAction("history.forward", KeyCode.RIGHT, alt = true, tooltip = "Forward")
val TAB_MERGE_TOGGLE = ParataskAction("tab.merge.toggle", null, tooltip = "Split / Merge with the Tab to the right")
val TAB_SPLIT_TOGGLE = ParataskAction("tab.split.toggle", KeyCode.F3, tooltip = "Split/Un-Split")
val SIDE_PANEL_TOGGLE = ParataskAction("side.panel.toggle", KeyCode.F9, tooltip = "Show/Hide the side panel")
val OPTION_RUN = ParataskAction("actions.run", KeyCode.ENTER)
val OPTION_RUN_NEW_TAB = ParataskAction("actions.run.new.tab", KeyCode.ENTER, shift = true)
val OPTION_PROMPT = ParataskAction("actions.run", KeyCode.F8)
val OPTION_PROMPT_NEW_TAB = ParataskAction("actions.run.new.tab", KeyCode.F8, shift = true)
val PARAMETERS_SHOW = ParataskAction("parameters.show", KeyCode.P, control = true, label = "Show Parameters")
val RESULTS_SHOW = ParataskAction("results.show", KeyCode.R, control = true, label = "Show Results")
// Table
val NEXT_ROW = ParataskAction("row.next", KeyCode.DOWN)
val PREV_ROW = ParataskAction("row.previous", KeyCode.UP)
val SELECT_ROW_DOWN = ParataskAction("row.select.down", KeyCode.DOWN, shift = true)
val SELECT_ROW_UP = ParataskAction("row.select.up", KeyCode.UP, shift = true)
// DirectoryTool
val DIRECTORY_EDIT_PLACES = ParataskAction("directory.places.edit", null, label = "Edit", tooltip = "Edit Places")
val DIRECTORY_CHANGE_PLACES = ParataskAction("directory.places.change", null, label = "Change Places File")
val DIRECTORY_CHANGE_TREE_ROOT = ParataskAction("director.change.root", null, label = "Change Root", tooltip = "Change tree's root directory")
// EditorTool
val EDIT_FIND = ParataskAction("edit.find", KeyCode.F, control = true, tooltip = "Find")
val EDIT_REPLACE = ParataskAction("edit.replace", KeyCode.H, control = true, tooltip = "Replace")
// General
val CONTEXT_MENU = ParataskAction("context.menu", KeyCode.CONTEXT_MENU)
val FILE_SAVE = ParataskAction("file.save", KeyCode.S, control = true, tooltip = "Save")
val EDIT_CUT = ParataskAction("edit.cut", KeyCode.X, control = true, tooltip = "Cut")
val EDIT_COPY = ParataskAction("edit.copy", KeyCode.C, control = true, tooltip = "Copy")
val EDIT_PASTE = ParataskAction("edit.paste", KeyCode.V, control = true, tooltip = "Paste")
val EDIT_UNDO = ParataskAction("edit.undo", KeyCode.Z, control = true, tooltip = "Undo")
val EDIT_REDO = ParataskAction("edit.redo", KeyCode.Z, shift = true, control = true, tooltip = "Redo")
val ESCAPE = ParataskAction("escape", KeyCode.ESCAPE)
val SELECT_ALL = ParataskAction("select-all", KeyCode.A, control = true)
val SELECT_NONE = ParataskAction("select-all", KeyCode.A, control = true, shift = true)
// GlobalShortcuts
val NEXT_MAJOR_TAB = ParataskAction("tab.major.next", KeyCode.CLOSE_BRACKET, control = true)
val PREV_MAJOR_TAB = ParataskAction("tab.major.prev", KeyCode.OPEN_BRACKET, control = true)
val NEXT_MINOR_TAB = ParataskAction("tab.minor.next", KeyCode.CLOSE_BRACKET, control = true, shift = true)
val PREV_MINOR_TAB = ParataskAction("tab.minor.prev", KeyCode.OPEN_BRACKET, control = true, shift = true)
val FOCUS_OPTION = ParataskAction("focus.option", KeyCode.F10)
val FOCUS_RESULTS = ParataskAction("focus.results", KeyCode.F10, control = true)
val FOCUS_HEADER = ParataskAction("focus.header", KeyCode.F10, shift = true)
val FOCUS_OTHER_SPLIT = ParataskAction("focus.other.split", KeyCode.F3, control = true)
val MAJOR_TAB_1 = ParataskAction("tab.major.1", KeyCode.DIGIT1, control = true)
val MAJOR_TAB_2 = ParataskAction("tab.major.2", KeyCode.DIGIT2, control = true)
val MAJOR_TAB_3 = ParataskAction("tab.major.3", KeyCode.DIGIT3, control = true)
val MAJOR_TAB_4 = ParataskAction("tab.major.4", KeyCode.DIGIT4, control = true)
val MAJOR_TAB_5 = ParataskAction("tab.major.5", KeyCode.DIGIT5, control = true)
val MAJOR_TAB_6 = ParataskAction("tab.major.6", KeyCode.DIGIT6, control = true)
val MAJOR_TAB_7 = ParataskAction("tab.major.7", KeyCode.DIGIT7, control = true)
val MAJOR_TAB_8 = ParataskAction("tab.major.8", KeyCode.DIGIT8, control = true)
val MAJOR_TAB_9 = ParataskAction("tab.major.9", KeyCode.DIGIT9, control = true)
val MAJOR_TABS = listOf(MAJOR_TAB_1, MAJOR_TAB_2, MAJOR_TAB_3, MAJOR_TAB_4, MAJOR_TAB_5, MAJOR_TAB_6, MAJOR_TAB_7, MAJOR_TAB_8, MAJOR_TAB_9)
val MINOR_TAB_1 = ParataskAction("tab.minor.1", KeyCode.DIGIT1, control = true, shift = true)
val MINOR_TAB_2 = ParataskAction("tab.minor.2", KeyCode.DIGIT2, control = true, shift = true)
val MINOR_TAB_3 = ParataskAction("tab.minor.3", KeyCode.DIGIT3, control = true, shift = true)
val MINOR_TAB_4 = ParataskAction("tab.minor.4", KeyCode.DIGIT4, control = true, shift = true)
val MINOR_TAB_5 = ParataskAction("tab.minor.5", KeyCode.DIGIT5, control = true, shift = true)
val MINOR_TAB_6 = ParataskAction("tab.minor.6", KeyCode.DIGIT6, control = true, shift = true)
val MINOR_TAB_7 = ParataskAction("tab.minor.7", KeyCode.DIGIT7, control = true, shift = true)
val MINOR_TAB_8 = ParataskAction("tab.minor.8", KeyCode.DIGIT8, control = true, shift = true)
val MINOR_TAB_9 = ParataskAction("tab.minor.9", KeyCode.DIGIT9, control = true, shift = true)
val MINOR_TABS = listOf(MINOR_TAB_1, MINOR_TAB_2, MINOR_TAB_3, MINOR_TAB_4, MINOR_TAB_5, MINOR_TAB_6, MINOR_TAB_7, MINOR_TAB_8, MINOR_TAB_9)
init {
load()
}
fun add(action: ParataskAction) {
nameToActionMap.put(action.name, action)
}
fun shortcutPrefencesFile() = Preferences.configDirectory.child("shortcuts.json")
fun save() {
val jroot = JsonObject()
val jshortcuts = JsonArray()
nameToActionMap.values.forEach { action ->
if (action.isChanged()) {
val jshortcut = JsonObject()
jshortcut.add("name", action.name)
jshortcut.add("keycode", action.keyCodeCombination?.code?.toString() ?: "")
addModifier(jshortcut, "control", action.keyCodeCombination?.control)
addModifier(jshortcut, "shift", action.keyCodeCombination?.shift)
addModifier(jshortcut, "alt", action.keyCodeCombination?.alt)
jshortcuts.add(jshortcut)
}
}
jroot.add("shortcuts", jshortcuts)
BufferedWriter(OutputStreamWriter(FileOutputStream(shortcutPrefencesFile()))).use {
jroot.writeTo(it, PrettyPrint.indentWithSpaces(4))
}
}
fun addModifier(jparent: JsonObject, name: String, mod: KeyCombination.ModifierValue?) {
mod?.let { jparent.add(name, mod.toString()) }
}
fun load() {
val file = shortcutPrefencesFile()
if (!file.exists()) {
return
}
val jroot = Json.parse(InputStreamReader(FileInputStream(file))).asObject()
val jshortcutsObj = jroot.get("shortcuts")
jshortcutsObj?.let {
val jshortcuts = it.asArray()
jshortcuts.forEach {
val jshortcut = it.asObject()
val name = jshortcut.getString("name", "")
val action = nameToActionMap[name]
action?.let {
val keyCodeS = jshortcut.getString("keycode", "")
val controlS = jshortcut.getString("control", "ANY")
val shiftS = jshortcut.getString("shift", "ANY")
val altS = jshortcut.getString("alt", "ANY")
val control = KeyCombination.ModifierValue.valueOf(controlS)
val shift = KeyCombination.ModifierValue.valueOf(shiftS)
val alt = KeyCombination.ModifierValue.valueOf(altS)
if (keyCodeS == "") {
it.keyCodeCombination = null
} else {
val keyCode = KeyCode.valueOf(keyCodeS)
it.keyCodeCombination = KeyCodeCombination(
keyCode,
control,
shift,
alt,
KeyCombination.ModifierValue.UP,
KeyCombination.ModifierValue.UP)
}
}
}
}
}
}
| gpl-3.0 | 4bfc5ece9e1fcfc8d5b90a9d9707e84d | 49.5625 | 146 | 0.662811 | 3.84584 | false | false | false | false |
michaelgallacher/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 3 | 2899 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic
import com.intellij.CommonBundle
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun showJetBrainsAccountDialog(parent: Component, project: Project? = null): DialogWrapper {
val credentials = ErrorReportConfigurable.getCredentials()
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.password?.toString())
// if no user name - never stored and so, defaults to remember. if user name set, but no password, so, previously was stored without password
val rememberCheckBox = CheckBox(CommonBundle.message("checkbox.remember.password"), selected = credentials?.userName == null || !credentials?.password.isNullOrEmpty())
val panel = panel {
noteRow("Login to JetBrains Account to get notified when the submitted\nexceptions are fixed.")
row("Username:") { userField() }
row("Password:") { passwordField() }
row {
rememberCheckBox()
right {
link("Forgot password?") { BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=${userField.text.trim().encodeUrlQueryParameter()}") }
}
}
noteRow("""Do not have an account? <a href="https://account.jetbrains.com/login">Sign Up</a>""")
}
return dialog(
title = DiagnosticBundle.message("error.report.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null) {
val userName = userField.text
if (!userName.isNullOrBlank()) {
PasswordSafe.getInstance().set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, if (rememberCheckBox.isSelected) passwordField.password else null))
}
}
} | apache-2.0 | afe71698d8259461c7a525db0b6aaa1e | 42.939394 | 196 | 0.754743 | 4.43951 | false | false | false | false |
pedroSG94/rtmp-streamer-java | rtmp/src/main/java/com/pedro/rtmp/amf/v3/Amf3Double.kt | 2 | 1425 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtmp.amf.v3
import com.pedro.rtmp.utils.readUntil
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import kotlin.jvm.Throws
/**
* Created by pedro on 29/04/21.
*/
class Amf3Double(var value: Double = 0.0): Amf3Data() {
@Throws(IOException::class)
override fun readBody(input: InputStream) {
val bytes = ByteArray(getSize())
input.readUntil(bytes)
val value = ByteBuffer.wrap(bytes).long
this.value = Double.Companion.fromBits(value)
}
@Throws(IOException::class)
override fun writeBody(output: OutputStream) {
val byteBuffer = ByteBuffer.allocate(getSize()).putLong(value.toRawBits())
output.write(byteBuffer.array())
}
override fun getType(): Amf3Type = Amf3Type.DOUBLE
override fun getSize(): Int = 8
} | apache-2.0 | d1083cbae148ada204c3cdf516c14fad | 28.708333 | 78 | 0.733333 | 3.851351 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/LlvmDeclarations.kt | 1 | 15318 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.*
import llvm.*
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
internal fun createLlvmDeclarations(context: Context): LlvmDeclarations {
val generator = DeclarationsGeneratorVisitor(context)
context.ir.irModule.acceptChildrenVoid(generator)
return with(generator) {
LlvmDeclarations(
functions, classes, fields, staticFields, uniques
)
}
}
// Please note, that llvmName is part of the ABI, and cannot be liberally changed.
enum class UniqueKind(val llvmName: String) {
UNIT("theUnitInstance"),
EMPTY_ARRAY("theEmptyArray")
}
internal class LlvmDeclarations(
private val functions: Map<IrFunction, FunctionLlvmDeclarations>,
private val classes: Map<IrClass, ClassLlvmDeclarations>,
private val fields: Map<IrField, FieldLlvmDeclarations>,
private val staticFields: Map<IrField, StaticFieldLlvmDeclarations>,
private val unique: Map<UniqueKind, UniqueLlvmDeclarations>) {
fun forFunction(function: IrFunction) = forFunctionOrNull(function) ?: with(function){error("$name in $file/${parent.fqNameForIrSerialization}")}
fun forFunctionOrNull(function: IrFunction) = functions[function]
fun forClass(irClass: IrClass) = classes[irClass] ?:
error(irClass.descriptor.toString())
fun forField(field: IrField) = fields[field] ?:
error(field.descriptor.toString())
fun forStaticField(field: IrField) = staticFields[field] ?:
error(field.descriptor.toString())
fun forSingleton(irClass: IrClass) = forClass(irClass).singletonDeclarations ?:
error(irClass.descriptor.toString())
fun forUnique(kind: UniqueKind) = unique[kind] ?: error("No unique $kind")
}
internal class ClassLlvmDeclarations(
val bodyType: LLVMTypeRef,
val typeInfoGlobal: StaticData.Global,
val writableTypeInfoGlobal: StaticData.Global?,
val typeInfo: ConstPointer,
val singletonDeclarations: SingletonLlvmDeclarations?,
val objCDeclarations: KotlinObjCClassLlvmDeclarations?)
internal class SingletonLlvmDeclarations(val instanceStorage: AddressAccess)
internal class KotlinObjCClassLlvmDeclarations(
val classInfoGlobal: StaticData.Global,
val bodyOffsetGlobal: StaticData.Global
)
internal class FunctionLlvmDeclarations(val llvmFunction: LLVMValueRef)
internal class FieldLlvmDeclarations(val index: Int, val classBodyType: LLVMTypeRef)
internal class StaticFieldLlvmDeclarations(val storageAddressAccess: AddressAccess)
internal class UniqueLlvmDeclarations(val pointer: ConstPointer)
private fun ContextUtils.createClassBodyType(name: String, fields: List<IrField>): LLVMTypeRef {
val fieldTypes = listOf(runtime.objHeaderType) + fields.map { getLLVMType(it.type) }
// TODO: consider adding synthetic ObjHeader field to Any.
val classType = LLVMStructCreateNamed(LLVMGetModuleContext(context.llvmModule), name)!!
// LLVMStructSetBody expects the struct to be properly aligned and will insert padding accordingly. In our case
// `allocInstance` returns 16x + 8 address, i.e. always misaligned for vector types. Workaround is to use packed struct.
val hasBigAlignment = fields.any { LLVMABIAlignmentOfType(context.llvm.runtime.targetData, getLLVMType(it.type)) > 8 }
val packed = if (hasBigAlignment) 1 else 0
LLVMStructSetBody(classType, fieldTypes.toCValues(), fieldTypes.size, packed)
return classType
}
private class DeclarationsGeneratorVisitor(override val context: Context) :
IrElementVisitorVoid, ContextUtils {
val functions = mutableMapOf<IrFunction, FunctionLlvmDeclarations>()
val classes = mutableMapOf<IrClass, ClassLlvmDeclarations>()
val fields = mutableMapOf<IrField, FieldLlvmDeclarations>()
val staticFields = mutableMapOf<IrField, StaticFieldLlvmDeclarations>()
val uniques = mutableMapOf<UniqueKind, UniqueLlvmDeclarations>()
private class Namer(val prefix: String) {
private val names = mutableMapOf<IrDeclaration, Name>()
private val counts = mutableMapOf<FqName, Int>()
fun getName(parent: FqName, declaration: IrDeclaration): Name {
return names.getOrPut(declaration) {
val count = counts.getOrDefault(parent, 0) + 1
counts[parent] = count
Name.identifier(prefix + count)
}
}
}
val objectNamer = Namer("object-")
private fun getLocalName(parent: FqName, declaration: IrDeclaration): Name {
if (declaration.isAnonymousObject) {
return objectNamer.getName(parent, declaration)
}
return declaration.nameForIrSerialization
}
private fun getFqName(declaration: IrDeclaration): FqName {
val parent = declaration.parent
val parentFqName = when (parent) {
is IrPackageFragment -> parent.fqName
is IrDeclaration -> getFqName(parent)
else -> error(parent)
}
val localName = getLocalName(parentFqName, declaration)
return parentFqName.child(localName)
}
/**
* Produces the name to be used for non-exported LLVM declarations corresponding to [declaration].
*
* Note: since these declarations are going to be private, the name is only required not to clash with any
* exported declarations.
*/
private fun qualifyInternalName(declaration: IrDeclaration): String {
return getFqName(declaration).asString() + "#internal"
}
override fun visitElement(element: IrElement) {
element.acceptChildrenVoid(this)
}
override fun visitClass(declaration: IrClass) {
if (declaration.requiresRtti()) {
this.classes[declaration] = createClassDeclarations(declaration)
}
super.visitClass(declaration)
}
private fun createClassDeclarations(declaration: IrClass): ClassLlvmDeclarations {
val internalName = qualifyInternalName(declaration)
val fields = context.getLayoutBuilder(declaration).fields
val bodyType = createClassBodyType("kclassbody:$internalName", fields)
val typeInfoPtr: ConstPointer
val typeInfoGlobal: StaticData.Global
val typeInfoSymbolName = if (declaration.isExported()) {
declaration.typeInfoSymbolName
} else {
"ktype:$internalName"
}
if (declaration.typeInfoHasVtableAttached) {
// Create the special global consisting of TypeInfo and vtable.
val typeInfoGlobalName = "ktypeglobal:$internalName"
val typeInfoWithVtableType = structType(
runtime.typeInfoType,
LLVMArrayType(int8TypePtr, context.getLayoutBuilder(declaration).vtableEntries.size)!!
)
typeInfoGlobal = staticData.createGlobal(typeInfoWithVtableType, typeInfoGlobalName, isExported = false)
val llvmTypeInfoPtr = LLVMAddAlias(context.llvmModule,
kTypeInfoPtr,
typeInfoGlobal.pointer.getElementPtr(0).llvm,
typeInfoSymbolName)!!
if (declaration.isExported()) {
if (llvmTypeInfoPtr.name != typeInfoSymbolName) {
// So alias name has been mangled by LLVM to avoid name clash.
throw IllegalArgumentException("Global '$typeInfoSymbolName' already exists")
}
} else {
LLVMSetLinkage(llvmTypeInfoPtr, LLVMLinkage.LLVMInternalLinkage)
}
typeInfoPtr = constPointer(llvmTypeInfoPtr)
} else {
typeInfoGlobal = staticData.createGlobal(runtime.typeInfoType,
typeInfoSymbolName,
isExported = declaration.isExported())
typeInfoPtr = typeInfoGlobal.pointer
}
if (declaration.isUnit() || declaration.isKotlinArray())
createUniqueDeclarations(declaration, typeInfoPtr, bodyType)
val singletonDeclarations = if (declaration.kind.isSingleton) {
createSingletonDeclarations(declaration)
} else {
null
}
val objCDeclarations = if (declaration.isKotlinObjCClass()) {
createKotlinObjCClassDeclarations(declaration)
} else {
null
}
val writableTypeInfoType = runtime.writableTypeInfoType
val writableTypeInfoGlobal = if (writableTypeInfoType == null) {
null
} else if (declaration.isExported()) {
val name = declaration.writableTypeInfoSymbolName
staticData.createGlobal(writableTypeInfoType, name, isExported = true).also {
it.setLinkage(LLVMLinkage.LLVMCommonLinkage) // Allows to be replaced by other bitcode module.
}
} else {
staticData.createGlobal(writableTypeInfoType, "")
}.also {
it.setZeroInitializer()
}
return ClassLlvmDeclarations(bodyType, typeInfoGlobal, writableTypeInfoGlobal, typeInfoPtr,
singletonDeclarations, objCDeclarations)
}
private fun createUniqueDeclarations(
irClass: IrClass, typeInfoPtr: ConstPointer, bodyType: LLVMTypeRef) {
when {
irClass.isUnit() -> {
uniques[UniqueKind.UNIT] =
UniqueLlvmDeclarations(staticData.createUniqueInstance(UniqueKind.UNIT, bodyType, typeInfoPtr))
}
irClass.isKotlinArray() -> {
uniques[UniqueKind.EMPTY_ARRAY] =
UniqueLlvmDeclarations(staticData.createUniqueInstance(UniqueKind.EMPTY_ARRAY, bodyType, typeInfoPtr))
}
else -> TODO("Unsupported unique $irClass")
}
}
private fun createSingletonDeclarations(irClass: IrClass): SingletonLlvmDeclarations? {
if (irClass.isUnit()) {
return null
}
val storageKind = irClass.storageKind(context)
val threadLocal = storageKind == ObjectStorageKind.THREAD_LOCAL
val isExported = irClass.isExported()
val symbolName = if (isExported) {
irClass.globalObjectStorageSymbolName
} else {
"kobjref:" + qualifyInternalName(irClass)
}
val instanceAddress = if (threadLocal) {
addKotlinThreadLocal(symbolName, getLLVMType(irClass.defaultType))
} else {
addKotlinGlobal(symbolName, getLLVMType(irClass.defaultType), isExported)
}
return SingletonLlvmDeclarations(instanceAddress)
}
private fun createKotlinObjCClassDeclarations(irClass: IrClass): KotlinObjCClassLlvmDeclarations {
val internalName = qualifyInternalName(irClass)
val isExported = irClass.isExported()
val classInfoSymbolName = if (isExported) {
irClass.kotlinObjCClassInfoSymbolName
} else {
"kobjcclassinfo:$internalName"
}
val classInfoGlobal = staticData.createGlobal(
context.llvm.runtime.kotlinObjCClassInfo,
classInfoSymbolName,
isExported = isExported
).apply {
setConstant(true)
}
val bodyOffsetGlobal = staticData.createGlobal(int32Type, "kobjcbodyoffs:$internalName")
return KotlinObjCClassLlvmDeclarations(classInfoGlobal, bodyOffsetGlobal)
}
override fun visitField(declaration: IrField) {
super.visitField(declaration)
val containingClass = declaration.parent as? IrClass
if (containingClass != null) {
if (!containingClass.requiresRtti()) return
val classDeclarations = this.classes[containingClass] ?:
error(containingClass.descriptor.toString())
val allFields = context.getLayoutBuilder(containingClass).fields
this.fields[declaration] = FieldLlvmDeclarations(
allFields.indexOf(declaration) + 1, // First field is ObjHeader.
classDeclarations.bodyType
)
} else {
// Fields are module-private, so we use internal name:
val name = "kvar:" + qualifyInternalName(declaration)
val storage = if (declaration.storageKind == FieldStorageKind.THREAD_LOCAL) {
addKotlinThreadLocal(name, getLLVMType(declaration.type))
} else {
addKotlinGlobal(name, getLLVMType(declaration.type), isExported = false)
}
this.staticFields[declaration] = StaticFieldLlvmDeclarations(storage)
}
}
override fun visitFunction(declaration: IrFunction) {
super.visitFunction(declaration)
if (!declaration.isReal) return
val llvmFunctionType = getLlvmFunctionType(declaration)
if ((declaration is IrConstructor && declaration.isObjCConstructor)) {
return
}
val llvmFunction = if (declaration.isExternal) {
if (declaration.isTypedIntrinsic || declaration.isObjCBridgeBased()
// All call-sites to external accessors to interop properties
// are lowered by InteropLowering.
|| (declaration.isAccessor && declaration.isFromMetadataInteropLibrary())
|| declaration.annotations.hasAnnotation(RuntimeNames.cCall)) return
context.llvm.externalFunction(declaration.symbolName, llvmFunctionType,
// Assume that `external fun` is defined in native libs attached to this module:
origin = declaration.llvmSymbolOrigin,
independent = declaration.hasAnnotation(RuntimeNames.independent)
)
} else {
val symbolName = if (declaration.isExported()) {
declaration.symbolName.also {
if (declaration.name.asString() != "main") {
assert(LLVMGetNamedFunction(context.llvm.llvmModule, it) == null) { it }
} else {
// As a workaround, allow `main` functions to clash because frontend accepts this.
// See [OverloadResolver.isTopLevelMainInDifferentFiles] usage.
}
}
} else {
"kfun:" + qualifyInternalName(declaration)
}
val function = LLVMAddFunction(context.llvmModule, symbolName, llvmFunctionType)!!
addLlvmAttributes(context, declaration, function)
function
}
this.functions[declaration] = FunctionLlvmDeclarations(llvmFunction)
}
}
| apache-2.0 | 34de626d3b9163a9f843e0f02ce025ed | 39.416887 | 149 | 0.663533 | 5.518012 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/search/dsl/SearchQueryDsl.kt | 1 | 658 | package net.nemerosa.ontrack.model.search.dsl
import net.nemerosa.ontrack.model.search.*
/**
* DSL marker for the search DSL
*/
@DslMarker
annotation class SearchQueryDsl
@SearchQueryDsl
fun query(dsl: SearchQueryDslBuilder.() -> SearchQuery): SearchQuery = SearchQueryDslBuilder().dsl()
@SearchQueryDsl
class SearchQueryDslBuilder {
infix fun String.eq(any: Any): SearchQuery = SearchEqQuery(this, any)
infix fun String.gt(any: Any): SearchQuery = SearchGtQuery(this, any)
infix fun String.lt(any: Any): SearchQuery = SearchLtQuery(this, any)
infix fun SearchQuery.or(other: SearchQuery): SearchQuery = SearchOrQuery(this, other)
} | mit | 3daec074f62a3703b45a91b7147a2523 | 26.458333 | 100 | 0.755319 | 3.870588 | false | false | false | false |
RedstonerServer/Parcels | src/main/kotlin/io/dico/parcels2/storage/migration/plotme/PlotmeTables.kt | 1 | 1125 | package io.dico.parcels2.storage.migration.plotme
import org.jetbrains.exposed.sql.Table
class PlotmeTables(val uppercase: Boolean) {
fun String.toCorrectCase() = if (uppercase) this else toLowerCase()
val PlotmePlots = PlotmePlotsT()
val PlotmeAllowed = PlotmeAllowedT()
val PlotmeDenied = PlotmeDeniedT()
inner abstract class PlotmeTable(name: String) : Table(name) {
val px = integer("idX").primaryKey()
val pz = integer("idZ").primaryKey()
val world_name = varchar("world", 32).primaryKey()
}
inner abstract class PlotmePlotPlayerMap(name: String) : PlotmeTable(name) {
val player_name = varchar("player", 32)
val player_uuid = blob("playerid").nullable()
}
inner class PlotmePlotsT : PlotmeTable("plotmePlots".toCorrectCase()) {
val owner_name = varchar("owner", 32)
val owner_uuid = blob("ownerid").nullable()
}
inner class PlotmeAllowedT : PlotmePlotPlayerMap("plotmeAllowed".toCorrectCase())
inner class PlotmeDeniedT : PlotmePlotPlayerMap("plotmeDenied".toCorrectCase())
}
| gpl-2.0 | f58e02da7c102db8f09e3d8529dff281 | 34.290323 | 85 | 0.671111 | 3.629032 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/quickActions/QuickActionsActivity.kt | 1 | 3979 | package be.florien.anyflow.feature.quickActions
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import be.florien.anyflow.R
import be.florien.anyflow.data.view.Song
import be.florien.anyflow.databinding.ActivityQuickActionsBinding
import be.florien.anyflow.extension.anyFlowApp
import be.florien.anyflow.extension.startActivity
import be.florien.anyflow.feature.connect.ConnectActivity
import be.florien.anyflow.feature.player.songlist.InfoFragment
import be.florien.anyflow.feature.player.songlist.SongInfoActions
import be.florien.anyflow.injection.AnyFlowViewModelFactory
import be.florien.anyflow.injection.QuickActionsComponent
import be.florien.anyflow.injection.ViewModelFactoryHolder
import javax.inject.Inject
class QuickActionsActivity : AppCompatActivity(), ViewModelFactoryHolder {
private lateinit var binding: ActivityQuickActionsBinding
private lateinit var activityComponent: QuickActionsComponent
private lateinit var viewModel: InfoActionsSelectionViewModel
@Inject
lateinit var viewModelFactory: AnyFlowViewModelFactory
private val fakeComponent = object : QuickActionsComponent {
override fun inject(quickActionsActivity: QuickActionsActivity) {}
}
override fun onCreate(savedInstanceState: Bundle?) {
val component = anyFlowApp.userComponent
?.quickActionsComponentBuilder()
?.build()
activityComponent = if (component != null) {
component
} else {
startActivity(ConnectActivity::class)
finish()
fakeComponent
}
super.onCreate(savedInstanceState)
if (activityComponent == fakeComponent) {
return
}
activityComponent.inject(this)
viewModel = ViewModelProvider(this, viewModelFactory)
.get(InfoActionsSelectionViewModel::class.java)
.apply {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
val itemWidth = resources.getDimensionPixelSize(R.dimen.minClickableSize)
val margin = resources.getDimensionPixelSize(R.dimen.smallDimen)
val itemFullWidth = itemWidth + margin + margin
maxItems = (width / itemFullWidth) - 1
}
binding = DataBindingUtil.setContentView(this, R.layout.activity_quick_actions)
binding.lifecycleOwner = this
binding.viewModel = viewModel
initToolbar()
val fragment = supportFragmentManager.findFragmentByTag(InfoFragment::class.java.simpleName)
if (fragment == null) {
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container_view, InfoFragment(
Song(
SongInfoActions.DUMMY_SONG_ID,
getString(R.string.info_title),
getString(R.string.info_artist),
getString(R.string.info_album),
getString(R.string.info_album_artist),
120,
"",
"",
getString(R.string.info_genre)
)
), InfoFragment::class.java.simpleName)
.commit()
}
}
override fun getFactory() = viewModelFactory
private fun initToolbar() {
setSupportActionBar(binding.toolbar)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_up)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.toolbar.setNavigationOnClickListener {
if (!supportFragmentManager.popBackStackImmediate()) {
finish()
}
}
}
} | gpl-3.0 | e3d0b73b1d02d2aaa60fed3c06fd91ed | 38.8 | 100 | 0.66097 | 5.565035 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/test/java/net/mm2d/upnp/internal/impl/IconBuilderTest.kt | 1 | 3181 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.impl
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@Suppress("TestFunctionName", "NonAsciiCharacters")
@RunWith(JUnit4::class)
class IconBuilderTest {
@Test
fun build() {
val mimeType = "mimeType"
val height = 200
val width = 300
val depth = 24
val url = "http://192.168.0.1/"
val icon = IconImpl.Builder()
.setMimeType(mimeType)
.setWidth(width.toString())
.setHeight(height.toString())
.setDepth(depth.toString())
.setUrl(url)
.build()
assertThat(icon.mimeType).isEqualTo(mimeType)
assertThat(icon.width).isEqualTo(width)
assertThat(icon.height).isEqualTo(height)
assertThat(icon.depth).isEqualTo(depth)
assertThat(icon.url).isEqualTo(url)
}
@Test(expected = IllegalStateException::class)
fun build_mimeTypeなし() {
val height = 200
val width = 300
val depth = 24
val url = "http://192.168.0.1/"
IconImpl.Builder()
.setWidth(width.toString())
.setHeight(height.toString())
.setDepth(depth.toString())
.setUrl(url)
.build()
}
@Test(expected = IllegalStateException::class)
fun build_width異常() {
val mimeType = "mimeType"
val height = 200
val depth = 24
val url = "http://192.168.0.1/"
IconImpl.Builder()
.setMimeType(mimeType)
.setWidth("width")
.setHeight(height.toString())
.setDepth(depth.toString())
.setUrl(url)
.build()
}
@Test(expected = IllegalStateException::class)
fun build_height異常() {
val mimeType = "mimeType"
val width = 300
val depth = 24
val url = "http://192.168.0.1/"
IconImpl.Builder()
.setMimeType(mimeType)
.setWidth(width.toString())
.setHeight("height")
.setDepth(depth.toString())
.setUrl(url)
.build()
}
@Test(expected = IllegalStateException::class)
fun build_depth異常() {
val mimeType = "mimeType"
val height = 200
val width = 300
val url = "http://192.168.0.1/"
IconImpl.Builder()
.setMimeType(mimeType)
.setWidth(width.toString())
.setHeight(height.toString())
.setDepth("depth")
.setUrl(url)
.build()
}
@Test(expected = IllegalStateException::class)
fun build_urlなし() {
val mimeType = "mimeType"
val height = 200
val width = 300
val depth = 24
IconImpl.Builder()
.setMimeType(mimeType)
.setWidth(width.toString())
.setHeight(height.toString())
.setDepth(depth.toString())
.build()
}
}
| mit | a1ae99471cc14dbb87ec96a3c14db4fa | 27.151786 | 53 | 0.555661 | 4.192819 | false | true | false | false |
stoman/competitive-programming | problems/2020adventofcode12a/submissions/accepted/Stefan.kt | 2 | 686 | import java.util.*
import kotlin.math.abs
fun main() {
val directions = listOf(Pair(1, 0), Pair(0, -1), Pair(-1, 0), Pair(0, 1))
val s = Scanner(System.`in`)
var dir = 0
var x = 0
var y = 0
while (s.hasNext()) {
val line = s.next()
val command = line[0]
val arg = if (line.length > 1) line.drop(1).toInt() else 0
when (command) {
'E' -> x += arg
'S' -> y -= arg
'W' -> x -= arg
'N' -> y += arg
'L' -> dir -= arg / 90
'R' -> dir += arg / 90
'F' -> {
x += directions[dir % directions.size].first * arg
y += directions[dir % directions.size].second * arg
}
}
}
println(abs(x) + abs(y))
}
| mit | 81f80cd43da45f79ca502ac3338592af | 23.5 | 75 | 0.488338 | 2.944206 | false | false | false | false |
permissions-dispatcher/PermissionsDispatcher | processor/src/main/kotlin/permissions/dispatcher/processor/util/Validators.kt | 2 | 5132 | package permissions.dispatcher.processor.util
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.processor.ProcessorUnit
import permissions.dispatcher.processor.RuntimePermissionsElement
import permissions.dispatcher.processor.TYPE_UTILS
import permissions.dispatcher.processor.exception.*
import java.util.*
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
private const val WRITE_SETTINGS = "android.permission.WRITE_SETTINGS"
private const val SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW"
/**
* Obtains the [ProcessorUnit] implementation for the provided element.
* Raises an exception if no suitable implementation exists
*/
fun <K> findAndValidateProcessorUnit(units: List<ProcessorUnit<K>>, element: Element): ProcessorUnit<K> {
val type = element.asType()
try {
return units.first { type.isSubtypeOf(it.getTargetType()) }
} catch (ex: NoSuchElementException) {
throw WrongClassException(type)
}
}
/**
* Checks the elements in the provided list annotated with an annotation against duplicate values.
* <p>
* Raises an exception if any annotation value is found multiple times.
*/
fun <A : Annotation> checkDuplicatedValue(items: List<ExecutableElement>, annotationClass: Class<A>) {
val allItems: HashSet<List<String>> = hashSetOf()
items.forEach {
val permissionValue = it.getAnnotation(annotationClass).permissionValue().sorted()
if (allItems.contains(permissionValue)) {
throw DuplicatedValueException(permissionValue, it, annotationClass)
} else {
allItems.add(permissionValue)
}
}
}
/**
* Checks the elements in the provided list for elements.
* <p>
* Raises an exception if it doesn't contain any elements.
*/
fun <A : Annotation> checkNotEmpty(items: List<ExecutableElement>, rpe: RuntimePermissionsElement, annotationClass: Class<A>) {
if (items.isEmpty()) {
throw NoAnnotatedMethodsException(rpe, annotationClass)
}
}
/**
* Checks the elements in the provided list annotated with an annotation
* against private modifiers.
* <p>
* Raises an exception if any element contains the "private" modifier.
*/
fun <A : Annotation> checkPrivateMethods(items: List<ExecutableElement>, annotationClass: Class<A>) {
items.forEach {
if (it.modifiers.contains(Modifier.PRIVATE)) {
throw PrivateMethodException(it, annotationClass)
}
}
}
/**
* Checks the return type of the elements in the provided list.
* <p>
* Raises an exception if any element specifies a return type other than 'void'.
*/
fun checkMethodSignature(items: List<ExecutableElement>) {
items.forEach {
// Allow 'void' return type only
if (it.returnType.kind != TypeKind.VOID) {
throw WrongReturnTypeException(it)
}
// Allow methods without 'throws' declaration only
if (it.thrownTypes.isNotEmpty()) {
throw NoThrowsAllowedException(it)
}
}
}
fun checkMethodParameters(items: List<ExecutableElement>, numParams: Int, requiredType: TypeMirror? = null) {
items.forEach {
val params = it.parameters
if (numParams == 0 && params.isNotEmpty()) {
throw NoParametersAllowedException(it)
}
if (requiredType == null) {
return
}
if (numParams < params.size) {
throw WrongParametersException(it, numParams, requiredType)
}
// maximum params size is 1
params.forEach { param ->
if (!TYPE_UTILS.isSameType(param.asType(), requiredType)) {
throw WrongParametersException(it, numParams, requiredType)
}
}
}
}
fun <A : Annotation> checkMixPermissionType(items: List<ExecutableElement>, annotationClass: Class<A>) {
items.forEach {
val permissionValue = it.getAnnotation(annotationClass).permissionValue()
if (permissionValue.size > 1) {
if (permissionValue.contains(WRITE_SETTINGS)) {
throw MixPermissionTypeException(it, WRITE_SETTINGS)
} else if (permissionValue.contains(SYSTEM_ALERT_WINDOW)) {
throw MixPermissionTypeException(it, SYSTEM_ALERT_WINDOW)
}
}
}
}
fun checkSpecialPermissionsWithNeverAskAgain(items: List<ExecutableElement>, annotationClass: Class<OnNeverAskAgain> = OnNeverAskAgain::class.java) {
items.forEach {
val permissionValue = it.getAnnotation(annotationClass).permissionValue()
if (permissionValue.contains(WRITE_SETTINGS) || permissionValue.contains(SYSTEM_ALERT_WINDOW)) {
throw SpecialPermissionsWithNeverAskAgainException()
}
}
}
fun checkDuplicatedMethodName(items: List<ExecutableElement>) {
items.forEach { item ->
items.firstOrNull { it != item && it.simpleName == item.simpleName }?.let {
throw DuplicatedMethodNameException(item)
}
}
}
| apache-2.0 | 5bfe737e2142ecdd60fa8541b9abe87d | 35.657143 | 149 | 0.694076 | 4.533569 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/EventBus.kt | 1 | 6559 | @file:Suppress("UNCHECKED_CAST")
package tornadofx
import javafx.application.Platform
import tornadofx.EventBus.RunOn.ApplicationThread
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import java.util.logging.Level
import kotlin.collections.HashSet
import kotlin.concurrent.thread
import kotlin.reflect.KClass
open class FXEvent(
open val runOn: EventBus.RunOn = ApplicationThread,
open val scope: Scope? = null
)
class EventContext {
internal var unsubscribe = false
fun unsubscribe() {
unsubscribe = true
}
}
interface EventRegistration {
val eventType: KClass<out FXEvent>
val owner: Component?
val action: EventContext.(FXEvent) -> Unit
fun unsubscribe()
}
class FXEventRegistration(override val eventType: KClass<out FXEvent>,
override val owner: Component?,
private val maxCount: Long? = null,
private val anAction: EventContext.(FXEvent) -> Unit) : EventRegistration {
private val invocationCount = AtomicLong()
override val action: EventContext.(FXEvent) -> Unit = {
if (maxCount == null || invocationCount.getAndIncrement() < maxCount) {
anAction.invoke(this, it)
} else {
[email protected]()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FXEventRegistration) return false
if (eventType != other.eventType) return false
if (owner != other.owner) return false
if (maxCount != other.maxCount) return false
if (action != other.action) return false
if (invocationCount.get() != other.invocationCount.get()) return false
return true
}
override fun hashCode(): Int {
var result = eventType.hashCode()
result = 31 * result + owner.hashCode()
result = 31 * result + action.hashCode()
return result
}
override fun unsubscribe() {
FX.eventbus.unsubscribe(this)
}
}
data class InvalidatableEventRegistration(val registration: EventRegistration, @Volatile var valid: Boolean = true) : EventRegistration by registration
class EventBus {
enum class RunOn { ApplicationThread, BackgroundThread }
private val subscriptions = ConcurrentHashMap<KClass<out FXEvent>, Set<InvalidatableEventRegistration>>()
private val eventScopes = ConcurrentHashMap<EventContext.(FXEvent) -> Unit, Scope>()
inline fun <reified T : FXEvent> subscribe(scope: Scope, registration: FXEventRegistration) = subscribe(T::class, scope, registration)
fun <T : FXEvent> subscribe(event: KClass<T>, scope: Scope, registration: FXEventRegistration) {
subscriptions.compute(event) { _, set ->
val newSet = if (set != null) HashSet(set.filter { it.valid }) else HashSet()
newSet.add(InvalidatableEventRegistration(registration))
newSet
}
eventScopes[registration.action] = scope
}
inline fun <reified T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, scope: Scope, noinline action: (T) -> Unit) = subscribe(owner, times, T::class, scope, action)
fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: KClass<T>, scope: Scope, action: (T) -> Unit) {
subscribe(event, scope, FXEventRegistration(event, owner, times, action as EventContext.(FXEvent) -> Unit))
}
fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: Class<T>, scope: Scope, action: (T) -> Unit) = subscribe(event.kotlin, scope, FXEventRegistration(event.kotlin, owner, times, action as EventContext.(FXEvent) -> Unit))
inline fun <reified T : FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) = unsubscribe(T::class, action)
fun <T : FXEvent> unsubscribe(event: Class<T>, action: EventContext.(T) -> Unit) = unsubscribe(event.kotlin, action)
fun <T : FXEvent> unsubscribe(event: KClass<T>, action: EventContext.(T) -> Unit) {
subscriptions[event]?.forEach {
if (it.action == action) {
it.valid = false
}
}
eventScopes.remove(action)
}
fun unsubscribe(registration: EventRegistration) {
unsubscribe(registration.eventType, registration.action)
registration.owner?.subscribedEvents?.computeIfPresent(registration.eventType) {_, list -> list.filter { it != registration }}
}
private fun cleanupInvalidRegistrations(eventKlass: KClass<FXEvent>) {
subscriptions.computeIfPresent(eventKlass) { _, set -> set.filter { it.valid }.toSet() }
}
fun fire(event: FXEvent) {
fun fireEvents() {
val eventKlass = event.javaClass.kotlin
subscriptions[eventKlass]?.forEach {
if (it.valid && (event.scope == null || event.scope == eventScopes[it.action])) {
val context = EventContext()
try {
it.action.invoke(context, event)
} catch (subscriberFailure: Exception) {
log.log(Level.WARNING, "Event $event was delivered to subscriber from ${it.owner}, but invocation resulted in exception", subscriberFailure)
}
if (context.unsubscribe) unsubscribe(it)
}
}
cleanupInvalidRegistrations(eventKlass)
}
if (Platform.isFxApplicationThread()) {
if (event.runOn == ApplicationThread) {
fireEvents()
} else {
thread(true) {
fireEvents()
}
}
} else {
if (event.runOn == ApplicationThread) {
Platform.runLater {
fireEvents()
}
} else {
fireEvents()
}
}
}
internal fun clear() {
subscriptions.clear()
eventScopes.clear()
}
internal fun unsubscribeAll(scope: Scope) {
val scopedContexts: Map<EventContext.(FXEvent) -> Unit, Scope> = eventScopes.filter { it.value == scope }
val registrations = mutableListOf<EventRegistration>()
subscriptions.forEach { (_, subscriptionRegistrations) ->
registrations += subscriptionRegistrations.filter { scopedContexts.containsKey(it.action) }
}
registrations.forEach { it.unsubscribe() }
}
} | apache-2.0 | fbc67a8e0dbc36bd88e5a1d56ae5b3a8 | 37.816568 | 254 | 0.626163 | 4.691702 | false | false | false | false |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/tunnels/BranchingPattern.kt | 1 | 2145 | package org.hildan.minecraft.mining.optimizer.patterns.tunnels
import org.hildan.minecraft.mining.optimizer.blocks.Sample
import org.hildan.minecraft.mining.optimizer.patterns.Access
import org.hildan.minecraft.mining.optimizer.patterns.RepeatedDiggingPattern
/**
* One main shaft with perpendicular branches.
*/
class BranchingPattern(
private val shaft: TunnelPattern,
private val branch: TunnelPattern,
private val branchLength: Int,
private val branchOffsetByTier: Int,
) : RepeatedDiggingPattern {
private val layerHeight = shaft.section.height + shaft.vSpacing
// the offset doesn't matter here, the spatial period is the same
override val width = 2 * branchLength + shaft.section.width
// with an offset, two consecutive layers are different
override val height = layerHeight * 2
override val length = branch.hSpacing + branch.section.width
init {
if (shaft.section.height < branch.section.height) {
throw IllegalArgumentException("The main shaft should be higher than branches")
}
if (shaft.hSpacing < 2 * branch.section.width) {
throw IllegalArgumentException("Branches from 2 different shafts are touching: reduce branch length, or put more space")
}
}
override fun getAccesses(offsetX: Int, offsetY: Int) =
setOf(Access(offsetX + branchLength, offsetY), Access(offsetX + branchLength, offsetY + layerHeight))
override fun digInto(sample: Sample, offsetX: Int, offsetY: Int, offsetZ: Int) {
digLayer(sample, offsetX, offsetY, offsetZ, 0)
digLayer(sample, offsetX, offsetY + layerHeight, offsetZ, branchOffsetByTier)
}
private fun digLayer(sample: Sample, originX: Int, originY: Int, originZ: Int, offset: Int) {
branch.digInto(sample, originX, originY, originZ + offset, branchLength, Axis.X)
shaft.digInto(sample, originX + branchLength, originY, originZ, length, Axis.Z)
val oppositeBranchStartX = originX + branchLength + shaft.section.width
branch.digInto(sample, oppositeBranchStartX, originY, originZ + offset, branchLength, Axis.X)
}
}
| mit | 54bc14f24f2ad6e1926bf1f5be447ba0 | 41.9 | 132 | 0.720746 | 4.117083 | false | false | false | false |
stripe/stripe-android | stripecardscan/src/main/java/com/stripe/android/stripecardscan/cardscan/CardScanActivity.kt | 1 | 12060 | package com.stripe.android.stripecardscan.cardscan
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PointF
import android.os.Bundle
import android.util.Size
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.RestrictTo
import com.stripe.android.camera.CameraPreviewImage
import com.stripe.android.camera.framework.Stats
import com.stripe.android.camera.scanui.ScanErrorListener
import com.stripe.android.camera.scanui.ScanState
import com.stripe.android.camera.scanui.SimpleScanStateful
import com.stripe.android.camera.scanui.ViewFinderBackground
import com.stripe.android.camera.scanui.util.asRect
import com.stripe.android.camera.scanui.util.setDrawable
import com.stripe.android.camera.scanui.util.startAnimation
import com.stripe.android.stripecardscan.R
import com.stripe.android.stripecardscan.cardscan.exception.InvalidStripePublishableKeyException
import com.stripe.android.stripecardscan.cardscan.exception.UnknownScanException
import com.stripe.android.stripecardscan.cardscan.result.MainLoopAggregator
import com.stripe.android.stripecardscan.cardscan.result.MainLoopState
import com.stripe.android.stripecardscan.databinding.ActivityCardscanBinding
import com.stripe.android.stripecardscan.framework.api.dto.ScanStatistics
import com.stripe.android.stripecardscan.framework.api.uploadScanStatsOCR
import com.stripe.android.stripecardscan.framework.util.AppDetails
import com.stripe.android.stripecardscan.framework.util.Device
import com.stripe.android.stripecardscan.framework.util.ScanConfig
import com.stripe.android.stripecardscan.payment.card.ScannedCard
import com.stripe.android.stripecardscan.scanui.CancellationReason
import com.stripe.android.stripecardscan.scanui.ScanActivity
import com.stripe.android.stripecardscan.scanui.ScanResultListener
import com.stripe.android.stripecardscan.scanui.util.getColorByRes
import com.stripe.android.stripecardscan.scanui.util.hide
import com.stripe.android.stripecardscan.scanui.util.setVisible
import com.stripe.android.stripecardscan.scanui.util.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicBoolean
internal const val INTENT_PARAM_REQUEST = "request"
internal const val INTENT_PARAM_RESULT = "result"
private val MINIMUM_RESOLUTION = Size(1067, 600) // minimum size of OCR
internal interface CardScanResultListener : ScanResultListener {
/**
* The scan completed.
*/
fun cardScanComplete(card: ScannedCard)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
sealed class CardScanState(isFinal: Boolean) : ScanState(isFinal) {
object NotFound : CardScanState(isFinal = false)
object Found : CardScanState(isFinal = false)
object Correct : CardScanState(isFinal = true)
}
internal class CardScanActivity : ScanActivity(), SimpleScanStateful<CardScanState> {
override val minimumAnalysisResolution = MINIMUM_RESOLUTION
private val viewBinding by lazy {
ActivityCardscanBinding.inflate(layoutInflater)
}
override val previewFrame: ViewGroup by lazy {
viewBinding.cameraView.previewFrame
}
private val viewFinderWindow: View by lazy {
viewBinding.cameraView.viewFinderWindowView
}
private val viewFinderBorder: ImageView by lazy {
viewBinding.cameraView.viewFinderBorderView
}
private val viewFinderBackground: ViewFinderBackground by lazy {
viewBinding.cameraView.viewFinderBackgroundView
}
private val params: CardScanSheetParams by lazy {
intent.getParcelableExtra(INTENT_PARAM_REQUEST)
?: CardScanSheetParams("")
}
private val hasPreviousValidResult = AtomicBoolean(false)
override var scanState: CardScanState? = CardScanState.NotFound
override var scanStatePrevious: CardScanState? = null
override val scanErrorListener: ScanErrorListener = ScanErrorListener()
/**
* The listener which handles results from the scan.
*/
override val resultListener: CardScanResultListener =
object : CardScanResultListener {
override fun cardScanComplete(card: ScannedCard) {
val intent = Intent()
.putExtra(
INTENT_PARAM_RESULT,
CardScanSheetResult.Completed(
ScannedCard(
pan = card.pan
)
)
)
setResult(RESULT_OK, intent)
}
override fun userCanceled(reason: CancellationReason) {
val intent = Intent()
.putExtra(
INTENT_PARAM_RESULT,
CardScanSheetResult.Canceled(reason)
)
setResult(RESULT_CANCELED, intent)
}
override fun failed(cause: Throwable?) {
val intent = Intent()
.putExtra(
INTENT_PARAM_RESULT,
CardScanSheetResult.Failed(cause ?: UnknownScanException())
)
setResult(RESULT_CANCELED, intent)
}
}
/**
* The flow used to scan an item.
*/
private val scanFlow: CardScanFlow by lazy {
object : CardScanFlow(scanErrorListener) {
/**
* A final result was received from the aggregator. Set the result from this activity.
*/
override suspend fun onResult(
result: MainLoopAggregator.FinalResult
) {
launch(Dispatchers.Main) {
changeScanState(CardScanState.Correct)
cameraAdapter.unbindFromLifecycle(this@CardScanActivity)
resultListener.cardScanComplete(ScannedCard(result.pan))
scanStat.trackResult("card_scanned")
closeScanner()
}.let { }
}
/**
* An interim result was received from the result aggregator.
*/
override suspend fun onInterimResult(
result: MainLoopAggregator.InterimResult
) = launch(Dispatchers.Main) {
if (
result.state is MainLoopState.OcrFound &&
!hasPreviousValidResult.getAndSet(true)
) {
scanStat.trackResult("ocr_pan_observed")
}
when (result.state) {
is MainLoopState.Initial -> changeScanState(CardScanState.NotFound)
is MainLoopState.OcrFound -> changeScanState(CardScanState.Found)
is MainLoopState.Finished -> changeScanState(CardScanState.Correct)
}
}.let { }
override suspend fun onReset() = launch(Dispatchers.Main) {
changeScanState(CardScanState.NotFound)
}.let { }
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
if (!ensureValidParams()) {
return
}
viewBinding.closeButton.setOnClickListener {
userClosedScanner()
}
viewBinding.torchButton.setOnClickListener {
toggleFlashlight()
}
viewBinding.swapCameraButton.setOnClickListener {
toggleCamera()
}
viewFinderBorder.setOnTouchListener { _, e ->
setFocus(
PointF(
e.x + viewFinderBorder.left,
e.y + viewFinderBorder.top
)
)
true
}
displayState(requireNotNull(scanState), scanStatePrevious)
}
override fun onResume() {
super.onResume()
scanState = CardScanState.NotFound
}
override fun onDestroy() {
scanFlow.cancelFlow()
super.onDestroy()
}
/**
* Cancel the scan when the user presses back.
*/
override fun onBackPressed() {
runBlocking { scanStat.trackResult("user_canceled") }
resultListener.userCanceled(CancellationReason.Back)
closeScanner()
}
override fun onFlashSupported(supported: Boolean) {
viewBinding.torchButton.setVisible(supported)
}
override fun onSupportsMultipleCameras(supported: Boolean) {
viewBinding.swapCameraButton.setVisible(supported)
}
override fun onCameraReady() {
previewFrame.post {
viewFinderBackground
.setViewFinderRect(viewFinderWindow.asRect())
startCameraAdapter()
}
}
/**
* Once the camera stream is available, start processing images.
*/
override suspend fun onCameraStreamAvailable(cameraStream: Flow<CameraPreviewImage<Bitmap>>) {
scanFlow.startFlow(
context = this,
imageStream = cameraStream,
viewFinder = viewBinding.cameraView.viewFinderWindowView.asRect(),
lifecycleOwner = this,
coroutineScope = this,
parameters = null
)
}
/**
* Called when the flashlight state has changed.
*/
override fun onFlashlightStateChanged(flashlightOn: Boolean) {
if (flashlightOn) {
viewBinding.torchButton.setDrawable(R.drawable.stripe_flash_on_dark)
} else {
viewBinding.torchButton.setDrawable(R.drawable.stripe_flash_off_dark)
}
}
private fun ensureValidParams() = when {
params.stripePublishableKey.isEmpty() -> {
scanFailure(InvalidStripePublishableKeyException("Missing publishable key"))
false
}
else -> true
}
override fun displayState(newState: CardScanState, previousState: CardScanState?) {
when (newState) {
is CardScanState.NotFound -> {
viewFinderBackground
.setBackgroundColor(getColorByRes(R.color.stripeNotFoundBackground))
viewFinderWindow
.setBackgroundResource(R.drawable.stripe_card_background_not_found)
viewFinderBorder.startAnimation(R.drawable.stripe_card_border_not_found)
viewBinding.instructions.setText(R.string.stripe_card_scan_instructions)
}
is CardScanState.Found -> {
viewFinderBackground
.setBackgroundColor(getColorByRes(R.color.stripeFoundBackground))
viewFinderWindow
.setBackgroundResource(R.drawable.stripe_card_background_found)
viewFinderBorder.startAnimation(R.drawable.stripe_card_border_found)
viewBinding.instructions.setText(R.string.stripe_card_scan_instructions)
viewBinding.instructions.show()
}
is CardScanState.Correct -> {
viewFinderBackground
.setBackgroundColor(getColorByRes(R.color.stripeCorrectBackground))
viewFinderWindow
.setBackgroundResource(R.drawable.stripe_card_background_correct)
viewFinderBorder.startAnimation(R.drawable.stripe_card_border_correct)
viewBinding.instructions.hide()
}
}
}
override fun closeScanner() {
uploadScanStatsOCR(
stripePublishableKey = params.stripePublishableKey,
instanceId = Stats.instanceId,
scanId = Stats.scanId,
device = Device.fromContext(this),
appDetails = AppDetails.fromContext(this),
scanStatistics = ScanStatistics.fromStats(),
scanConfig = ScanConfig(0)
)
super.closeScanner()
}
}
| mit | e372ce58b728161d93e217bbb26b21a2 | 35.656535 | 98 | 0.648507 | 5.149445 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/FocusManager.kt | 3 | 9593 | /*
* 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.focus
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection.Companion.Next
import androidx.compose.ui.focus.FocusDirection.Companion.Previous
import androidx.compose.ui.focus.FocusRequester.Companion.Cancel
import androidx.compose.ui.focus.FocusRequester.Companion.Default
import androidx.compose.ui.focus.FocusStateImpl.Active
import androidx.compose.ui.focus.FocusStateImpl.ActiveParent
import androidx.compose.ui.focus.FocusStateImpl.Captured
import androidx.compose.ui.focus.FocusStateImpl.Deactivated
import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent
import androidx.compose.ui.focus.FocusStateImpl.Inactive
import androidx.compose.ui.internal.JvmDefaultWithCompatibility
import androidx.compose.ui.unit.LayoutDirection
@JvmDefaultWithCompatibility
interface FocusManager {
/**
* Call this function to clear focus from the currently focused component, and set the focus to
* the root focus modifier.
*
* @param force: Whether we should forcefully clear focus regardless of whether we have
* any components that have Captured focus.
*
* @sample androidx.compose.ui.samples.ClearFocusSample
*/
fun clearFocus(force: Boolean = false)
/**
* Moves focus in the specified [direction][FocusDirection].
*
* If you are not satisfied with the default focus order, consider setting a custom order using
* [Modifier.focusProperties()][focusProperties].
*
* @return true if focus was moved successfully. false if the focused item is unchanged.
*
* @sample androidx.compose.ui.samples.MoveFocusSample
*/
fun moveFocus(focusDirection: FocusDirection): Boolean
}
/**
* The focus manager is used by different [Owner][androidx.compose.ui.node.Owner] implementations
* to control focus.
*
* @param focusModifier The modifier that will be used as the root focus modifier.
*/
internal class FocusManagerImpl(
private val focusModifier: FocusModifier = FocusModifier(Inactive)
) : FocusManager {
/**
* A [Modifier] that can be added to the [Owners][androidx.compose.ui.node.Owner] modifier
* list that contains the modifiers required by the focus system. (Eg, a root focus modifier).
*/
// TODO(b/168831247): return an empty Modifier when there are no focusable children.
val modifier: Modifier = Modifier.focusTarget(focusModifier)
lateinit var layoutDirection: LayoutDirection
/**
* The [Owner][androidx.compose.ui.node.Owner] calls this function when it gains focus. This
* informs the [focus manager][FocusManagerImpl] that the
* [Owner][androidx.compose.ui.node.Owner] gained focus, and that it should propagate this
* focus to one of the focus modifiers in the component hierarchy.
*/
fun takeFocus() {
// If the focus state is not Inactive, it indicates that the focus state is already
// set (possibly by dispatchWindowFocusChanged). So we don't update the state.
if (focusModifier.focusState == Inactive) {
focusModifier.focusState = Active
// TODO(b/152535715): propagate focus to children based on child focusability.
}
}
/**
* The [Owner][androidx.compose.ui.node.Owner] calls this function when it loses focus. This
* informs the [focus manager][FocusManagerImpl] that the
* [Owner][androidx.compose.ui.node.Owner] lost focus, and that it should clear focus from
* all the focus modifiers in the component hierarchy.
*/
fun releaseFocus() {
focusModifier.clearFocus(forcedClear = true)
}
/**
* Call this function to set the focus to the root focus modifier.
*
* @param force: Whether we should forcefully clear focus regardless of whether we have
* any components that have captured focus.
*
* This could be used to clear focus when a user clicks on empty space outside a focusable
* component.
*/
override fun clearFocus(force: Boolean) {
// If this hierarchy had focus before clearing it, it indicates that the host view has
// focus. So after clearing focus within the compose hierarchy, we should restore focus to
// the root focus modifier to maintain consistency with the host view.
val rootInitialState = focusModifier.focusState
if (focusModifier.clearFocus(force)) {
focusModifier.focusState = when (rootInitialState) {
Active, ActiveParent, Captured -> Active
Deactivated, DeactivatedParent -> Deactivated
Inactive -> Inactive
}
}
}
/**
* Moves focus in the specified direction.
*
* @return true if focus was moved successfully. false if the focused item is unchanged.
*/
override fun moveFocus(focusDirection: FocusDirection): Boolean {
// If there is no active node in this sub-hierarchy, we can't move focus.
val source = focusModifier.findActiveFocusNode() ?: return false
// Check if a custom focus traversal order is specified.
val nextFocusRequester = source.customFocusSearch(focusDirection, layoutDirection)
return when (nextFocusRequester) {
@OptIn(ExperimentalComposeUiApi::class)
Cancel -> false
Default -> {
val foundNextItem =
focusModifier.focusSearch(focusDirection, layoutDirection) { destination ->
if (destination == source) return@focusSearch false
checkNotNull(destination.parent) { "Focus search landed at the root." }
// If we found a potential next item, move focus to it.
destination.requestFocus()
true
}
// If we didn't find a potential next item, try to wrap around.
foundNextItem || wrapAroundFocus(focusDirection)
}
else -> {
// TODO(b/175899786): We ideally need to check if the nextFocusRequester points to
// something that is visible and focusable in the current mode (Touch/Non-Touch mode).
nextFocusRequester.requestFocus()
true
}
}
}
/**
* Runs the focus properties block for all [focusProperties] modifiers to fetch updated
* [FocusProperties].
*
* The [focusProperties] block is run automatically whenever the properties change, and you
* rarely need to invoke this function manually. However, if you have a situation where you want
* to change a property, and need to see the change in the current snapshot, use this API.
*/
fun fetchUpdatedFocusProperties() {
focusModifier.updateProperties()
}
/**
* Searches for the currently focused item.
*
* @return the currently focused item.
*/
@Suppress("ModifierFactoryExtensionFunction", "ModifierFactoryReturnType")
internal fun getActiveFocusModifier(): FocusModifier? {
return focusModifier.findActiveItem()
}
// TODO(b/144116848): This is a hack to make Next/Previous wrap around. This must be
// replaced by code that sends the move request back to the view system. The view system
// will then pass focus to other views, and ultimately return back to this compose view.
private fun wrapAroundFocus(focusDirection: FocusDirection): Boolean {
// Wrap is not supported when this sub-hierarchy doesn't have focus.
if (!focusModifier.focusState.hasFocus || focusModifier.focusState.isFocused) return false
// Next and Previous wraps around.
when (focusDirection) {
Next, Previous -> {
// Clear Focus to send focus the root node.
clearFocus(force = false)
if (!focusModifier.focusState.isFocused) return false
// Wrap around by calling moveFocus after the root gains focus.
return moveFocus(focusDirection)
}
// We only wrap-around for 1D Focus search.
else -> return false
}
}
}
private fun FocusModifier.updateProperties() {
// Update the focus node with the current focus properties.
refreshFocusProperties()
// Update the focus properties for all children.
children.forEach { it.updateProperties() }
}
/**
* Find the focus modifier in this sub-hierarchy that is currently focused.
*/
@Suppress("ModifierFactoryExtensionFunction", "ModifierFactoryReturnType")
private fun FocusModifier.findActiveItem(): FocusModifier? {
return when (focusState) {
Active, Captured -> this
ActiveParent, DeactivatedParent -> {
focusedChild?.findActiveItem() ?: error("no child")
}
Deactivated, Inactive -> null
}
}
| apache-2.0 | 0f08394e41947f292deca72794781aa5 | 40.89083 | 103 | 0.681122 | 4.91193 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/messaging/MessageScanner.kt | 1 | 2645 | package com.teamwizardry.librarianlib.facade.container.messaging
import com.teamwizardry.librarianlib.core.util.kotlin.unmodifiableView
import com.teamwizardry.librarianlib.scribe.Scribe
import com.teamwizardry.librarianlib.scribe.nbt.NbtSerializer
import dev.thecodewarrior.mirror.Mirror
import dev.thecodewarrior.mirror.member.MethodMirror
import dev.thecodewarrior.prism.PrismException
import net.minecraft.nbt.NbtCompound
import net.minecraft.nbt.NbtList
public object MessageScanner {
private val scanCache = mutableMapOf<Class<*>, List<MessageScan>>()
public fun getMessages(targetType: Class<*>): List<MessageScan> {
return scanCache.getOrPut(targetType) {
Mirror.reflectClass(targetType).methods.mapNotNull {
if(it.annotations.isPresent<Message>())
MessageScan(it)
else
null
}.unmodifiableView()
}
}
public class MessageScan(public val method: MethodMirror) {
private val messageAnnotation = method.annotations.get<Message>()!!
public val name: String = messageAnnotation.name.let {
if(it == "") method.name else it
}
public val side: MessageSide = messageAnnotation.side
public val parameterSerializers: List<NbtSerializer<*>> = method.parameters.map { parameter ->
try {
Scribe.nbt[parameter.type].value
} catch(e: PrismException) {
throw IllegalStateException("Error getting serializer for parameter ${parameter.index} of message '$name'", e)
}
}.unmodifiableView()
public fun writeArguments(arguments: Array<out Any?>): NbtCompound {
if(parameterSerializers.size != arguments.size)
throw IllegalArgumentException("Expected ${parameterSerializers.size} arguments, not ${arguments.size}")
val list = NbtList()
parameterSerializers.mapIndexed { i, serializer ->
val tag = NbtCompound()
arguments[i]?.also {
tag.put("V", serializer.write(it))
}
list.add(tag)
}.toTypedArray()
return NbtCompound().also { it.put("ll", list) }
}
public fun readArguments(payload: NbtCompound): Array<Any?> {
val list = payload.getList("ll", NbtCompound().type.toInt())
return parameterSerializers.mapIndexed { i, serializer ->
list.getCompound(i).get("V")?.let {
serializer.read(it)
}
}.toTypedArray()
}
}
}
| lgpl-3.0 | b2d955657df6099a6f013799d8cd01ee | 39.692308 | 126 | 0.62344 | 4.971805 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/KeyboardActions.kt | 3 | 3710 | /*
* 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.foundation.text
import androidx.compose.ui.text.input.ImeAction
/**
* The [KeyboardActions] class allows developers to specify actions that will be triggered in
* response to users triggering IME action on the software keyboard.
*/
class KeyboardActions(
/**
* This is run when the user triggers the [Done][ImeAction.Done] action. A null value
* indicates that the default implementation if any, should be executed.
*/
val onDone: (KeyboardActionScope.() -> Unit)? = null,
/**
* This is run when the user triggers the [Go][ImeAction.Go] action. A null value indicates
* that the default implementation if any, should be executed.
*/
val onGo: (KeyboardActionScope.() -> Unit)? = null,
/**
* This is run when the user triggers the [Next][ImeAction.Next] action. A null value
* indicates that the default implementation should be executed. The default implementation
* moves focus to the next item in the focus traversal order.
*
* See [Modifier.focusProperties()][androidx.compose.ui.focus.focusProperties] for more details
* on how to specify a custom focus order if needed.
*/
val onNext: (KeyboardActionScope.() -> Unit)? = null,
/**
* This is run when the user triggers the [Previous][ImeAction.Previous] action. A null value
* indicates that the default implementation should be executed. The default implementation
* moves focus to the previous item in the focus traversal order.
*
* See [Modifier.focusProperties()][androidx.compose.ui.focus.focusProperties] for more details
* on how to specify a custom focus order if needed.
*/
val onPrevious: (KeyboardActionScope.() -> Unit)? = null,
/**
* This is run when the user triggers the [Search][ImeAction.Search] action. A null value
* indicates that the default implementation if any, should be executed.
*/
val onSearch: (KeyboardActionScope.() -> Unit)? = null,
/**
* This is run when the user triggers the [Send][ImeAction.Send] action. A null value
* indicates that the default implementation if any, should be executed.
*/
val onSend: (KeyboardActionScope.() -> Unit)? = null
) {
companion object {
/**
* Use this default value if you don't want to specify any action but want to use use the
* default action implementations.
*/
val Default: KeyboardActions = KeyboardActions()
}
}
/**
* Creates an instance of [KeyboardActions] that uses the specified lambda for all [ImeAction]s.
*/
fun KeyboardActions(onAny: KeyboardActionScope.() -> Unit): KeyboardActions = KeyboardActions(
onDone = onAny,
onGo = onAny,
onNext = onAny,
onPrevious = onAny,
onSearch = onAny,
onSend = onAny
)
/**
* This scope can be used to execute the default action implementation.
*/
interface KeyboardActionScope {
/**
* Runs the default implementation for the specified [action][ImeAction].
*/
fun defaultKeyboardAction(imeAction: ImeAction)
}
| apache-2.0 | 349de17fac08e3b96e86c28d90737e9f | 36.474747 | 99 | 0.692722 | 4.591584 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/desktopMain/kotlin/androidx/compose/ui/text/ExpireAfterAccessCache.desktop.kt | 3 | 3495 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
// expire cache entries after `expireAfter` after last access
internal class ExpireAfterAccessCache<K, V>(
val expireAfterNanos: Long,
val timeProvider: TimeProvider = SystemTimeProvider()
) : Cache<K, V> {
internal interface TimeProvider {
fun getTime(): Long
}
internal class SystemTimeProvider : TimeProvider {
override fun getTime() = System.nanoTime()
}
inner class Entry(
val key: K,
val value: V,
var accessTime: Long,
var nextInAccess: Entry? = null,
var prevInAccess: Entry? = null
)
inner class LinkedQueue {
var head: Entry? = null
var tail: Entry? = null
fun moveToHead(entry: Entry) {
if (head == entry) {
return
}
if (tail == entry) {
tail = entry.nextInAccess
}
entry.nextInAccess?.prevInAccess = entry.prevInAccess
entry.prevInAccess?.nextInAccess = entry.nextInAccess
head?.nextInAccess = entry
entry.prevInAccess = head
entry.nextInAccess = null
head = entry
}
fun putToHead(entry: Entry) {
if (tail == null) {
tail = entry
}
head?.nextInAccess = entry
entry.prevInAccess = head
head = entry
}
fun removeFromTail() {
if (tail == head) {
head == null
}
tail?.nextInAccess?.prevInAccess = null
tail = tail?.nextInAccess
}
}
internal val map = HashMap<K, Entry>()
internal val accessQueue = LinkedQueue()
private val lock = ReentrantLock()
override fun get(key: K, loader: (K) -> V): V {
lock.withLock {
val now = timeProvider.getTime()
val v = map[key]
if (v != null) {
v.accessTime = now
accessQueue.moveToHead(v)
checkEvicted(now)
return v.value
} else {
checkEvicted(now)
val newVal = loader(key)
val entry = Entry(
key = key,
value = newVal,
accessTime = now
)
map[key] = entry
accessQueue.putToHead(entry)
return newVal
}
}
}
private fun checkEvicted(now: Long) {
val expireTime = now - expireAfterNanos
var next = accessQueue.tail
while (next != null && next.accessTime < expireTime) {
map.remove(next.key)
accessQueue.removeFromTail()
next = next.nextInAccess
}
}
}
| apache-2.0 | 448d14534b95b09b021134c0f8942b9c | 28.125 | 75 | 0.554793 | 4.586614 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/util/wrapper/OriginalSizeGlideTarget.kt | 2 | 996 | package me.proxer.app.util.wrapper
import android.graphics.drawable.Drawable
import com.bumptech.glide.request.Request
import com.bumptech.glide.request.target.SizeReadyCallback
import com.bumptech.glide.request.target.Target
/**
* @author Ruben Gees
*/
abstract class OriginalSizeGlideTarget<R> : Target<R> {
private var request: Request? = null
override fun onLoadStarted(placeholder: Drawable?) = Unit
override fun onLoadFailed(errorDrawable: Drawable?) = Unit
override fun onLoadCleared(placeholder: Drawable?) = Unit
override fun onStart() = Unit
override fun onStop() = Unit
override fun onDestroy() = Unit
override fun removeCallback(cb: SizeReadyCallback) = Unit
override fun getSize(cb: SizeReadyCallback) {
cb.onSizeReady(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
}
override fun getRequest(): Request? {
return request
}
override fun setRequest(request: Request?) {
this.request = request
}
}
| gpl-3.0 | 31a71a8cdf8e223ea878029168df7202 | 26.666667 | 66 | 0.721888 | 4.349345 | false | false | false | false |
pyamsoft/power-manager | powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/WifiManagerWrapperImpl.kt | 1 | 2097 | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.states
import android.content.Context
import android.net.wifi.WifiManager
import com.pyamsoft.powermanager.base.logger.Logger
import com.pyamsoft.powermanager.model.Connections
import com.pyamsoft.powermanager.model.States
import timber.log.Timber
import javax.inject.Inject
internal class WifiManagerWrapperImpl @Inject internal constructor(context: Context,
private val logger: Logger) : ConnectedDeviceFunctionWrapper {
private val wifiManager: WifiManager?
init {
this.wifiManager = context.applicationContext.getSystemService(
Context.WIFI_SERVICE) as WifiManager
}
private fun toggle(state: Boolean) {
if (wifiManager != null) {
logger.i("Wifi: %s", if (state) "enable" else "disable")
wifiManager.isWifiEnabled = state
}
}
override fun enable() {
toggle(true)
}
override fun disable() {
toggle(false)
}
override val state: States
get() {
if (wifiManager == null) {
Timber.w("Wifi state unknown")
return States.UNKNOWN
} else {
return if (wifiManager.isWifiEnabled) States.ENABLED else States.DISABLED
}
}
override val connectionState: Connections
get() {
if (wifiManager == null) {
Timber.w("Wifi connection state unknown")
return Connections.UNKNOWN
} else {
return if (wifiManager.connectionInfo == null) Connections.DISCONNECTED
else Connections.CONNECTED
}
}
}
| apache-2.0 | 45eb9b59a4488126a03624df4add37a5 | 28.957143 | 84 | 0.709108 | 4.461702 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/tumangaonline/src/eu/kanade/tachiyomi/extension/es/tumangaonline/TuMangaOnline.kt | 1 | 25685 | package eu.kanade.tachiyomi.extension.es.tumangaonline
import android.app.Application
import android.content.SharedPreferences
import eu.kanade.tachiyomi.lib.ratelimit.SpecificHostRateLimitInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.SimpleDateFormat
import java.util.Locale
class TuMangaOnline : ConfigurableSource, ParsedHttpSource() {
override val name = "TuMangaOnline"
override val baseUrl = "https://lectortmo.com"
override val lang = "es"
override val supportsLatest = true
private val imageCDNUrl = "https://img1.japanreader.com"
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
private val webRateLimitInterceptor = SpecificHostRateLimitInterceptor(
baseUrl.toHttpUrlOrNull()!!,
preferences.getString(WEB_RATELIMIT_PREF, WEB_RATELIMIT_PREF_DEFAULT_VALUE)!!.toInt(),
60
)
private val imageCDNRateLimitInterceptor = SpecificHostRateLimitInterceptor(
imageCDNUrl.toHttpUrlOrNull()!!,
preferences.getString(IMAGE_CDN_RATELIMIT_PREF, IMAGE_CDN_RATELIMIT_PREF_DEFAULT_VALUE)!!.toInt(),
60
)
override val client: OkHttpClient = network.client.newBuilder()
.addNetworkInterceptor(webRateLimitInterceptor)
.addNetworkInterceptor(imageCDNRateLimitInterceptor)
.build()
// Marks erotic content as false and excludes: Ecchi(6), GirlsLove(17), BoysLove(18) and Harem(19) genders
private val getSFWUrlPart = if (getSFWModePref()) "&exclude_genders%5B%5D=6&exclude_genders%5B%5D=17&exclude_genders%5B%5D=18&exclude_genders%5B%5D=19&erotic=false" else ""
override fun popularMangaRequest(page: Int) = GET("$baseUrl/library?order_item=likes_count&order_dir=desc&filter_by=title$getSFWUrlPart&_pg=1&page=$page", headers)
override fun popularMangaNextPageSelector() = "a.page-link"
override fun popularMangaSelector() = "div.element"
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
element.select("div.element > a").let {
setUrlWithoutDomain(it.attr("href").substringAfter(" "))
title = it.select("h4.text-truncate").text()
thumbnail_url = it.select("style").toString().substringAfter("('").substringBeforeLast("')")
}
}
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/library?order_item=creation&order_dir=desc&filter_by=title$getSFWUrlPart&_pg=1&page=$page", headers)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/library".toHttpUrlOrNull()!!.newBuilder()
url.addQueryParameter("title", query)
if (getSFWModePref()) {
SFW_MODE_PREF_EXCLUDE_GENDERS.forEach { gender ->
url.addQueryParameter("exclude_genders[]", gender)
}
url.addQueryParameter("erotic", "false")
}
url.addQueryParameter("page", page.toString())
url.addQueryParameter("_pg", "1") // Extra Query to Prevent Scrapping aka without it = 403
filters.forEach { filter ->
when (filter) {
is Types -> {
url.addQueryParameter("type", filter.toUriPart())
}
is Demography -> {
url.addQueryParameter("demography", filter.toUriPart())
}
is Status -> {
url.addQueryParameter("status", filter.toUriPart())
}
is TranslationStatus -> {
url.addQueryParameter("translation_status", filter.toUriPart())
}
is FilterBy -> {
url.addQueryParameter("filter_by", filter.toUriPart())
}
is SortBy -> {
if (filter.state != null) {
url.addQueryParameter("order_item", SORTABLES[filter.state!!.index].second)
url.addQueryParameter(
"order_dir",
if (filter.state!!.ascending) { "asc" } else { "desc" }
)
}
}
is ContentTypeList -> {
filter.state.forEach { content ->
// If (SFW mode is not enabled) OR (SFW mode is enabled AND filter != erotic) -> Apply filter
// else -> ignore filter
if (!getSFWModePref() || (getSFWModePref() && content.id != "erotic")) {
when (content.state) {
Filter.TriState.STATE_IGNORE -> url.addQueryParameter(content.id, "")
Filter.TriState.STATE_INCLUDE -> url.addQueryParameter(content.id, "true")
Filter.TriState.STATE_EXCLUDE -> url.addQueryParameter(content.id, "false")
}
}
}
}
is GenreList -> {
filter.state.forEach { genre ->
when (genre.state) {
Filter.TriState.STATE_INCLUDE -> url.addQueryParameter("genders[]", genre.id)
Filter.TriState.STATE_EXCLUDE -> url.addQueryParameter("exclude_genders[]", genre.id)
}
}
}
}
}
return GET(url.build().toString(), headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
title = document.select("h2.element-subtitle").text()
document.select("h5.card-title").let {
author = it?.first()?.attr("title")?.substringAfter(", ")
artist = it?.last()?.attr("title")?.substringAfter(", ")
}
genre = document.select("a.py-2").joinToString(", ") {
it.text()
}
description = document.select("p.element-description")?.text()
status = parseStatus(document.select("span.book-status")?.text().orEmpty())
thumbnail_url = document.select(".book-thumbnail").attr("src")
}
private fun parseStatus(status: String) = when {
status.contains("Publicándose") -> SManga.ONGOING
status.contains("Finalizado") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
// One-shot
if (document.select("div.chapters").isEmpty()) {
return document.select(oneShotChapterListSelector()).map { oneShotChapterFromElement(it) }
}
// Regular list of chapters
val chapters = mutableListOf<SChapter>()
document.select(regularChapterListSelector()).forEach { chapelement ->
val chapternumber = chapelement.select("a.btn-collapse").text()
.substringBefore(":")
.substringAfter("Capítulo")
.trim()
.toFloat()
val chaptername = chapelement.select("div.col-10.text-truncate").text()
val scanelement = chapelement.select("ul.chapter-list > li")
if (getScanlatorPref()) {
scanelement.forEach { chapters.add(regularChapterFromElement(it, chaptername, chapternumber)) }
} else {
scanelement.first { chapters.add(regularChapterFromElement(it, chaptername, chapternumber)) }
}
}
return chapters
}
override fun chapterListSelector() = throw UnsupportedOperationException("Not used")
override fun chapterFromElement(element: Element) = throw UnsupportedOperationException("Not used")
private fun oneShotChapterListSelector() = "div.chapter-list-element > ul.list-group li.list-group-item"
private fun oneShotChapterFromElement(element: Element) = SChapter.create().apply {
url = element.select("div.row > .text-right > a").attr("href")
name = "One Shot"
scanlator = element.select("div.col-md-6.text-truncate")?.text()
date_upload = element.select("span.badge.badge-primary.p-2").first()?.text()?.let { parseChapterDate(it) }
?: 0
}
private fun regularChapterListSelector() = "div.chapters > ul.list-group li.p-0.list-group-item"
private fun regularChapterFromElement(element: Element, chName: String, number: Float) = SChapter.create().apply {
url = element.select("div.row > .text-right > a").attr("href")
name = chName
chapter_number = number
scanlator = element.select("div.col-md-6.text-truncate")?.text()
date_upload = element.select("span.badge.badge-primary.p-2").first()?.text()?.let { parseChapterDate(it) }
?: 0
}
private fun parseChapterDate(date: String): Long = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(date)?.time
?: 0
override fun pageListRequest(chapter: SChapter): Request {
val currentUrl = client.newCall(GET(chapter.url, headers)).execute().asJsoup().body().baseUri()
// Get /cascade instead of /paginate to get all pages at once
val newUrl = if (getPageMethodPref() == "cascade" && currentUrl.contains("paginated")) {
currentUrl.substringBefore("paginated") + "cascade"
} else if (getPageMethodPref() == "paginated" && currentUrl.contains("cascade")) {
currentUrl.substringBefore("cascade") + "paginated"
} else currentUrl
return GET(newUrl, headers)
}
override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply {
if (getPageMethodPref() == "cascade") {
document.select("div.viewer-container img").forEach {
add(
Page(
size,
"",
it.let {
if (it.hasAttr("data-src"))
it.attr("abs:data-src") else it.attr("abs:src")
}
)
)
}
} else {
val pageList = document.select("#viewer-pages-select").first().select("option").map { it.attr("value").toInt() }
val url = document.baseUri()
pageList.forEach {
add(Page(it, "$url/$it"))
}
}
}
// Note: At this moment (15/02/2021) it's necessary to make the image request without headers to prevent 403.
override fun imageRequest(page: Page) = GET(page.imageUrl!!)
override fun imageUrlParse(document: Document): String {
return document.select("div.viewer-container > div.img-container > img.viewer-image").attr("src")
}
private fun searchMangaByIdRequest(id: String) = GET("$baseUrl/$PREFIX_LIBRARY/$id", headers)
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return if (query.startsWith(PREFIX_ID_SEARCH)) {
val realQuery = query.removePrefix(PREFIX_ID_SEARCH)
client.newCall(searchMangaByIdRequest(realQuery))
.asObservableSuccess()
.map { response ->
val details = mangaDetailsParse(response)
details.url = "/$PREFIX_LIBRARY/$realQuery"
MangasPage(listOf(details), false)
}
} else {
client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
}
}
private class Types : UriPartFilter(
"Filtrar por tipo",
arrayOf(
Pair("Ver todo", ""),
Pair("Manga", "manga"),
Pair("Manhua", "manhua"),
Pair("Manhwa", "manhwa"),
Pair("Novela", "novel"),
Pair("One shot", "one_shot"),
Pair("Doujinshi", "doujinshi"),
Pair("Oel", "oel")
)
)
private class Status : UriPartFilter(
"Filtrar por estado de serie",
arrayOf(
Pair("Ver todo", ""),
Pair("Publicándose", "publishing"),
Pair("Finalizado", "ended"),
Pair("Cancelado", "cancelled"),
Pair("Pausado", "on_hold")
)
)
private class TranslationStatus : UriPartFilter(
"Filtrar por estado de traducción",
arrayOf(
Pair("Ver todo", ""),
Pair("Activo", "publishing"),
Pair("Finalizado", "ended"),
Pair("Abandonado", "cancelled")
)
)
private class Demography : UriPartFilter(
"Filtrar por demografía",
arrayOf(
Pair("Ver todo", ""),
Pair("Seinen", "seinen"),
Pair("Shoujo", "shoujo"),
Pair("Shounen", "shounen"),
Pair("Josei", "josei"),
Pair("Kodomo", "kodomo")
)
)
private class FilterBy : UriPartFilter(
"Filtrar por",
arrayOf(
Pair("Título", "title"),
Pair("Autor", "author"),
Pair("Compañia", "company")
)
)
class SortBy : Filter.Sort(
"Ordenar por",
SORTABLES.map { it.first }.toTypedArray(),
Selection(0, false)
)
private class ContentType(name: String, val id: String) : Filter.TriState(name)
private class ContentTypeList(content: List<ContentType>) : Filter.Group<ContentType>("Filtrar por tipo de contenido", content)
private class Genre(name: String, val id: String) : Filter.TriState(name)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Filtrar por géneros", genres)
override fun getFilterList() = FilterList(
Types(),
Filter.Separator(),
Filter.Header("Ignorado sino se filtra por tipo"),
Status(),
Filter.Separator(),
Filter.Header("Ignorado sino se filtra por tipo"),
TranslationStatus(),
Filter.Separator(),
Demography(),
Filter.Separator(),
FilterBy(),
Filter.Separator(),
SortBy(),
Filter.Separator(),
ContentTypeList(getContentTypeList()),
Filter.Separator(),
GenreList(getGenreList())
)
// Array.from(document.querySelectorAll('#books-genders .col-auto .custom-control'))
// .map(a => `Genre("${a.querySelector('label').innerText}", "${a.querySelector('input').value}")`).join(',\n')
// on https://lectortmo.com/library
// Last revision 15/02/2021
private fun getGenreList() = listOf(
Genre("Acción", "1"),
Genre("Aventura", "2"),
Genre("Comedia", "3"),
Genre("Drama", "4"),
Genre("Recuentos de la vida", "5"),
Genre("Ecchi", "6"),
Genre("Fantasia", "7"),
Genre("Magia", "8"),
Genre("Sobrenatural", "9"),
Genre("Horror", "10"),
Genre("Misterio", "11"),
Genre("Psicológico", "12"),
Genre("Romance", "13"),
Genre("Ciencia Ficción", "14"),
Genre("Thriller", "15"),
Genre("Deporte", "16"),
Genre("Girls Love", "17"),
Genre("Boys Love", "18"),
Genre("Harem", "19"),
Genre("Mecha", "20"),
Genre("Supervivencia", "21"),
Genre("Reencarnación", "22"),
Genre("Gore", "23"),
Genre("Apocalíptico", "24"),
Genre("Tragedia", "25"),
Genre("Vida Escolar", "26"),
Genre("Historia", "27"),
Genre("Militar", "28"),
Genre("Policiaco", "29"),
Genre("Crimen", "30"),
Genre("Superpoderes", "31"),
Genre("Vampiros", "32"),
Genre("Artes Marciales", "33"),
Genre("Samurái", "34"),
Genre("Género Bender", "35"),
Genre("Realidad Virtual", "36"),
Genre("Ciberpunk", "37"),
Genre("Musica", "38"),
Genre("Parodia", "39"),
Genre("Animación", "40"),
Genre("Demonios", "41"),
Genre("Familia", "42"),
Genre("Extranjero", "43"),
Genre("Niños", "44"),
Genre("Realidad", "45"),
Genre("Telenovela", "46"),
Genre("Guerra", "47"),
Genre("Oeste", "48")
)
private fun getContentTypeList() = listOf(
ContentType("Webcomic", "webcomic"),
ContentType("Yonkoma", "yonkoma"),
ContentType("Amateur", "amateur"),
ContentType("Erótico", "erotic")
)
private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) :
Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) {
val SFWModePref = androidx.preference.CheckBoxPreference(screen.context).apply {
key = SFW_MODE_PREF
title = SFW_MODE_PREF_TITLE
summary = SFW_MODE_PREF_SUMMARY
setDefaultValue(SFW_MODE_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
val checkValue = newValue as Boolean
preferences.edit().putBoolean(SFW_MODE_PREF, checkValue).commit()
}
}
val scanlatorPref = androidx.preference.CheckBoxPreference(screen.context).apply {
key = SCANLATOR_PREF
title = SCANLATOR_PREF_TITLE
summary = SCANLATOR_PREF_SUMMARY
setDefaultValue(SCANLATOR_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
val checkValue = newValue as Boolean
preferences.edit().putBoolean(SCANLATOR_PREF, checkValue).commit()
}
}
val pageMethodPref = androidx.preference.ListPreference(screen.context).apply {
key = PAGE_METHOD_PREF
title = PAGE_METHOD_PREF_TITLE
entries = arrayOf("Cascada", "Páginado")
entryValues = arrayOf("cascade", "paginated")
summary = PAGE_METHOD_PREF_SUMMARY
setDefaultValue(PAGE_METHOD_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
try {
val setting = preferences.edit().putString(PAGE_METHOD_PREF, newValue as String).commit()
setting
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
// Rate limit
val apiRateLimitPreference = androidx.preference.ListPreference(screen.context).apply {
key = WEB_RATELIMIT_PREF
title = WEB_RATELIMIT_PREF_TITLE
summary = WEB_RATELIMIT_PREF_SUMMARY
entries = ENTRIES_ARRAY
entryValues = ENTRIES_ARRAY
setDefaultValue(WEB_RATELIMIT_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
try {
val setting = preferences.edit().putString(WEB_RATELIMIT_PREF, newValue as String).commit()
setting
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
val imgCDNRateLimitPreference = androidx.preference.ListPreference(screen.context).apply {
key = IMAGE_CDN_RATELIMIT_PREF
title = IMAGE_CDN_RATELIMIT_PREF_TITLE
summary = IMAGE_CDN_RATELIMIT_PREF_SUMMARY
entries = ENTRIES_ARRAY
entryValues = ENTRIES_ARRAY
setDefaultValue(IMAGE_CDN_RATELIMIT_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
try {
val setting = preferences.edit().putString(IMAGE_CDN_RATELIMIT_PREF, newValue as String).commit()
setting
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
screen.addPreference(SFWModePref)
screen.addPreference(scanlatorPref)
screen.addPreference(pageMethodPref)
screen.addPreference(apiRateLimitPreference)
screen.addPreference(imgCDNRateLimitPreference)
}
private fun getScanlatorPref(): Boolean = preferences.getBoolean(SCANLATOR_PREF, SCANLATOR_PREF_DEFAULT_VALUE)
private fun getSFWModePref(): Boolean = preferences.getBoolean(SFW_MODE_PREF, SFW_MODE_PREF_DEFAULT_VALUE)
private fun getPageMethodPref() = preferences.getString(PAGE_METHOD_PREF, PAGE_METHOD_PREF_DEFAULT_VALUE)
companion object {
private const val SCANLATOR_PREF = "scanlatorPref"
private const val SCANLATOR_PREF_TITLE = "Mostrar todos los scanlator"
private const val SCANLATOR_PREF_SUMMARY = "Se mostraran capítulos repetidos pero con diferentes Scanlators"
private const val SCANLATOR_PREF_DEFAULT_VALUE = true
private const val SFW_MODE_PREF = "SFWModePref"
private const val SFW_MODE_PREF_TITLE = "Ocultar contenido NSFW"
private const val SFW_MODE_PREF_SUMMARY = "Ocultar el contenido erótico (puede que aún activandolo se sigan mostrando portadas o series NSFW). Ten en cuenta que al activarlo se ignoran filtros al explorar y buscar.\nLos filtros ignorados son: Filtrar por tipo de contenido (Erotico) y el Filtrar por generos: Ecchi, Boys Love, Girls Love y Harem."
private const val SFW_MODE_PREF_DEFAULT_VALUE = false
private val SFW_MODE_PREF_EXCLUDE_GENDERS = listOf("6", "17", "18", "19")
private const val PAGE_METHOD_PREF = "pageMethodPref"
private const val PAGE_METHOD_PREF_TITLE = "Método para descargar imágenes"
private const val PAGE_METHOD_PREF_SUMMARY = "Previene ser banneado por el servidor cuando se usa la configuración \"Cascada\" ya que esta reduce la cantidad de solicitudes.\nPuedes usar \"Páginado\" cuando las imágenes no carguen usando \"Cascada\".\nConfiguración actual: %s"
private const val PAGE_METHOD_PREF_DEFAULT_VALUE = "cascade"
private const val WEB_RATELIMIT_PREF = "webRatelimitPreference"
// Ratelimit permits per second for main website
private const val WEB_RATELIMIT_PREF_TITLE = "Ratelimit por minuto para el sitio web"
// This value affects network request amount to TMO url. Lower this value may reduce the chance to get HTTP 429 error, but loading speed will be slower too. Tachiyomi restart required. \nCurrent value: %s
private const val WEB_RATELIMIT_PREF_SUMMARY = "Este valor afecta la cantidad de solicitudes de red a la URL de TMO. Reducir este valor puede disminuir la posibilidad de obtener un error HTTP 429, pero la velocidad de descarga será más lenta. Se requiere reiniciar Tachiyomi. \nValor actual: %s"
private const val WEB_RATELIMIT_PREF_DEFAULT_VALUE = "10"
private const val IMAGE_CDN_RATELIMIT_PREF = "imgCDNRatelimitPreference"
// Ratelimit permits per second for image CDN
private const val IMAGE_CDN_RATELIMIT_PREF_TITLE = "Ratelimit por minuto para descarga de imágenes"
// This value affects network request amount for loading image. Lower this value may reduce the chance to get error when loading image, but loading speed will be slower too. Tachiyomi restart required. \nCurrent value: %s
private const val IMAGE_CDN_RATELIMIT_PREF_SUMMARY = "Este valor afecta la cantidad de solicitudes de red para descargar imágenes. Reducir este valor puede disminuir errores al cargar imagenes, pero la velocidad de descarga será más lenta. Se requiere reiniciar Tachiyomi. \nValor actual: %s"
private const val IMAGE_CDN_RATELIMIT_PREF_DEFAULT_VALUE = "10"
private val ENTRIES_ARRAY = (1..10).map { i -> i.toString() }.toTypedArray()
const val PREFIX_LIBRARY = "library"
const val PREFIX_ID_SEARCH = "id:"
private val SORTABLES = listOf(
Pair("Me gusta", "likes_count"),
Pair("Alfabético", "alphabetically"),
Pair("Puntuación", "score"),
Pair("Creación", "creation"),
Pair("Fecha estreno", "release_date"),
Pair("Núm. Capítulos", "num_chapters")
)
}
}
| apache-2.0 | adf2cdacec77acf3a79b1a31aa67c18a | 43.601739 | 355 | 0.6045 | 4.401236 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/mine/activity/SettingPreferenceActivity.kt | 1 | 2913 | package com.intfocus.template.dashboard.mine.activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import com.intfocus.template.R
import com.intfocus.template.ui.BaseActivity
import com.intfocus.template.util.CacheCleanManager
import kotlinx.android.synthetic.main.activity_setting_preference.*
/**
* Created by liuruilin on 2017/3/28.
*/
class SettingPreferenceActivity : BaseActivity() {
private var mSharedPreferences: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setting_preference)
initSwitchPreference()
initListener()
}
override fun onResume() {
super.onResume()
switch_screenLock!!.isChecked = mSharedPreferences!!.getBoolean("ScreenLock", false)
}
/**
* Switch 状态初始化
*/
private fun initSwitchPreference() {
mSharedPreferences = getSharedPreferences("SettingPreference", Context.MODE_PRIVATE)
switch_screenLock.isChecked = mSharedPreferences!!.getBoolean("ScreenLock", false)
switch_keep_pwd.isChecked = mSharedPreferences!!.getBoolean("keep_pwd", false)
switch_report_copy.isChecked = mSharedPreferences!!.getBoolean("ReportCopy", false)
switch_landscape_banner.isChecked = mSharedPreferences!!.getBoolean("Landscape", false)
}
private fun initListener() {
switch_screenLock.setOnCheckedChangeListener(mSwitchScreenLockListener)
switch_keep_pwd.setOnCheckedChangeListener(mSwitchKeepPwdListener)
switch_report_copy.setOnCheckedChangeListener(mSwitchReportCopyListener)
}
/**
* Switch ScreenLock 开关
*/
private val mSwitchScreenLockListener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
if (!buttonView.isPressed) {
return@OnCheckedChangeListener
}
if (isChecked) {
val intent = Intent(this@SettingPreferenceActivity, InitPassCodeActivity::class.java)
startActivity(intent)
} else {
mSharedPreferences!!.edit().putBoolean("ScreenLock", isChecked).apply()
}
}
/**
* Switch Keep Password 开关
*/
private val mSwitchKeepPwdListener = CompoundButton.OnCheckedChangeListener { _, isChecked -> mSharedPreferences!!.edit().putBoolean("keep_pwd", isChecked).apply() }
/**
* Switch Report Copy 开关
*/
private val mSwitchReportCopyListener = CompoundButton.OnCheckedChangeListener { _, isChecked -> mSharedPreferences!!.edit().putBoolean("ReportCopy", isChecked).apply() }
/**
* 清理缓存
*/
fun clearUserCache(view: View) {
CacheCleanManager.clearAppUserCache(this)
}
}
| gpl-3.0 | c7bb858f685d2b572e1c230c6424be70 | 34.592593 | 174 | 0.710024 | 4.919795 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/nine/module/text/MultiTextFragment.kt | 1 | 3065 | package com.intfocus.template.subject.nine.module.text
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.intfocus.template.R
import com.intfocus.template.constant.Params
import com.intfocus.template.ui.BaseModuleFragment
import kotlinx.android.synthetic.main.module_single_text.*
/**
* @author liuruilin
* @data 2017/11/3
* @describe
*/
class MultiTextFragment : BaseModuleFragment(), TextModuleContract.View {
private var rootView: View? = null
private lateinit var datas: TextEntity
private var param: String? = null
private var key: String? = null
private var listItemType: Int = 0
override lateinit var presenter: TextModuleContract.Presenter
companion object {
private val LIST_ITEM_TYPE = "list_item_type"
fun newInstance(param: String?, key: String?, listItemType: Int): MultiTextFragment {
val fragment = MultiTextFragment()
val args = Bundle()
args.putString(Params.ARG_PARAM, param)
args.putString(Params.KEY, key)
args.putInt(LIST_ITEM_TYPE, listItemType)
fragment.arguments = args
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
param = arguments!!.getString(Params.ARG_PARAM)
key = arguments!!.getString(Params.KEY)
listItemType = arguments!!.getInt(LIST_ITEM_TYPE)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (null == rootView) {
rootView = inflater.inflate(R.layout.module_multi_text, container, false)
}
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
param?.let {
presenter.loadData(it)
}
initView()
}
override fun onDestroy() {
super.onDestroy()
TextModelImpl.destroyInstance()
}
private fun initView() {
et_single_text.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(p0: Editable?) {
datas.value = p0.toString()
key?.let {
presenter.update(datas, it,listItemType)
}
}
})
}
override fun initModule(entity: TextEntity) {
datas = entity
if (entity.title.trim().isEmpty()) tv_single_text_title.visibility = View.GONE else tv_single_text_title.text = entity.title
if (entity.hint.trim().isEmpty()) et_single_text.hint = "" else et_single_text.hint = entity.hint
}
}
| gpl-3.0 | ad56a51ca4ab62ff1a2ef8cc74bbad8a | 32.681319 | 132 | 0.645351 | 4.416427 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt | 3 | 13784 | package info.nightscout.androidaps.plugins.pump.danaR.activities
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.DanaRHistoryRecord
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus.toObservable
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes
import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.danar_historyactivity.*
import org.slf4j.LoggerFactory
import java.util.*
class DanaRHistoryActivity : NoSplashAppCompatActivity() {
private val log = LoggerFactory.getLogger(L.PUMP)
private val disposable = CompositeDisposable()
private var showingType = RecordTypes.RECORD_TYPE_ALARM
private var historyList: List<DanaRHistoryRecord> = ArrayList()
class TypeList internal constructor(var type: Byte, var name: String) {
override fun toString(): String = name
}
override fun onResume() {
super.onResume()
disposable.add(toObservable(EventPumpStatusChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ danar_history_status.text = it.getStatus() }) { FabricPrivacy.logException(it) }
)
disposable.add(toObservable(EventDanaRSyncStatus::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (L.isEnabled(L.PUMP))
log.debug("EventDanaRSyncStatus: " + it.message)
danar_history_status.text = it.message
}) { FabricPrivacy.logException(it) }
)
}
override fun onPause() {
super.onPause()
disposable.clear()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.danar_historyactivity)
danar_history_recyclerview.setHasFixedSize(true)
danar_history_recyclerview.layoutManager = LinearLayoutManager(this)
danar_history_recyclerview.adapter = RecyclerViewAdapter(historyList)
danar_history_status.visibility = View.GONE
val isKorean = DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PUMP)
val isRS = DanaRSPlugin.getPlugin().isEnabled(PluginType.PUMP)
// Types
val typeList = ArrayList<TypeList>()
typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, MainApp.gs(R.string.danar_history_alarm)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, MainApp.gs(R.string.danar_history_basalhours)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, MainApp.gs(R.string.danar_history_bolus)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_CARBO, MainApp.gs(R.string.danar_history_carbohydrates)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, MainApp.gs(R.string.danar_history_dailyinsulin)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, MainApp.gs(R.string.danar_history_glucose)))
if (!isKorean && !isRS) {
typeList.add(TypeList(RecordTypes.RECORD_TYPE_ERROR, MainApp.gs(R.string.danar_history_errors)))
}
if (isRS) typeList.add(TypeList(RecordTypes.RECORD_TYPE_PRIME, MainApp.gs(R.string.danar_history_prime)))
if (!isKorean) {
typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, MainApp.gs(R.string.danar_history_refill)))
typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, MainApp.gs(R.string.danar_history_syspend)))
}
danar_history_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, typeList)
danar_history_reload.setOnClickListener {
val selected = danar_history_spinner.selectedItem as TypeList
runOnUiThread {
danar_history_reload?.visibility = View.GONE
danar_history_status?.visibility = View.VISIBLE
}
clearCardView()
ConfigBuilderPlugin.getPlugin().commandQueue.loadHistory(selected.type, object : Callback() {
override fun run() {
loadDataFromDB(selected.type)
runOnUiThread {
danar_history_reload?.visibility = View.VISIBLE
danar_history_status?.visibility = View.GONE
}
}
})
}
danar_history_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val selected = danar_history_spinner?.selectedItem as TypeList? ?: return
loadDataFromDB(selected.type)
showingType = selected.type
}
override fun onNothingSelected(parent: AdapterView<*>?) {
clearCardView()
}
}
}
inner class RecyclerViewAdapter internal constructor(private var historyList: List<DanaRHistoryRecord>) : RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): HistoryViewHolder =
HistoryViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.danar_history_item, viewGroup, false))
override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
val record = historyList[position]
holder.time.text = DateUtil.dateAndTimeString(record.recordDate)
holder.value.text = DecimalFormatter.to2Decimal(record.recordValue)
holder.stringValue.text = record.stringRecordValue
holder.bolusType.text = record.bolusType
holder.duration.text = DecimalFormatter.to0Decimal(record.recordDuration.toDouble())
holder.alarm.text = record.recordAlarm
when (showingType) {
RecordTypes.RECORD_TYPE_ALARM -> {
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.VISIBLE
holder.stringValue.visibility = View.GONE
holder.bolusType.visibility = View.GONE
holder.duration.visibility = View.GONE
holder.dailyBasal.visibility = View.GONE
holder.dailyBolus.visibility = View.GONE
holder.dailyTotal.visibility = View.GONE
holder.alarm.visibility = View.VISIBLE
}
RecordTypes.RECORD_TYPE_BOLUS -> {
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.VISIBLE
holder.stringValue.visibility = View.GONE
holder.bolusType.visibility = View.VISIBLE
holder.duration.visibility = View.VISIBLE
holder.dailyBasal.visibility = View.GONE
holder.dailyBolus.visibility = View.GONE
holder.dailyTotal.visibility = View.GONE
holder.alarm.visibility = View.GONE
}
RecordTypes.RECORD_TYPE_DAILY -> {
holder.dailyBasal.text = MainApp.gs(R.string.formatinsulinunits, record.recordDailyBasal)
holder.dailyBolus.text = MainApp.gs(R.string.formatinsulinunits, record.recordDailyBolus)
holder.dailyTotal.text = MainApp.gs(R.string.formatinsulinunits, record.recordDailyBolus + record.recordDailyBasal)
holder.time.text = DateUtil.dateString(record.recordDate)
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.GONE
holder.stringValue.visibility = View.GONE
holder.bolusType.visibility = View.GONE
holder.duration.visibility = View.GONE
holder.dailyBasal.visibility = View.VISIBLE
holder.dailyBolus.visibility = View.VISIBLE
holder.dailyTotal.visibility = View.VISIBLE
holder.alarm.visibility = View.GONE
}
RecordTypes.RECORD_TYPE_GLUCOSE -> {
holder.value.text = Profile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, ProfileFunctions.getSystemUnits())
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.VISIBLE
holder.stringValue.visibility = View.GONE
holder.bolusType.visibility = View.GONE
holder.duration.visibility = View.GONE
holder.dailyBasal.visibility = View.GONE
holder.dailyBolus.visibility = View.GONE
holder.dailyTotal.visibility = View.GONE
holder.alarm.visibility = View.GONE
}
RecordTypes.RECORD_TYPE_CARBO, RecordTypes.RECORD_TYPE_BASALHOUR, RecordTypes.RECORD_TYPE_ERROR, RecordTypes.RECORD_TYPE_PRIME, RecordTypes.RECORD_TYPE_REFILL, RecordTypes.RECORD_TYPE_TB -> {
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.VISIBLE
holder.stringValue.visibility = View.GONE
holder.bolusType.visibility = View.GONE
holder.duration.visibility = View.GONE
holder.dailyBasal.visibility = View.GONE
holder.dailyBolus.visibility = View.GONE
holder.dailyTotal.visibility = View.GONE
holder.alarm.visibility = View.GONE
}
RecordTypes.RECORD_TYPE_SUSPEND -> {
holder.time.visibility = View.VISIBLE
holder.value.visibility = View.GONE
holder.stringValue.visibility = View.VISIBLE
holder.bolusType.visibility = View.GONE
holder.duration.visibility = View.GONE
holder.dailyBasal.visibility = View.GONE
holder.dailyBolus.visibility = View.GONE
holder.dailyTotal.visibility = View.GONE
holder.alarm.visibility = View.GONE
}
}
}
override fun getItemCount(): Int {
return historyList.size
}
inner class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var time: TextView = itemView.findViewById(R.id.danar_history_time)
var value: TextView = itemView.findViewById(R.id.danar_history_value)
var bolusType: TextView = itemView.findViewById(R.id.danar_history_bolustype)
var stringValue: TextView = itemView.findViewById(R.id.danar_history_stringvalue)
var duration: TextView = itemView.findViewById(R.id.danar_history_duration)
var dailyBasal: TextView = itemView.findViewById(R.id.danar_history_dailybasal)
var dailyBolus: TextView = itemView.findViewById(R.id.danar_history_dailybolus)
var dailyTotal: TextView = itemView.findViewById(R.id.danar_history_dailytotal)
var alarm: TextView = itemView.findViewById(R.id.danar_history_alarm)
}
}
private fun loadDataFromDB(type: Byte) {
historyList = MainApp.getDbHelper().getDanaRHistoryRecordsByType(type)
runOnUiThread { danar_history_recyclerview?.swapAdapter(RecyclerViewAdapter(historyList), false) }
}
private fun clearCardView() {
historyList = ArrayList()
runOnUiThread { danar_history_recyclerview?.swapAdapter(RecyclerViewAdapter(historyList), false) }
}
} | agpl-3.0 | 8ad340fa97e7da142c0b11b3d45a36aa | 54.584677 | 207 | 0.623984 | 5.045388 | false | false | false | false |
maxmil/kool-kotlin | src/test/kotlin/my/favorite/kotlin/features/Presentation.kt | 1 | 12250 | package my.favorite.kotlin.features
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.TextNode
import my.favorite.kotlin.features.ClassDelegates.*
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.Test
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
/*
________ __ __
| \ | \ | \
| $$$$$$$$ __ __ _| $$_ ______ _______ _______ \$$ ______ _______
| $$__ | \ / \| $$ \ / \ | \ / \| \ / \ | \
| $$ \ \$$\/ $$ \$$$$$$ | $$$$$$\| $$$$$$$\| $$$$$$$| $$| $$$$$$\| $$$$$$$\
| $$$$$ >$$ $$ | $$ __ | $$ $$| $$ | $$ \$$ \ | $$| $$ | $$| $$ | $$
| $$_____ / $$$$\ | $$| \| $$$$$$$$| $$ | $$ _\$$$$$$\| $$| $$__/ $$| $$ | $$
| $$ \| $$ \$$\ \$$ $$ \$$ \| $$ | $$| $$| $$ \$$ $$| $$ | $$
\$$$$$$$$ \$$ \$$ \$$$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$ \$$$$$$ \$$ \$$
______ __ __
/ \ | \ | \
| $$$$$$\ __ __ _______ _______ _| $$_ \$$ ______ _______ _______
| $$_ \$$| \ | \| \ / \| $$ \ | \ / \ | \ / \
| $$ \ | $$ | $$| $$$$$$$\| $$$$$$$ \$$$$$$ | $$| $$$$$$\| $$$$$$$\| $$$$$$$
| $$$$ | $$ | $$| $$ | $$| $$ | $$ __ | $$| $$ | $$| $$ | $$ \$$ \
| $$ | $$__/ $$| $$ | $$| $$_____ | $$| \| $$| $$__/ $$| $$ | $$ _\$$$$$$\
| $$ \$$ $$| $$ | $$ \$$ \ \$$ $$| $$ \$$ $$| $$ | $$| $$
\$$ \$$$$$$ \$$ \$$ \$$$$$$$ \$$$$ \$$ \$$$$$$ \$$ \$$ \$$$$$$$
*/
fun String.echo(): Unit {
println(this)
}
data class Person(val name: String)
val node = TextNode("bob")
fun toPerson(node: JsonNode) = Person(node.asText())
fun isCalledBob(person: Person) = person.name == "bob"
val isBob = isCalledBob(toPerson(node))
class LeftToRight {
fun JsonNode.toPerson() = Person(asText())
fun Person.isCalledBob() = name == "bob"
val isBob = node.toPerson().isCalledBob()
@Test
fun `Left to right gives the same result`() {
assertThat(LeftToRight().isBob).isEqualTo(isBob)
}
}
/*
javap build.kotlin-classes.test.my.favorite.kotlin.features.LeftToRight
Warning: Binary file build.kotlin-classes.test.my.favorite.kotlin.features.LeftToRight contains my.favorite.kotlin.features.LeftToRight
Compiled from "Presentation.kt"
public final class my.favorite.kotlin.features.LeftToRight {
public final my.favorite.kotlin.features.Person toPerson(com.fasterxml.jackson.databind.JsonNode);
public final boolean isCalledBob(my.favorite.kotlin.features.Person);
public final boolean isBob();
public final void Left to right gives the same result();
public my.favorite.kotlin.features.LeftToRight();
}
*/
class ExtensionFunctionsCanExtendFunctions {
fun (() -> String).timeBoxed(timeout: Long, unit: TimeUnit): () -> String = {
Executors.newSingleThreadExecutor().submit(Callable { this() }).get(timeout, unit)
}
val waitForOneSecondAndThenSayHi: () -> String = {
Thread.sleep(1000)
"Hi"
}
@Test
fun `Times out when timeBoxed 100 milliseconds`() {
val timeBoxed100Millis = waitForOneSecondAndThenSayHi.timeBoxed(100, TimeUnit.MILLISECONDS)
assertThatExceptionOfType(TimeoutException::class.java).isThrownBy { timeBoxed100Millis() }
}
@Test
fun `Does not time out when timeBoxed 2 seconds`() {
val timeBoxed2Seconds = waitForOneSecondAndThenSayHi.timeBoxed(2, TimeUnit.SECONDS)
assertThat(timeBoxed2Seconds()).isEqualTo("Hi")
}
}
/*
__ __ __ __ __ __
| \ | \ | \| \ | \ | \
| $$\ | $$ __ __ | $$| $$ ______ | $$____ | $$ ______
| $$$\| $$| \ | \| $$| $$ | \ | $$ \ | $$ / \
| $$$$\ $$| $$ | $$| $$| $$ \$$$$$$\| $$$$$$$\| $$| $$$$$$\
| $$\$$ $$| $$ | $$| $$| $$ / $$| $$ | $$| $$| $$ $$
| $$ \$$$$| $$__/ $$| $$| $$| $$$$$$$| $$__/ $$| $$| $$$$$$$$
| $$ \$$$ \$$ $$| $$| $$ \$$ $$| $$ $$| $$ \$$ \
\$$ \$$ \$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$ \$$ \$$$$$$$
________
| \
\$$$$$$$$__ __ ______ ______ _______
| $$ | \ | \ / \ / \ / \
| $$ | $$ | $$| $$$$$$\| $$$$$$\| $$$$$$$
| $$ | $$ | $$| $$ | $$| $$ $$ \$$ \
| $$ | $$__/ $$| $$__/ $$| $$$$$$$$ _\$$$$$$\
| $$ \$$ $$| $$ $$ \$$ \| $$
\$$ _\$$$$$$$| $$$$$$$ \$$$$$$$ \$$$$$$$
| \__| $$| $$
\$$ $$| $$
\$$$$$$ \$$
Tony Hoare introduced Null references in ALGOL W back in 1965,
in his own words "simply because it was so easy to implement".
He has now spoken about that decision as a "my billion-dollar mistake".
*/
class NullTypes {
var nullString: String? = null
var nonNullString: String = ""
// They are still types where the nullable type is a super type of the non null type
val `nonNullString is a super type Of nullString`: String? = nonNullString
// val `null string is a sub type of nonNullString`: String = nullString
// Applies to user defined types not just platform types
}
class SmartCast {
val nullString: String? = null
fun doTheMagic(){
if (nullString != null) println(nullString.length)
// println(nullString.length)
}
}
class ExtendNullTypes {
fun String?.withDefault(default:String = ""):String = if (this == null) default else this
fun List<String>?.add(s: String) = if (this == null) listOf(s) else this + s
@Test
fun `Default value for null string`() {
val nullString: String? = null
assertThat(nullString.withDefault()).isEqualTo("")
}
@Test
fun `Can add to null list`() {
val nullList: List<String>? = null
assertThat(nullList.add("some")).isEqualTo(listOf("some"))
}
}
class NullableTypeParameters {
fun <T : Any> notNull(thing: T) = if (thing == null) throw NullPointerException() else thing
fun <T : Any> possiblyNull(thing: T?) = if (thing == null) throw NullPointerException() else thing
}
/*
______ __
/ \ | \
| $$$$$$\| $$ ______ _______ _______
| $$ \$$| $$ | \ / \ / \
| $$ | $$ \$$$$$$\| $$$$$$$| $$$$$$$
| $$ __ | $$ / $$ \$$ \ \$$ \
| $$__/ \| $$| $$$$$$$ _\$$$$$$\ _\$$$$$$\
\$$ $$| $$ \$$ $$| $$| $$
\$$$$$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$$$$
_______ __ __
| \ | \ | \
| $$$$$$$\ ______ | $$ ______ ______ ______ _| $$_ ______ _______
| $$ | $$ / \ | $$ / \ / \ | \| $$ \ / \ / \
| $$ | $$| $$$$$$\| $$| $$$$$$\| $$$$$$\ \$$$$$$\\$$$$$$ | $$$$$$\| $$$$$$$
| $$ | $$| $$ $$| $$| $$ $$| $$ | $$ / $$ | $$ __ | $$ $$ \$$ \
| $$__/ $$| $$$$$$$$| $$| $$$$$$$$| $$__| $$| $$$$$$$ | $$| \| $$$$$$$$ _\$$$$$$\
| $$ $$ \$$ \| $$ \$$ \ \$$ $$ \$$ $$ \$$ $$ \$$ \| $$
\$$$$$$$ \$$$$$$$ \$$ \$$$$$$$ _\$$$$$$$ \$$$$$$$ \$$$$ \$$$$$$$ \$$$$$$$
| \__| $$
\$$ $$
\$$$$$$
*/
class ClassDelegates {
interface Drummer {
fun hiphop(): String
fun bosanova(): String
fun rock(): String
fun funky(): String
}
interface Singer {
fun doe(): String
fun re(): String
fun mi(): String
fun fa(): String
fun sol(): String
fun la(): String
fun si(): String
}
class OneRhythmDrummer : Drummer {
override fun hiphop() = "Boom Cha Boom Boom Cha"
override fun bosanova() = "Boom Cha Boom Boom Cha"
override fun rock() = "Boom Cha Boom Boom Cha"
override fun funky() = "Boom Cha Boom Boom Cha"
}
class DrunkenSinger : Singer {
override fun `doe`() = "miiiiiii"
override fun re() = "laaaaaa"
override fun mi() = "soooooool"
override fun fa() = "siiiiiiii"
override fun sol() = "dooooooo"
override fun la() = "faaaaaaa"
override fun si() = "reeeeeee"
}
}
class KotlinOneManBand : Drummer by OneRhythmDrummer(), Singer by DrunkenSinger()
/*
_______ __ __
| \ | \ | \
| $$$$$$$\ ______ _| $$_ _| $$_ ______ ______
| $$__/ $$ / \| $$ \| $$ \ / \ / \
| $$ $$| $$$$$$\\$$$$$$ \$$$$$$ | $$$$$$\| $$$$$$\
| $$$$$$$\| $$ $$ | $$ __ | $$ __ | $$ $$| $$ \$$
| $$__/ $$| $$$$$$$$ | $$| \| $$| \| $$$$$$$$| $$
| $$ $$ \$$ \ \$$ $$ \$$ $$ \$$ \| $$
\$$$$$$$ \$$$$$$$ \$$$$ \$$$$ \$$$$$$$ \$$
__
| \
______ ______ _______ ______ ______ \$$ _______ _______
/ \ / \ | \ / \ / \ | \ / \ / \
| $$$$$$\| $$$$$$\| $$$$$$$\| $$$$$$\| $$$$$$\| $$| $$$$$$$| $$$$$$$
| $$ | $$| $$ $$| $$ | $$| $$ $$| $$ \$$| $$| $$ \$$ \
| $$__| $$| $$$$$$$$| $$ | $$| $$$$$$$$| $$ | $$| $$_____ _\$$$$$$\
\$$ $$ \$$ \| $$ | $$ \$$ \| $$ | $$ \$$ \| $$
_\$$$$$$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$
| \__| $$
\$$ $$
\$$$$$$
*/
// The covariance problem
class InOutAndShakeItAllAbout {
class Box<T>
fun covariantAssign(boxOfInteger: Box<Int>) {
// val boxOfNumber:Box<Number> = boxOfInteger
}
}
interface EasyToReadTypeSignatures {
// In Java for a Stream<T> the signature for flat map looks like this
//<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
interface Function<in T, out R>
interface Stream<out T> {
fun <R> flatMap(f: Function<T, R>): Stream<R>
}
}
class ReifiedGenerics {
inline fun <reified T : Any> genericTypeOf(list: List<T>) = T::class
@Test
fun `Can get class name of generic list`() {
assertThat(genericTypeOf(listOf("one", "two", "three"))).isEqualTo(String::class)
assertThat(genericTypeOf(listOf(1, 2, 3))).isEqualTo(Integer::class)
}
}
/*
______ __ __ __ ______ ______
/ \ | \ | \ | \ / \ / \
| $$$$$$\ _| $$_ | $$____ ______ ______ _______ _| $$_ __ __ | $$$$$$\| $$$$$$\
| $$ | $$| $$ \ | $$ \ / \ / \ / \| $$ \ | \ | \| $$_ \$$| $$_ \$$
| $$ | $$ \$$$$$$ | $$$$$$$\| $$$$$$\| $$$$$$\ | $$$$$$$ \$$$$$$ | $$ | $$| $$ \ | $$ \
| $$ | $$ | $$ __ | $$ | $$| $$ $$| $$ \$$ \$$ \ | $$ __ | $$ | $$| $$$$ | $$$$
| $$__/ $$ | $$| \| $$ | $$| $$$$$$$$| $$ _\$$$$$$\ | $$| \| $$__/ $$| $$ | $$
\$$ $$ \$$ $$| $$ | $$ \$$ \| $$ | $$ \$$ $$ \$$ $$| $$ | $$
\$$$$$$ \$$$$ \$$ \$$ \$$$$$$$ \$$ \$$$$$$$ \$$$$ \$$$$$$ \$$ \$$
- Everything is an expression (except an assignment)
- Algebraic data types
- Type inference
- Operator overloading
- Smart casts
- Named arguments
- Default arguments
- Data classes
- Tail recursion
- Delegated properties
- Infix function notation
- String templates`
*/
| apache-2.0 | 416bd93a1a7c9313dc981757749a4f73 | 17.310912 | 135 | 0.346449 | 2.853482 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/SimpleCourseListsDefaultAdapterDelegate.kt | 1 | 3780 | package org.stepik.android.view.catalog.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.header_catalog_block.*
import kotlinx.android.synthetic.main.item_block_simple_course_lists_default.*
import org.stepic.droid.R
import org.stepic.droid.ui.util.CoursesSnapHelper
import org.stepik.android.domain.catalog.model.CatalogCourseList
import org.stepik.android.presentation.course_list_redux.model.CatalogBlockStateWrapper
import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager
import org.stepik.android.view.catalog.mapper.CourseCountMapper
import org.stepik.android.view.catalog.model.CatalogItem
import org.stepik.android.view.catalog.ui.delegate.CatalogBlockHeaderDelegate
import ru.nobird.android.core.model.cast
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class SimpleCourseListsDefaultAdapterDelegate(
private val courseCountMapper: CourseCountMapper,
private val onCourseListClicked: (CatalogCourseList) -> Unit
) : AdapterDelegate<CatalogItem, DelegateViewHolder<CatalogItem>>() {
private val sharedViewPool = RecyclerView.RecycledViewPool()
override fun isForViewType(position: Int, data: CatalogItem): Boolean =
data is CatalogItem.Block && data.catalogBlockStateWrapper is CatalogBlockStateWrapper.SimpleCourseListsDefault
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogItem> =
ViewHolder(createView(parent, R.layout.item_block_simple_course_lists_default))
private inner class ViewHolder(
override val containerView: View
) : DelegateViewHolder<CatalogItem>(containerView), LayoutContainer {
private val catalogBlockTitleDelegate =
CatalogBlockHeaderDelegate(catalogBlockContainer, null)
private val adapter = DefaultDelegateAdapter<CatalogCourseList>()
.also {
it += SimpleCourseListDefaultAdapterDelegate(courseCountMapper, onCourseListClicked)
}
init {
val rowCount = context.resources.getInteger(R.integer.simple_course_lists_default_rows)
courseListsRecycler.layoutManager =
TableLayoutManager(
context,
horizontalSpanCount = context.resources.getInteger(R.integer.simple_course_lists_default_columns),
verticalSpanCount = rowCount,
orientation = LinearLayoutManager.HORIZONTAL,
reverseLayout = false
)
courseListsRecycler.setRecycledViewPool(sharedViewPool)
courseListsRecycler.setHasFixedSize(true)
courseListsRecycler.adapter = adapter
val snapHelper = CoursesSnapHelper(rowCount)
snapHelper.attachToRecyclerView(courseListsRecycler)
}
override fun onBind(data: CatalogItem) {
val simpleCourseListsDefault = data
.cast<CatalogItem.Block>()
.catalogBlockStateWrapper
.cast<CatalogBlockStateWrapper.SimpleCourseListsDefault>()
adapter.items = simpleCourseListsDefault.content.courseLists
catalogBlockTitleDelegate.setInformation(simpleCourseListsDefault.catalogBlockItem)
val count = simpleCourseListsDefault.content.courseLists.size
catalogBlockTitleDelegate.setCount(context.resources.getQuantityString(R.plurals.catalog_course_lists, count, count))
}
}
} | apache-2.0 | b45623ff91a0e5897c4a4c51b7e98abe | 48.103896 | 129 | 0.748677 | 5.178082 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectAndroidTest/app/src/main/java/me/liuqingwen/android/projectandroidtest/notedetail/NoteDetailFragment.kt | 1 | 7952 | package me.liuqingwen.android.projectandroidtest.notedetail
import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.support.constraint.ConstraintLayout.LayoutParams.PARENT_ID
import android.widget.ProgressBar
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import org.jetbrains.anko.constraint.layout.ConstraintSetBuilder.Side.*
import kotlinx.android.synthetic.main.laoyut_fragment_add_note.view.*
import kotlinx.android.synthetic.main.layout_fragment_note_detail.view.*
import me.liuqingwen.android.projectandroidtest.FloatingButtonType
import me.liuqingwen.android.projectandroidtest.IMainInteractionListener
import me.liuqingwen.android.projectandroidtest.R
import me.liuqingwen.android.projectandroidtest.data.InMemoryNotesRepository
import me.liuqingwen.android.projectandroidtest.data.InMemoryNotesServiceApi
import me.liuqingwen.android.projectandroidtest.data.Note
import me.liuqingwen.android.projectandroidtest.data.NotesRepositories
import me.liuqingwen.android.projectandroidtest.noteslist.NotesListFragment
import org.jetbrains.anko.*
import org.jetbrains.anko.constraint.layout.applyConstraintSet
import org.jetbrains.anko.constraint.layout.constraintLayout
import org.jetbrains.anko.constraint.layout.matchConstraint
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.find
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [NoteDetailFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [NoteDetailFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class NoteDetailFragment : Fragment(), INoteDetailContract.IView
{
interface OnFragmentInteractionListener:IMainInteractionListener
companion object
{
private const val PARAM_NOTE_ID = "NOTE_ID"
fun newInstance(noteId:Int) = NoteDetailFragment().apply {
this.arguments = Bundle().apply { this.putInt(NoteDetailFragment.PARAM_NOTE_ID, noteId) }
}
}
private var listener: OnFragmentInteractionListener? = null
private val repository by lazy(LazyThreadSafetyMode.NONE) { NotesRepositories.getRepository(InMemoryNotesServiceApi()) }
private val presenter by lazy(LazyThreadSafetyMode.NONE) { NoteDetailPresenter(this.repository, this) }
private val request by lazy(LazyThreadSafetyMode.NONE) { Glide.with(this).applyDefaultRequestOptions(RequestOptions().apply {
this.error(R.mipmap.ic_launcher)
this.placeholder(R.mipmap.ic_launcher)
this.centerCrop()
}).asDrawable() }
private var noteId : Int = 0
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
this.arguments?.let {
this.noteId = it.getInt(NoteDetailFragment.PARAM_NOTE_ID)
}
this.listener?.setTitle("Notes: ${this.noteId}")
this.listener?.configFloatingButton(FloatingButtonType.NONE, false, null)
}
override fun displayMissingNote()
{
val labelTitle = this.find<TextView>(NoteDetailUI.ID_LABEL_TITLE)
labelTitle.text = ""
val labelContent = this.find<TextView>(NoteDetailUI.ID_LABEL_CONTENT)
labelContent.text = "No data!"
val imageContent = this.find<ImageView>(NoteDetailUI.ID_IMAGE_CONTENT)
imageContent.setImageDrawable(this.resources.getDrawable(R.mipmap.ic_launcher_round))
}
override fun showProgress()
{
val progressBar = this.find<ProgressBar>(NoteDetailUI.ID_PROGRESS_BAR)
progressBar.visibility = View.VISIBLE
}
override fun hideProgress()
{
val progressBar = this.find<ProgressBar>(NoteDetailUI.ID_PROGRESS_BAR)
progressBar.visibility = View.GONE
}
override fun displayNote(note: Note)
{
val labelTitle = this.find<TextView>(NoteDetailUI.ID_LABEL_TITLE)
labelTitle.text = note.title
val labelContent = this.find<TextView>(NoteDetailUI.ID_LABEL_CONTENT)
labelContent.text = note.content
val imageContent = this.find<ImageView>(NoteDetailUI.ID_IMAGE_CONTENT)
this.request.load(note.image).into(imageContent)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
NoteDetailUI().createView(AnkoContext.create(this.ctx, this, false))
override fun onStart()
{
super.onStart()
this.presenter.getNote(this.noteId)
}
override fun onAttach(context: Context)
{
super.onAttach(context)
this.listener = if (context is OnFragmentInteractionListener) context else throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
override fun onDetach()
{
super.onDetach()
listener = null
}
override fun onDestroy()
{
super.onDestroy()
this.presenter.dispose()
}
}
class NoteDetailUI:AnkoComponent<Fragment>
{
companion object
{
const val ID_PROGRESS_BAR = 0x11
const val ID_LABEL_TITLE = 0x12
const val ID_LABEL_CONTENT = 0x13
const val ID_IMAGE_CONTENT = 0x14
}
override fun createView(ui: AnkoContext<Fragment>) = with(ui){
scrollView {
constraintLayout {
horizontalProgressBar {
id = ID_PROGRESS_BAR
isIndeterminate = true
}.lparams(width = matchConstraint, height = wrapContent)
textView {
id = ID_LABEL_TITLE
textSize = 24.0f
textColor = Color.MAGENTA
}.lparams(width = matchConstraint, height = wrapContent)
textView {
id = ID_LABEL_CONTENT
textSize = 18.0f
}.lparams(width = matchConstraint, height = wrapContent)
imageView {
id = ID_IMAGE_CONTENT
scaleType = ImageView.ScaleType.FIT_CENTER
}.lparams(width = wrapContent, height = wrapContent)
applyConstraintSet {
connect(
TOP of ID_PROGRESS_BAR to TOP of PARENT_ID margin dip(8),
START of ID_PROGRESS_BAR to START of PARENT_ID margin dip(8),
END of ID_PROGRESS_BAR to END of PARENT_ID margin dip(8),
TOP of ID_LABEL_TITLE to BOTTOM of ID_PROGRESS_BAR margin dip(8),
START of ID_LABEL_TITLE to START of PARENT_ID margin dip(8),
END of ID_LABEL_TITLE to END of PARENT_ID margin dip(8),
TOP of ID_LABEL_CONTENT to BOTTOM of ID_LABEL_TITLE margin dip(8),
START of ID_LABEL_CONTENT to START of PARENT_ID margin dip(8),
END of ID_LABEL_CONTENT to END of PARENT_ID margin dip(8),
START of ID_IMAGE_CONTENT to START of PARENT_ID margin dip(8),
END of ID_IMAGE_CONTENT to END of PARENT_ID margin dip(8),
TOP of ID_IMAGE_CONTENT to BOTTOM of ID_LABEL_CONTENT margin dip(8)
)
}
}.lparams(width = matchParent, height = matchParent)
}
}
}
| mit | ee9eb553649f2cfaf325d471143e5b8e | 37.790244 | 175 | 0.647762 | 4.801932 | false | false | false | false |
da1z/intellij-community | platform/script-debugger/backend/src/debugger/BreakpointManagerBase.kt | 3 | 4987 | /*
* 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 org.jetbrains.debugger
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.containers.ContainerUtil
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.concurrency.*
import java.util.concurrent.ConcurrentMap
abstract class BreakpointManagerBase<T : BreakpointBase<*>> : BreakpointManager {
override val breakpoints = ContainerUtil.newConcurrentSet<T>()
protected val breakpointDuplicationByTarget: ConcurrentMap<T, T> = ConcurrentCollectionFactory.createMap<T, T>(object : TObjectHashingStrategy<T> {
override fun computeHashCode(b: T): Int {
var result = b.line
result *= 31 + b.column
if (b.condition != null) {
result *= 31 + b.condition!!.hashCode()
}
result *= 31 + b.target.hashCode()
return result
}
override fun equals(b1: T, b2: T) = b1.target.javaClass == b2.target.javaClass && b1.target == b2.target && b1.line == b2.line && b1.column == b2.column && StringUtil.equals(b1.condition, b2.condition)
})
protected val dispatcher: EventDispatcher<BreakpointListener> = EventDispatcher.create(BreakpointListener::class.java)
protected abstract fun createBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): T
protected abstract fun doSetBreakpoint(target: BreakpointTarget, url: Url?, breakpoint: T): Promise<out Breakpoint>
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, url: Url?, condition: String?, ignoreCount: Int, enabled: Boolean, promiseRef: Ref<Promise<out Breakpoint>>?): Breakpoint {
val breakpoint = createBreakpoint(target, line, column, condition, ignoreCount, enabled)
val existingBreakpoint = breakpointDuplicationByTarget.putIfAbsent(breakpoint, breakpoint)
if (existingBreakpoint != null) {
promiseRef?.set(resolvedPromise(breakpoint))
return existingBreakpoint
}
breakpoints.add(breakpoint)
if (enabled) {
val promise = doSetBreakpoint(target, url, breakpoint)
.rejected { dispatcher.multicaster.errorOccurred(breakpoint, it.message ?: it.toString()) }
promiseRef?.set(promise)
}
else {
promiseRef?.set(resolvedPromise(breakpoint))
}
return breakpoint
}
override final fun remove(breakpoint: Breakpoint): Promise<*> {
@Suppress("UNCHECKED_CAST")
val b = breakpoint as T
val existed = breakpoints.remove(b)
if (existed) {
breakpointDuplicationByTarget.remove(b)
}
return if (!existed || !b.isVmRegistered()) nullPromise() else doClearBreakpoint(b)
}
override final fun removeAll(): Promise<*> {
val list = breakpoints.toList()
breakpoints.clear()
breakpointDuplicationByTarget.clear()
val promises = SmartList<Promise<*>>()
for (b in list) {
if (b.isVmRegistered()) {
promises.add(doClearBreakpoint(b))
}
}
return all(promises)
}
protected abstract fun doClearBreakpoint(breakpoint: T): Promise<*>
override final fun addBreakpointListener(listener: BreakpointListener) {
dispatcher.addListener(listener)
}
protected fun notifyBreakpointResolvedListener(breakpoint: T) {
if (breakpoint.isResolved) {
dispatcher.multicaster.resolved(breakpoint)
}
}
@Suppress("UNCHECKED_CAST")
override fun flush(breakpoint: Breakpoint) = (breakpoint as T).flush(this)
override fun enableBreakpoints(enabled: Boolean): Promise<*> = rejectedPromise<Any?>("Unsupported")
}
class DummyBreakpointManager : BreakpointManager {
override val breakpoints: Iterable<Breakpoint>
get() = emptyList()
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, url: Url?, condition: String?, ignoreCount: Int, enabled: Boolean, promiseRef: Ref<Promise<out Breakpoint>>?): Breakpoint {
throw UnsupportedOperationException()
}
override fun remove(breakpoint: Breakpoint) = nullPromise()
override fun addBreakpointListener(listener: BreakpointListener) {
}
override fun removeAll() = nullPromise()
override fun flush(breakpoint: Breakpoint) = nullPromise()
override fun enableBreakpoints(enabled: Boolean) = nullPromise()
} | apache-2.0 | 1d287636d03f690dae1d344339012b17 | 37.076336 | 205 | 0.733307 | 4.405477 | false | false | false | false |
apollostack/apollo-android | apollo-runtime-kotlin/src/appleMain/kotlin/com/apollographql/apollo3/network/ws/ApolloWebSocket.kt | 1 | 8829 | package com.apollographql.apollo3.network.ws
import com.apollographql.apollo3.exception.ApolloWebSocketException
import com.apollographql.apollo3.network.toNSData
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.asStableRef
import kotlinx.cinterop.staticCFunction
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import okio.ByteString
import okio.ByteString.Companion.toByteString
import okio.IOException
import okio.internal.commonAsUtf8ToByteArray
import okio.toByteString
import platform.Foundation.NSData
import platform.Foundation.NSError
import platform.Foundation.NSMutableURLRequest
import platform.Foundation.NSOperationQueue
import platform.Foundation.NSThread
import platform.Foundation.NSURL
import platform.Foundation.NSURLRequest
import platform.Foundation.NSURLSession
import platform.Foundation.NSURLSessionConfiguration
import platform.Foundation.NSURLSessionWebSocketCloseCode
import platform.Foundation.NSURLSessionWebSocketDelegateProtocol
import platform.Foundation.NSURLSessionWebSocketMessage
import platform.Foundation.NSURLSessionWebSocketMessageTypeData
import platform.Foundation.NSURLSessionWebSocketMessageTypeString
import platform.Foundation.NSURLSessionWebSocketTask
import platform.Foundation.setHTTPMethod
import platform.Foundation.setValue
import platform.darwin.NSObject
import platform.darwin.dispatch_async_f
import platform.darwin.dispatch_get_main_queue
import kotlin.native.concurrent.ensureNeverFrozen
import kotlin.native.concurrent.freeze
interface WebSocketConnectionListener {
fun onOpen(webSocket: NSURLSessionWebSocketTask)
fun onClose(webSocket: NSURLSessionWebSocketTask, code: NSURLSessionWebSocketCloseCode)
}
typealias NSWebSocketFactory = (NSURLRequest, WebSocketConnectionListener) -> NSURLSessionWebSocketTask
@ExperimentalCoroutinesApi
actual class ApolloWebSocketFactory(
private val serverUrl: NSURL,
private val headers: Map<String, String>,
private val webSocketFactory: NSWebSocketFactory
) : WebSocketFactory {
actual constructor(
serverUrl: String,
headers: Map<String, String>
) : this(
serverUrl = NSURL(string = serverUrl),
headers = headers,
webSocketFactory = { request, connectionListener ->
NSURLSession.sessionWithConfiguration(
configuration = NSURLSessionConfiguration.defaultSessionConfiguration,
delegate = NSURLSessionWebSocketDelegate(connectionListener),
delegateQueue = NSOperationQueue.mainQueue
).webSocketTaskWithRequest(request)
}
)
override suspend fun open(headers: Map<String, String>): WebSocketConnection {
assert(NSThread.isMainThread())
val request = NSMutableURLRequest.requestWithURL(serverUrl).apply {
[email protected]
.plus(headers)
.forEach { (key, value) -> setValue(value, forHTTPHeaderField = key) }
setHTTPMethod("GET")
}
val messageChannel = Channel<ByteString>(Channel.BUFFERED)
val isOpen = CompletableDeferred<Boolean>()
val connectionListener = object : WebSocketConnectionListener {
override fun onOpen(webSocket: NSURLSessionWebSocketTask) {
if (!isOpen.complete(true)) {
webSocket.cancel()
}
}
override fun onClose(webSocket: NSURLSessionWebSocketTask, code: NSURLSessionWebSocketCloseCode) {
isOpen.cancel()
messageChannel.close()
}
}
val webSocket = webSocketFactory(request, connectionListener)
.apply { resume() }
try {
isOpen.await()
return WebSocketConnectionImpl(
webSocket = webSocket,
messageChannel = messageChannel.apply { ensureNeverFrozen() }
)
} catch (e: Exception) {
webSocket.cancel()
throw e
}
}
}
@ExperimentalCoroutinesApi
private class WebSocketConnectionImpl(
val webSocket: NSURLSessionWebSocketTask,
val messageChannel: Channel<ByteString>
) : WebSocketConnection, ReceiveChannel<ByteString> by messageChannel {
init {
messageChannel.invokeOnClose {
webSocket.cancelWithCloseCode(
closeCode = 1001,
reason = null
)
}
receiveNext()
}
@Suppress("NAME_SHADOWING")
override fun send(data: ByteString) {
assert(NSThread.isMainThread())
if (!messageChannel.isClosedForReceive) {
val message = NSURLSessionWebSocketMessage(data.toByteArray().toNSData())
val webSocketConnectionPtr = StableRef.create(this).asCPointer()
val completionHandler = { error: NSError? ->
error?.dispatchOnMain(webSocketConnectionPtr)
Unit
}.freeze()
webSocket.sendMessage(message, completionHandler)
}
}
override fun close() {
assert(NSThread.isMainThread())
messageChannel.close()
}
@Suppress("NAME_SHADOWING")
internal fun receiveNext() {
assert(NSThread.isMainThread())
val webSocketConnectionPtr = StableRef.create(this).asCPointer()
val completionHandler = { message: NSURLSessionWebSocketMessage?, error: NSError? ->
error?.dispatchOnMain(webSocketConnectionPtr) ?: message?.dispatchOnMainAndRequestNext(webSocketConnectionPtr)
Unit
}
webSocket.receiveMessageWithCompletionHandler(completionHandler)
}
}
@Suppress("NAME_SHADOWING")
@ExperimentalCoroutinesApi
private fun NSError.dispatchOnMain(webSocketConnectionPtr: COpaquePointer) {
if (NSThread.isMainThread) {
dispatch(webSocketConnectionPtr)
} else {
dispatch_async_f(
queue = dispatch_get_main_queue(),
context = StableRef.create(freeze() to webSocketConnectionPtr).asCPointer(),
work = staticCFunction { ptr ->
val errorAndWebSocketConnectionRef = ptr!!.asStableRef<Pair<NSError, COpaquePointer>>()
val (error, webSocketConnectionPtr) = errorAndWebSocketConnectionRef.get()
errorAndWebSocketConnectionRef.dispose()
error.dispatch(webSocketConnectionPtr)
}
)
}
}
@ExperimentalCoroutinesApi
private fun NSError.dispatch(webSocketConnectionPtr: COpaquePointer) {
val webSocketConnectionRef = webSocketConnectionPtr.asStableRef<WebSocketConnectionImpl>()
val webSocketConnection = webSocketConnectionRef.get()
webSocketConnectionRef.dispose()
webSocketConnection.messageChannel.close(
ApolloWebSocketException(
message = "Web socket communication error",
cause = IOException(localizedDescription)
)
)
webSocketConnection.webSocket.cancel()
}
@Suppress("NAME_SHADOWING")
@ExperimentalCoroutinesApi
private fun NSURLSessionWebSocketMessage.dispatchOnMainAndRequestNext(webSocketConnectionPtr: COpaquePointer) {
if (NSThread.isMainThread) {
dispatchAndRequestNext(webSocketConnectionPtr)
} else {
dispatch_async_f(
queue = dispatch_get_main_queue(),
context = StableRef.create(freeze() to webSocketConnectionPtr).asCPointer(),
work = staticCFunction { ptr ->
val messageAndWebSocketConnectionRef = ptr!!.asStableRef<Pair<NSURLSessionWebSocketMessage, COpaquePointer>>()
val (message, webSocketConnectionPtr) = messageAndWebSocketConnectionRef.get()
messageAndWebSocketConnectionRef.dispose()
message.dispatchAndRequestNext(webSocketConnectionPtr)
}
)
}
}
@ExperimentalCoroutinesApi
private fun NSURLSessionWebSocketMessage.dispatchAndRequestNext(webSocketConnectionPtr: COpaquePointer) {
val webSocketConnectionRef = webSocketConnectionPtr.asStableRef<WebSocketConnectionImpl>()
val webSocketConnection = webSocketConnectionRef.get()
webSocketConnectionRef.dispose()
val data = when (type) {
NSURLSessionWebSocketMessageTypeData -> {
data?.toByteString()
}
NSURLSessionWebSocketMessageTypeString -> {
string?.commonAsUtf8ToByteArray()?.toByteString()
}
else -> null
}
try {
if (data != null) webSocketConnection.messageChannel.offer(data)
} catch (e: Exception) {
webSocketConnection.webSocket.cancel()
return
}
webSocketConnection.receiveNext()
}
private class NSURLSessionWebSocketDelegate(
val webSocketConnectionListener: WebSocketConnectionListener
) : NSObject(), NSURLSessionWebSocketDelegateProtocol {
override fun URLSession(session: NSURLSession, webSocketTask: NSURLSessionWebSocketTask, didOpenWithProtocol: String?) {
webSocketConnectionListener.onOpen(webSocketTask)
}
override fun URLSession(session: NSURLSession, webSocketTask: NSURLSessionWebSocketTask, didCloseWithCode: NSURLSessionWebSocketCloseCode, reason: NSData?) {
webSocketConnectionListener.onClose(webSocket = webSocketTask, code = didCloseWithCode)
}
}
| mit | 62886157024689774fdd90998fd0ebb7 | 33.22093 | 159 | 0.762487 | 4.907727 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/scaleddot/ScaledDotAttentionForwardHelper.kt | 1 | 2787 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.attention.scaleddot
import com.kotlinnlp.simplednn.core.functionalities.activations.SoftmaxBase
import com.kotlinnlp.simplednn.core.layers.helpers.ForwardHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The helper which executes the forward on a [layer].
*
* @property layer the [ScaledDotAttentionLayer] in which the forward is executed
*/
internal class ScaledDotAttentionForwardHelper(
override val layer: ScaledDotAttentionLayer
) : ForwardHelper<DenseNDArray>(layer) {
/**
* Forward the input to the output combining it with the parameters.
*
* A = Softmax((Q (dot) K') / sqrt(dk))
* Y = A (dot) V
*/
override fun forward() {
this.forwardInputs()
val q: DenseNDArray = this.layer.queries.values
val k: DenseNDArray = this.layer.keys.values
val vT: DenseNDArray = this.layer.values.values.t
this.layer.attention = q.dot(k.t).assignProd(this.layer.params.attentionFactor)
this.layer.attentionAct = this.layer.attention.getRows().map { SoftmaxBase().f(it).t }
this.layer.outputArrays.zip(this.layer.attentionAct).forEachIndexed { i, (y, a) ->
this.layer.dropoutMasks?.let {
y.assignValues(vT.dotRightMasked(a, mask = it[i]))
} ?: y.assignValues(vT.dot(a))
}
}
/**
* Forward the input to calculate queries, keys and values.
*
* Q = Wq (dot) I + Bq
* K = Wk (dot) I + Bk
* V = Wv (dot) I + Bv
*/
private fun forwardInputs() {
/**
* Add the same bias [b] to each row of [m].
*/
fun addBias(m: DenseNDArray, b: DenseNDArray) {
(0 until m.rows).forEach { i ->
(0 until m.columns).forEach { j ->
m[i, j] += b[j]
}
}
}
val x: DenseNDArray = this.layer.inputMatrix.values
val wQ: DenseNDArray = this.layer.params.queries.weights.values
val wK: DenseNDArray = this.layer.params.keys.weights.values
val wV: DenseNDArray = this.layer.params.values.weights.values
this.layer.queries.assignValues(x.dot(wQ.t))
this.layer.keys.assignValues(x.dot(wK.t))
this.layer.values.assignValues(x.dot(wV.t))
addBias(m = this.layer.queries.values, b = this.layer.params.queries.biases.values)
addBias(m = this.layer.keys.values, b = this.layer.params.keys.biases.values)
addBias(m = this.layer.values.values, b = this.layer.params.values.biases.values)
}
}
| mpl-2.0 | 297bcef14accacc70056be3d6d348ec9 | 33.407407 | 90 | 0.663079 | 3.492481 | false | false | false | false |
kevinmost/extensions-kotlin | core/src/main/java/com/kevinmost/koolbelt/extension/CollectionUtil.kt | 2 | 2160 | package com.kevinmost.koolbelt.extension
// Thanks to http://stackoverflow.com/a/37936456 and to Klutter
private class ImmutableIterator<T>(private val inner: Iterator<T>) : Iterator<T> by inner
private class ImmutableListIterator<T>(private val inner: ListIterator<T>) : ListIterator<T> by inner
private class ImmutableCollection<T>(private val delegate: Collection<T>) : Collection<T> by delegate {
override fun iterator(): Iterator<T> {
return delegate.iterator()
}
}
private class ImmutableList<T>(private val inner: List<T>) : List<T> by inner {
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
return inner.subList(fromIndex, toIndex).toImmutable()
}
override fun listIterator(index: Int): ListIterator<T> {
return inner.listIterator(index).toImmutable()
}
override fun listIterator(): ListIterator<T> {
return inner.listIterator().toImmutable()
}
override fun iterator(): Iterator<T> {
return inner.iterator().toImmutable()
}
}
private class ImmutableMap<K, V>(private val inner: Map<K, V>) : Map<K, V> by inner {
override val entries: Set<Map.Entry<K, V>>
get() = inner.entries.toImmutable()
override val keys: Set<K>
get() = inner.keys.toImmutable()
override val values: Collection<V>
get() = inner.values.toImmutable()
}
private class ImmutableSet<T>(private val inner: Set<T>) : Set<T> by inner {
override fun iterator(): Iterator<T> {
return inner.iterator().toImmutable()
}
}
fun <T> Iterator<T>.toImmutable(): Iterator<T> = if (this is Iterator<T>) this else ImmutableIterator(this)
fun <T> ListIterator<T>.toImmutable(): ListIterator<T> =
if (this is ListIterator<T>) this else ImmutableListIterator(this)
fun <T> Collection<T>.toImmutable(): Collection<T> =
if (this is ImmutableCollection<T>) this else ImmutableCollection(this)
fun <T> List<T>.toImmutable(): List<T> = if (this is ImmutableList<T>) this else ImmutableList(this)
fun <K, V> Map<K, V>.toImmutable(): Map<K, V> = if (this is ImmutableMap<K, V>) this else ImmutableMap(this)
fun <T> Set<T>.toImmutable(): Set<T> = if (this is ImmutableSet<T>) this else ImmutableSet(this)
| apache-2.0 | f521a65532f65ef9cb6ff325b74ff6cd | 32.75 | 108 | 0.709722 | 3.679727 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/ActivityLauncherWrapper.kt | 1 | 1777 | package org.wordpress.android.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import dagger.Reusable
import org.wordpress.android.fluxc.model.PostImmutableModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.posts.RemotePreviewLogicHelper.RemotePreviewType
import javax.inject.Inject
/**
* Injectable wrapper around ActivityLauncher.
*
* ActivityLauncher interface is consisted of static methods, which make the client code difficult to test/mock.
* Main purpose of this wrapper is to make testing easier.
*
*/
@Reusable
class ActivityLauncherWrapper @Inject constructor() {
fun showActionableEmptyView(
context: Context,
actionableState: WPWebViewUsageCategory,
postTitle: String
) = ActivityLauncher.showActionableEmptyView(context, actionableState, postTitle)
fun previewPostOrPageForResult(
activity: Activity,
site: SiteModel,
post: PostImmutableModel,
remotePreviewType: RemotePreviewType
) = ActivityLauncher.previewPostOrPageForResult(activity, site, post, remotePreviewType)
fun openPlayStoreLink(context: Context, packageName: String) {
var intent: Intent? = context.packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("https://play.google.com/store/apps/details?id=$packageName")
flags = Intent.FLAG_ACTIVITY_NEW_TASK
setPackage("com.android.vending")
}
}
context.startActivity(intent)
}
companion object {
const val JETPACK_PACKAGE_NAME = "com.jetpack.android"
}
}
| gpl-2.0 | afadb24c86a69b51f382fdb764ba9280 | 33.843137 | 112 | 0.723129 | 4.603627 | false | false | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/ui/DetailActivity.kt | 1 | 5381 | package io.github.bkmioa.nexusrss.ui
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.Window
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import com.google.android.material.snackbar.Snackbar
import io.github.bkmioa.nexusrss.R
import io.github.bkmioa.nexusrss.Settings
import io.github.bkmioa.nexusrss.base.BaseActivity
import io.github.bkmioa.nexusrss.databinding.ActivityDetailBinding
import io.github.bkmioa.nexusrss.db.DownloadDao
import io.github.bkmioa.nexusrss.download.RemoteDownloader
import io.github.bkmioa.nexusrss.model.DownloadNodeModel
import io.github.bkmioa.nexusrss.model.Item
import kotlinx.android.synthetic.main.activity_detail.*
import org.koin.android.ext.android.inject
class DetailActivity : BaseActivity() {
companion object {
fun createIntent(context: Context, item: Item): Intent {
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra("item", item)
return intent
}
}
lateinit var item: Item
private val downloadDao: DownloadDao by inject()
private var downloadNodes: List<DownloadNodeModel> = emptyList()
private lateinit var binding: ActivityDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(toolBar)
item = intent.getSerializableExtra("item") as Item
supportActionBar?.displayOptions = ActionBar.DISPLAY_HOME_AS_UP or ActionBar.DISPLAY_SHOW_TITLE
supportActionBar?.title = item.subTitle ?: item.title
supportActionBar?.subtitle = if (item.subTitle == null) null else item.title
binding.webView.webViewClient = WebViewClient()
binding.webView.webChromeClient = WebChromeClient()
binding.webView.settings.apply {
javaScriptEnabled = true
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
useWideViewPort = true
loadWithOverviewMode = true
builtInZoomControls = true
displayZoomControls = false
}
item.link?.let {
val additionalHttpHeaders = mapOf("x-requested-with" to "WebView")
binding.webView.loadUrl(it, additionalHttpHeaders)
}
downloadDao.getAllLiveData().observe(this) {
downloadNodes = it
invalidateOptionsMenu()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
if (downloadNodes.isEmpty()) {
menu.add(R.string.remote_download)
.setOnMenuItemClickListener {
goSetting()
true
}
} else {
val subMenu = menu.addSubMenu(R.string.remote_download)
downloadNodes.forEach { node ->
subMenu.add(node.name)
.setOnMenuItemClickListener {
downloadTo(node)
true
}
}
}
menu.add(R.string.copy_link)
.setOnMenuItemClickListener {
copyLink()
true
}
menu.add(R.string.open_link)
.setOnMenuItemClickListener {
openLink()
true
}
return super.onCreateOptionsMenu(menu)
}
private fun openLink() {
val link = item.link
Intent(Intent.ACTION_VIEW, Uri.parse(link))
.run(::startActivity)
}
private fun getTorrentUrl() = item.torrentUrl + "&passkey=" + Settings.PASS_KEY
private fun copyLink() {
if (TextUtils.isEmpty(Settings.PASS_KEY)) {
Snackbar.make(findViewById(Window.ID_ANDROID_CONTENT), R.string.need_pass_key, Snackbar.LENGTH_LONG)
.setAction(R.string.go_download_setting) {
startActivity(Intent(this@DetailActivity, SettingActivity::class.java))
}
.show()
return
}
val torrentUrl = getTorrentUrl()
(getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager)
?.apply {
setPrimaryClip(ClipData.newPlainText(torrentUrl, torrentUrl))
Toast.makeText(application, R.string.copy_done, Toast.LENGTH_SHORT).show()
}
}
private fun downloadTo(node: DownloadNodeModel) {
if (TextUtils.isEmpty(Settings.PASS_KEY)) {
goSetting()
return
}
val torrentUrl = getTorrentUrl() ?: return
RemoteDownloader.download(applicationContext, node.toDownloadNode(), torrentUrl)
}
private fun goSetting() {
Snackbar.make(findViewById(Window.ID_ANDROID_CONTENT), R.string.need_download_setting, Snackbar.LENGTH_LONG)
.setAction(R.string.go_download_setting) {
startActivity(Intent(this@DetailActivity, SettingActivity::class.java))
}
.show()
}
}
| apache-2.0 | 278b7a2e0a2c8599b55ee88412854db6 | 33.273885 | 116 | 0.643932 | 4.830341 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/china/CityUnionTransitData.kt | 1 | 5248 | /*
* NewShenzhenTransitData.kt
*
* Copyright 2018 Google
*
* 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 au.id.micolous.metrodroid.transit.china
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.china.ChinaCard
import au.id.micolous.metrodroid.card.china.ChinaCardTransitFactory
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.ImmutableByteArray
// Reference: https://github.com/sinpolib/nfcard/blob/master/src/com/sinpo/xnfc/nfc/reader/pboc/CityUnion.java
@Parcelize
class CityUnionTransitData (val validityStart: Int?,
val validityEnd: Int?,
override val trips: List<ChinaTrip>?,
val mBalance: Int?,
private val mSerial: Int?,
private val mCity: Int?): TransitData() {
public override val balance: TransitBalance?
get() = if (mBalance != null)
TransitBalanceStored(TransitCurrency.CNY(mBalance),
null,
ChinaTransitData.parseHexDate(validityStart),
ChinaTransitData.parseHexDate(validityEnd))
else
null
override val serialNumber: String
get() = mSerial.toString()
override val cardName: String
get() = nameCity(mCity)
override val info: List<ListItem>?
get() {
if (mCity == null)
return null
val locId = cities[mCity]?.locationId
if (locId != null)
return listOf(ListItem (R.string.city_union_city, locId))
return listOf(ListItem (R.string.city_union_city,
Localizer.localizeString(R.string.unknown_format, mCity.toString(16))))
}
companion object {
private const val SHANGHAI = 0x2000
private val cities = mapOf(
SHANGHAI to CardInfo(
name = R.string.card_name_shanghai,
locationId = R.string.location_shanghai,
imageId = R.drawable.shanghai,
imageAlphaId = R.drawable.iso7810_id1_alpha,
cardType = CardType.ISO7816,
region = TransitRegion.CHINA,
preview = true
)
)
private fun parse (card: ChinaCard): CityUnionTransitData {
val file15 = ChinaTransitData.getFile(card, 0x15)?.binaryData
val (serial, city) = parseSerialAndCity(card)
return CityUnionTransitData(mSerial = serial,
validityStart = file15?.byteArrayToInt(20, 4),
validityEnd = file15?.byteArrayToInt(24, 4),
mCity = city,
mBalance = ChinaTransitData.parseBalance(card),
trips = ChinaTransitData.parseTrips(card) { ChinaTrip(it)} )
}
private val CARD_INFO = CardInfo(
name = R.string.card_name_cityunion,
locationId = R.string.location_china_mainland,
imageId = R.drawable.city_union,
cardType = CardType.ISO7816,
region = TransitRegion.CHINA,
preview = true)
val FACTORY: ChinaCardTransitFactory = object : ChinaCardTransitFactory {
override val appNames: List<ImmutableByteArray>
get() = listOf(ImmutableByteArray.fromHex("A00000000386980701"))
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO) + cities.values
override fun parseTransitIdentity(card: ChinaCard): TransitIdentity {
val (serial, city) = parseSerialAndCity(card)
return TransitIdentity(nameCity(city), serial.toString())
}
override fun parseTransitData(card: ChinaCard) = parse(card)
}
private fun nameCity(city: Int?): String = cities[city]?.name ?: Localizer.localizeString(R.string.card_name_cityunion)
private fun parseSerialAndCity(card: ChinaCard): Pair<Int?, Int?> {
val file15 = ChinaTransitData.getFile(card, 0x15)?.binaryData
val city = file15?.byteArrayToInt(2, 2)
if (city == SHANGHAI)
return Pair(file15.byteArrayToInt(16, 4), city)
return Pair(file15?.byteArrayToIntReversed(16, 4) ?: 0, city)
}
}
}
| gpl-3.0 | 73ec3eb91c41867782be59fe4c03e1a1 | 40.650794 | 127 | 0.613377 | 4.489307 | false | false | false | false |
datarank/tempest | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/model/ModelNode.kt | 1 | 4301 | /*
* The MIT License (MIT)
* Copyright (c) 2018 DataRank, Inc.
*
* 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.simplymeasured.elasticsearch.plugins.tempest.balancer.model
import com.simplymeasured.elasticsearch.plugins.tempest.balancer.IndexSizingGroup
import org.eclipse.collections.api.list.ListIterable
import org.eclipse.collections.api.map.MapIterable
import org.eclipse.collections.impl.utility.LazyIterate
import org.elasticsearch.cluster.routing.RoutingNode
import org.elasticsearch.cluster.routing.ShardRoutingState
import org.elasticsearch.index.shard.ShardId
/**
* Model representation of a Node and its shards
*/
class ModelNode private constructor(
val backingNode: RoutingNode,
val nodeId: String,
val shardManager: NodeShardManager,
val isBlacklisted: Boolean,
val isExpunging: Boolean) {
val shards: ListIterable<ModelShard>
get() { return shardManager.shards }
/**
* Deep Copy Constructor
*/
constructor(other: ModelNode) :
this(other.backingNode,
other.nodeId,
NodeShardManager(other.shardManager),
other.isBlacklisted,
other.isExpunging)
/**
* main constructor used when creating a base model from ES data structures
*/
constructor(routingNode: RoutingNode,
shardSizes: MapIterable<ShardId, IndexSizingGroup.ShardSizeInfo>,
shardScoreGroups: ListIterable<ShardScoreGroup>,
isBlacklisted: Boolean,
isExpunging: Boolean) :
this(backingNode = routingNode,
nodeId = routingNode.nodeId(),
shardManager = NodeShardManager(
shards = routingNode
.copyShards()
.let { LazyIterate.adapt(it) }
.collect { ModelShard(it, shardSizes[it.shardId()], shardScoreGroups.findScoreGroupDescriptionsForShard(it)) }
.toList(),
allocationScale = if (isExpunging) 0.0 else
routingNode
.node()
.attributes.getOrElse("allocation.scale", { "1.0" })
.toDouble(),
shardScoreGroups = shardScoreGroups),
isBlacklisted = isBlacklisted,
isExpunging = isExpunging)
/**
* sum of all shard sizes
*/
fun calculateUsage() : Long = shardManager.totalShardSizes
/**
* Like calculate usage but weighted in terms of the allocation scale used for this node
*/
fun calculateNormalizedNodeUsage() : Double = calculateUsage() / shardManager.allocationScale
/**
* Remove any relocating shards and set initializing shards to be started
*/
fun stabilizeNode() {
shardManager.nonStartedNodes
.select { it.state == ShardRoutingState.RELOCATING }
.forEach { shardManager.removeShard(it) }
shardManager.nonStartedNodes
.select { it.state == ShardRoutingState.INITIALIZING }
.forEach { shardManager.updateState(it, ShardRoutingState.STARTED) }
}
} | mit | 232608397a25a00c1c3a6952f569bc0d | 40.365385 | 139 | 0.653104 | 4.747241 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.