repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/lineWrapping/MultiLineWrapped.kt | 1 | 14757 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr 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.
//
// PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.lineWrapping
import com.planbase.pdf.lm2.attributes.DimAndPageNums
import com.planbase.pdf.lm2.contents.WrappedText
import com.planbase.pdf.lm2.pages.RenderTarget
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import org.organicdesign.indented.IndentedStringable
import org.organicdesign.indented.StringUtils.listToStr
import kotlin.math.nextUp
// TODO: Rename to MultiItemWrappedLine?
/** A mutable data structure to hold a single wrapped line consisting of multiple items. */
class MultiLineWrapped(tempItems: Iterable<LineWrapped>?) : LineWrapped, IndentedStringable {
constructor() : this(null)
var width: Double = 0.0
override var ascent: Double = 0.0
internal var lineHeight: Double = 0.0
internal val items: MutableList<LineWrapped> = mutableListOf()
init {
tempItems?.forEach { append(it) }
}
override val dim: Dim
get() = Dim(width, lineHeight)
override fun items(): List<LineWrapped> = items
private var descentLeading = lineHeight - ascent
fun isEmpty() = items.isEmpty()
fun append(fi: LineWrapped): MultiLineWrapped {
// lineHeight has to be ascent + descentLeading because we align on the baseline
ascent = maxOf(ascent, fi.ascent)
descentLeading = maxOf(descentLeading, fi.dim.height - fi.ascent)
lineHeight = ascent + descentLeading
width += fi.dim.width
items.add(fi)
return this
}
override fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean, justifyWidth: Double): DimAndPageNums {
// println("this=$this")
// println(" MultiLineWrapped.render(${lp.javaClass.simpleName}, $topLeft, reallyRender=$reallyRender, $justifyWidth=justifyWidth)")
// Note that I'm using height.nextUp() so that if there's a rounding error, our whole line gets thrown to
// the next page, not just the line-fragment with the highest ascent.
val adj = lp.pageBreakingTopMargin(topLeft.y - dim.height, dim.height.nextUp(), 0.0)
// println(" adj=$adj")
val y = if (adj == 0.0) {
topLeft.y
} else {
topLeft.y - adj
}
var pageNums: IntRange = DimAndPageNums.INVALID_PAGE_RANGE
var x: Double = topLeft.x
if (reallyRender) {
var tempItems = items
// Text justification calculation 2/2
// Do we need to justify text?
if (justifyWidth > 0.0) {
val contentWidth: Double = dim.width
// Justified text only looks good if the line is long enough.
if (contentWidth > justifyWidth * 0.75) {
val numSpaces: Int = items
.filter { it is WrappedText }
.sumBy { (it as WrappedText).numSpaces }
val wordSpacing = (justifyWidth - contentWidth) / numSpaces
tempItems = items.map {
if (it is WrappedText) {
it.withWordSpacing(wordSpacing)
} else {
it
}
}.toMutableList()
}
}
// Now that we've accounted for anything on the line that could cause a page-break,
// really render each wrapped item in this line
//
// Text rendering calculation spot 2/3
// ascent is the maximum ascent for anything on this line.
// _____
// / | \ \
// | | \ |
// (max) | | | > ascentDiff
// ascent < |_____/ |
// | | \ _ /
// | | \ |_)
// \. .|. . . .\. | \. . . .
// ^item
//
// Subtracting that from the top-y
// yields the baseline, which is what we want to align on.
for (item: LineWrapped in tempItems) {
val ascentDiff = ascent - item.ascent
// println(" item=$item, ascentDiff=$ascentDiff")
val innerUpperLeft = Coord(x, y - ascentDiff)
val dimAndPageNums: DimAndPageNums = item.render(lp, innerUpperLeft, true)
x += item.dim.width
pageNums = dimAndPageNums.maxExtents(pageNums)
}
} else {
pageNums = lp.pageNumFor(y)..lp.pageNumFor(y - dim.height)
x = topLeft.x + dim.width
}
return DimAndPageNums(Dim(x - topLeft.x, (topLeft.y - y) + dim.height), pageNums)
} // end fun render()
override fun indentedStr(indent: Int): String =
"MultiLineWrapped(width=$width, ascent=$ascent, lineHeight=$lineHeight, items=\n" +
"${listToStr(indent + "MultiLineWrapped(".length, items)})"
override fun toString(): String = indentedStr(0)
companion object {
/**
Given a maximum width, turns a list of renderables into a list of fixed-item WrappedMultiLineWrappeds.
This allows each line to contain multiple Renderables. They are baseline-aligned.
If any renderables are not text, their bottom is aligned to the text baseline.
Start a new line.
For each renderable
While renderable is not empty
If our current line is empty
add items.getSomething(blockWidth) to our current line.
Else
If getIfFits(blockWidth - line.widthSoFar)
add it to our current line.
Else
complete our line
Add it to finishedLines
start a new line.
*/
@JvmStatic
fun wrapLines(wrappables: List<LineWrappable>, maxWidth: Double): List<LineWrapped> {
// println("================in wrapLines...")
// println("wrapLines($wrappables, $maxWidth)")
if (maxWidth < 0) {
throw IllegalArgumentException("maxWidth must be >= 0, not $maxWidth")
}
// These are lines consisting of multiple (line-wrapped) items.
val wrappedLines: MutableList<LineWrapped> = mutableListOf()
// This is the current line we're working on.
var wrappedLine = MultiLineWrapped() // Is this right, putting no source here?
// var prevItem:LineWrappable = LineWrappable.ZeroLineWrappable
var unusedWidth = maxWidth
for (item in wrappables) {
// println("Wrappable: $item")
val lineWrapper: LineWrapper = item.lineWrapper()
while (lineWrapper.hasMore()) {
// println(" lineWrapper.hasMore()")
if (wrappedLine.isEmpty()) {
unusedWidth = maxWidth
// println(" wrappedLine.isEmpty()")
val something: ConTerm = lineWrapper.getSomething(maxWidth)
// println("🢂something=$something")
wrappedLine.append(something.item)
unusedWidth -= something.item.dim.width
// println(" unusedWidth1=$unusedWidth")
if (something is Terminal) {
// println("=============== TERMINAL")
// println("something:$something")
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else if ((something is Continuing) &&
(something.hasMore)) {
// println(" Continuing and has more. Adding line so far and starting a new one.")
// If we got as much as we could and there's more left, then it has to go on the next line.
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else if (lineWrapper.hasMore()) {
throw Exception("This shouldn't happen any more. 1")
// println(" LOOKAHEAD??? lineWrapper.hasMore()")
// We have a line of text which is too long and must be broken up. But if it’s too long by less
// than the width of a single space, it truncates the final space from the text fragment, then
// looks again and sees that the next word now fits, so adds it to the same line *without the space*
// which is wrong. To fix this, we check if the lineWrapper already gave us all it has for this
// line and if so, we store it and start the next line.
// addLineCheckBlank(wrappedLine, wrappedLines)
// wrappedLine = MultiLineWrapped()
// // This should never happen any more and should be deleted.
// if ( (something is Continuing) &&
// (something.item is WrappedText) ) {
// unusedWidth -= (something.item as WrappedText).textStyle.spaceWidth
// }
// println(" unusedWidth2=$unusedWidth")
}
} else {
// println(" wrappedLine is not empty")
val ctn: ConTermNone = lineWrapper.getIfFits(unusedWidth) //maxWidth - wrappedLine.width)
// println("🢂ctn=$ctn")
when (ctn) {
is Continuing -> {
// println(" appending result to current wrapped line")
wrappedLine.append(ctn.item)
if (ctn.hasMore) {
// println(" ctn.hasMore but it has to go on the next line.")
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
} else {
// println(" ctn doesn't have more, so something else might fit on this line.")
unusedWidth -= ctn.item.dim.width
}
// println(" unusedWidth3=$unusedWidth")
if (unusedWidth <= 0) {
throw Exception("This shouldn't happen any more. 2")
// addLineCheckBlank(wrappedLine, wrappedLines)
// wrappedLine = MultiLineWrapped()
// unusedWidth = maxWidth
}
}
is Terminal -> {
// println("=============== TERMINAL 222222222")
// println("ctn:$ctn")
wrappedLine.append(ctn.item)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
}
None -> {
// println("=============== NONE 222222222")
// MultiLineWrappeds.add(wrappedLine)
addLineCheckBlank(wrappedLine, wrappedLines)
wrappedLine = MultiLineWrapped()
unusedWidth = maxWidth
}
}
}
} // end while lineWrapper.hasMore()
} // end for item in wrappables
// println("Line before last item: $wrappedLine")
// Don't forget to add last item.
addLineCheckBlank(wrappedLine, wrappedLines)
return wrappedLines.toList()
}
private fun addLineCheckBlank(currLine: MultiLineWrapped,
wrappedLines: MutableList<LineWrapped>) {
// If this item is a blank line, take the height from the previous item (if there is one).
if (currLine.isEmpty() && wrappedLines.isNotEmpty()) {
val lastRealItem: LineWrapped = wrappedLines.last().items().last()
// println("================================ adding a spacer ===========================")
wrappedLines.add(BlankLineWrapped(Dim(0.0, lastRealItem.dim.height), lastRealItem.ascent))
} else if (currLine.items.size == 1) {
// Don't add a MultilineWrapped if we can just add a single wrapped thing.
// Trim space from final item on completed line.
val lastItem = currLine.items[0]
wrappedLines.add(when (lastItem) {
is WrappedText -> lastItem.withoutTrailingSpace()
else -> lastItem
})
} else {
// Add multiple items.
if (currLine.items.size > 1) {
// Trim space from final item on completed line.
val lastIdx = currLine.items.lastIndex
val lastItem = currLine.items[lastIdx]
if (lastItem is WrappedText) {
currLine.items.removeAt(lastIdx)
currLine.items.add(lastItem.withoutTrailingSpace())
}
}
wrappedLines.add(currLine)
}
}
}
} | agpl-3.0 | 7dedaa54a91524cb1b8f13c89b8df137 | 47.679868 | 140 | 0.522883 | 5.367176 | false | false | false | false |
paplorinc/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/FeatureUsageDataTest.kt | 2 | 12916 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.util.Version
import org.junit.Assert
import org.junit.Test
class FeatureUsageDataTest {
@Test
fun `test empty data`() {
val build = FeatureUsageData().build()
Assert.assertTrue(build.isEmpty())
}
@Test
fun `test put string data`() {
val build = FeatureUsageData().addData("key", "my-value").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "my-value")
}
@Test
fun `test put int data`() {
val build = FeatureUsageData().addData("key", 99).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == 99)
}
@Test
fun `test put long data`() {
val value: Long = 99
val build = FeatureUsageData().addData("key", value).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == 99L)
}
@Test
fun `test put boolean data`() {
val build = FeatureUsageData().addData("key", true).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == true)
}
@Test
fun `test put os data`() {
val build = FeatureUsageData().addOS().build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("os"))
}
@Test
fun `test put add null place`() {
val build = FeatureUsageData().addPlace(null).build()
Assert.assertTrue(build.isEmpty())
}
@Test
fun `test put add empty place`() {
val build = FeatureUsageData().addPlace("").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.UNKNOWN)
}
@Test
fun `test put add common place`() {
val build = FeatureUsageData().addPlace("TestTreeViewToolbar").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == "TestTreeViewToolbar")
}
@Test
fun `test put add common popup place`() {
val build = FeatureUsageData().addPlace("FavoritesPopup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == "FavoritesPopup")
}
@Test
fun `test put add custom popup place`() {
val build = FeatureUsageData().addPlace("popup@my-custom-popup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.POPUP)
}
@Test
fun `test put add custom place`() {
val build = FeatureUsageData().addPlace("my-custom-popup").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("place"))
Assert.assertTrue(build["place"] == ActionPlaces.UNKNOWN)
}
@Test
fun `test put null obj version`() {
val build = FeatureUsageData().addVersion(null).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test put null version`() {
val build = FeatureUsageData().addVersionByString(null).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown")
}
@Test
fun `test put obj version`() {
val build = FeatureUsageData().addVersion(Version(3, 5, 0)).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "3.5")
}
@Test
fun `test put version`() {
val build = FeatureUsageData().addVersionByString("5.11.0").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "5.11")
}
@Test
fun `test put obj version with bugfix`() {
val build = FeatureUsageData().addVersion(Version(3, 5, 9)).build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "3.5")
}
@Test
fun `test put version with bugfix`() {
val build = FeatureUsageData().addVersionByString("5.11.98").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "5.11")
}
@Test
fun `test put invalid version`() {
val build = FeatureUsageData().addVersionByString("2018-11").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "2018.0")
}
@Test
fun `test put empty version`() {
val build = FeatureUsageData().addVersionByString("").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test put version with snapshot`() {
val build = FeatureUsageData().addVersionByString("1.4-SNAPSHOT").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "1.4")
}
@Test
fun `test put version with suffix`() {
val build = FeatureUsageData().addVersionByString("2.5.0.BUILD-2017091412345").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "2.5")
}
@Test
fun `test put version with letters`() {
val build = FeatureUsageData().addVersionByString("abcd").build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build.containsKey("version"))
Assert.assertTrue(build["version"] == "unknown.format")
}
@Test
fun `test copy empty data`() {
val data = FeatureUsageData()
val data2 = data.copy()
Assert.assertTrue(data.build().isEmpty())
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test copy single element data`() {
val data = FeatureUsageData().addData("new-key", "new-value")
val data2 = data.copy()
Assert.assertTrue(data.build().size == 1)
Assert.assertTrue(data.build()["new-key"] == "new-value")
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test copy multi elements data`() {
val data = FeatureUsageData().addData("new-key", "new-value").addData("second", "test")
val data2 = data.copy()
Assert.assertTrue(data.build().size == 2)
Assert.assertTrue(data.build()["new-key"] == "new-value")
Assert.assertTrue(data.build()["second"] == "test")
Assert.assertEquals(data, data2)
Assert.assertEquals(data.build(), data2.build())
}
@Test
fun `test merge empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData()
data.merge(data2, "pr")
Assert.assertTrue(data.build().isEmpty())
}
@Test
fun `test merge empty with not empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData().addData("key", "value")
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "value")
}
@Test
fun `test merge empty with default not empty data`() {
val data = FeatureUsageData()
val data2 = FeatureUsageData().addData("data_1", "value")
data.merge(data2, "pr_")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["pr_data_1"] == "value")
}
@Test
fun `test merge not empty with empty data`() {
val data = FeatureUsageData().addData("key", "value")
val data2 = FeatureUsageData()
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["key"] == "value")
}
@Test
fun `test merge not empty default with empty data`() {
val data = FeatureUsageData().addData("data_2", "value")
val data2 = FeatureUsageData()
data.merge(data2, "pr")
val build = data.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["data_2"] == "value")
}
@Test
fun `test merge not empty data`() {
val data = FeatureUsageData().addData("first", "value-1")
val data2 = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
data.merge(data2, "pr")
Assert.assertTrue(data.build().size == 3)
Assert.assertTrue(data.build()["first"] == "value-1")
Assert.assertTrue(data.build()["second"] == "value-2")
Assert.assertTrue(data.build()["prdata_99"] == "default-value")
}
@Test
fun `test merge null group with null event data`() {
val merged = FUStateUsagesLogger.mergeWithEventData(null, null, 1)
Assert.assertNull(merged)
}
@Test
fun `test merge null group with null event data with not default value`() {
val merged = FUStateUsagesLogger.mergeWithEventData(null, null, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge group with null event data`() {
val group = FeatureUsageData().addData("first", "value-1")
val merged = FUStateUsagesLogger.mergeWithEventData(group, null, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["first"] == "value-1")
}
@Test
fun `test merge group with null event data with not default value`() {
val group = FeatureUsageData().addData("first", "value-1")
val merged = FUStateUsagesLogger.mergeWithEventData(group, null, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge null group with event data`() {
val event = FeatureUsageData().addData("first", 99)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["first"] == 99)
}
@Test
fun `test merge null group with default named event data`() {
val event = FeatureUsageData().addData("data_5", 99)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 1)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 1)
Assert.assertTrue(build["event_data_5"] == 99)
}
@Test
fun `test merge null group with event data with not default value`() {
val event = FeatureUsageData().addData("first", true)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["first"] == true)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge null group with default named event data with not default value`() {
val event = FeatureUsageData().addData("data_9", true)
val merged = FUStateUsagesLogger.mergeWithEventData(null, event, 10)
Assert.assertNotNull(merged)
val build = merged!!.build()
Assert.assertTrue(build.size == 2)
Assert.assertTrue(build["event_data_9"] == true)
Assert.assertTrue(build["value"] == 10)
}
@Test
fun `test merge group with event data`() {
val group = FeatureUsageData().addData("first", "value-1")
val event = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
val merged = FUStateUsagesLogger.mergeWithEventData(group, event, 1)
val build = merged!!.build()
Assert.assertTrue(build.size == 3)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["second"] == "value-2")
Assert.assertTrue(build["event_data_99"] == "default-value")
}
@Test
fun `test merge group with event data with not default value`() {
val group = FeatureUsageData().addData("first", "value-1")
val event = FeatureUsageData().addData("second", "value-2").addData("data_99", "default-value")
val merged = FUStateUsagesLogger.mergeWithEventData(group, event, 10)
val build = merged!!.build()
Assert.assertTrue(build.size == 4)
Assert.assertTrue(build["first"] == "value-1")
Assert.assertTrue(build["second"] == "value-2")
Assert.assertTrue(build["event_data_99"] == "default-value")
Assert.assertTrue(build["value"] == 10)
}
} | apache-2.0 | c22679f0e69d719604a00a1bedefce7a | 31.701266 | 140 | 0.668473 | 3.94141 | false | true | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/completion/OffsetsInFile.kt | 6 | 3239 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.ChangedPsiRangeUtil
import com.intellij.psi.impl.source.tree.FileElement
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.text.BlockSupport
/**
* @author peter
*/
class OffsetsInFile(val file: PsiFile, val offsets: OffsetMap) {
constructor(file: PsiFile) : this(file, OffsetMap(file.viewProvider.document!!))
fun toTopLevelFile(): OffsetsInFile {
val manager = InjectedLanguageManager.getInstance(file.project)
val hostFile = manager.getTopLevelFile(file)
if (hostFile == file) return this
return OffsetsInFile(hostFile, offsets.mapOffsets(hostFile.viewProvider.document!!) { manager.injectedToHost(file, it) })
}
fun toInjectedIfAny(offset: Int): OffsetsInFile {
val injected = InjectedLanguageUtil.findInjectedPsiNoCommit(file, offset) ?: return this
val documentWindow = InjectedLanguageUtil.getDocumentWindow(injected)!!
return OffsetsInFile(injected, offsets.mapOffsets(documentWindow) { documentWindow.hostToInjected(it) })
}
fun copyWithReplacement(startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
return replaceInCopy(file.copy() as PsiFile, startOffset, endOffset, replacement)
}
fun replaceInCopy(fileCopy: PsiFile, startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
val tempDocument = DocumentImpl(offsets.document.immutableCharSequence, true)
val tempMap = offsets.copyOffsets(tempDocument)
tempDocument.replaceString(startOffset, endOffset, replacement)
reparseFile(fileCopy, tempDocument.immutableCharSequence)
val copyOffsets = tempMap.copyOffsets(fileCopy.viewProvider.document!!)
return OffsetsInFile(fileCopy, copyOffsets)
}
private fun reparseFile(file: PsiFile, newText: CharSequence) {
val node = file.node as? FileElement ?: throw IllegalStateException("${file.javaClass} ${file.fileType}")
val range = ChangedPsiRangeUtil.getChangedPsiRange(file, node, newText) ?: return
val indicator = ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()
val log = BlockSupport.getInstance(file.project).reparseRange(file, node, range, newText, indicator, file.viewProvider.contents)
ProgressManager.getInstance().executeNonCancelableSection { log.doActualPsiChange(file) }
}
}
| apache-2.0 | dc4a0bf8c90d805a3bf26a8bd8a672f7 | 44.619718 | 132 | 0.780797 | 4.53007 | false | false | false | false |
google/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/InitialTypeProvider.kt | 6 | 1974 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.psi.dataFlow.types
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.psi.PsiType
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ResolvedVariableDescriptor
import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic
internal class InitialTypeProvider(private val start: GrControlFlowOwner, private val reverseMapping : Array<VariableDescriptor>) {
private val TYPE_INFERENCE_FAILED = Any()
private val cache: MutableMap<Int, Any> = mutableMapOf()
fun initialType(descriptorId: Int): PsiType? {
if (!cache.containsKey(descriptorId)) {
try {
if (isCompileStatic(start)) return null
if (descriptorId >= reverseMapping.size) {
thisLogger().error("Unrecognized variable at index $descriptorId", IllegalStateException(),
Attachment("block.text", start.text),
Attachment("block.flow", start.controlFlow.contentDeepToString()),
Attachment("block.vars", reverseMapping.contentToString()))
} else {
val field = reverseMapping[descriptorId].castSafelyTo<ResolvedVariableDescriptor>()?.variable?.castSafelyTo<GrField>() ?: return null
val fieldType = field.typeGroovy
if (fieldType != null) {
cache[descriptorId] = fieldType
}
}
} finally {
cache.putIfAbsent(descriptorId, TYPE_INFERENCE_FAILED)
}
}
return cache[descriptorId]?.castSafelyTo<PsiType>()
}
}
| apache-2.0 | cf89c555c1f0503649a9c6ba7d08303b | 47.146341 | 143 | 0.715299 | 4.745192 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoChildForParentWithPidEntityImpl.kt | 1 | 9538 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OoChildForParentWithPidEntityImpl(val dataSource: OoChildForParentWithPidEntityData) : OoChildForParentWithPidEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java,
OoChildForParentWithPidEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val childProperty: String
get() = dataSource.childProperty
override val parentEntity: OoParentWithPidEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: OoChildForParentWithPidEntityData?) : ModifiableWorkspaceEntityBase<OoChildForParentWithPidEntity>(), OoChildForParentWithPidEntity.Builder {
constructor() : this(OoChildForParentWithPidEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OoChildForParentWithPidEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isChildPropertyInitialized()) {
error("Field OoChildForParentWithPidEntity#childProperty should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field OoChildForParentWithPidEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field OoChildForParentWithPidEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as OoChildForParentWithPidEntity
this.entitySource = dataSource.entitySource
this.childProperty = dataSource.childProperty
if (parents != null) {
this.parentEntity = parents.filterIsInstance<OoParentWithPidEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var childProperty: String
get() = getEntityData().childProperty
set(value) {
checkModificationAllowed()
getEntityData().childProperty = value
changedProperty.add("childProperty")
}
override var parentEntity: OoParentWithPidEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): OoChildForParentWithPidEntityData = result ?: super.getEntityData() as OoChildForParentWithPidEntityData
override fun getEntityClass(): Class<OoChildForParentWithPidEntity> = OoChildForParentWithPidEntity::class.java
}
}
class OoChildForParentWithPidEntityData : WorkspaceEntityData<OoChildForParentWithPidEntity>() {
lateinit var childProperty: String
fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoChildForParentWithPidEntity> {
val modifiable = OoChildForParentWithPidEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OoChildForParentWithPidEntity {
return getCached(snapshot) {
val entity = OoChildForParentWithPidEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OoChildForParentWithPidEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return OoChildForParentWithPidEntity(childProperty, entitySource) {
this.parentEntity = parents.filterIsInstance<OoParentWithPidEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(OoParentWithPidEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildForParentWithPidEntityData
if (this.entitySource != other.entitySource) return false
if (this.childProperty != other.childProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as OoChildForParentWithPidEntityData
if (this.childProperty != other.childProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | b46216fa62d20742402ba1d9a8913d12 | 37.152 | 169 | 0.710526 | 5.833639 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/network/result/ResultDelegate.kt | 2 | 1152 | package quickbeer.android.network.result
import quickbeer.android.network.CallDelegate
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
class ResultDelegate<T>(proxy: Call<T>) : CallDelegate<T, ApiResult<T>>(proxy) {
override fun delegatedEnqueue(callback: Callback<ApiResult<T>>) = proxy.enqueue(
object : Callback<T> {
@Suppress("MagicNumber")
override fun onResponse(call: Call<T>, response: Response<T>) {
val result = when (val code = response.code()) {
in 200 until 300 -> ApiResult.Success(response.body())
else -> ApiResult.HttpError(code, HttpException(response))
}
callback.onResponse(this@ResultDelegate, Response.success(result))
}
override fun onFailure(call: Call<T>, error: Throwable) {
val result = ApiResult.mapError<T>(error)
callback.onResponse(this@ResultDelegate, Response.success(result))
}
}
)
override fun delegatedClone() = ResultDelegate(proxy.clone())
}
| gpl-3.0 | cb8d49c382f99b149c95078123b9e16b | 35 | 84 | 0.635417 | 4.589641 | false | false | false | false |
google/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/MavenizedStructureWizardStep.kt | 6 | 14416 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.wizard
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.installNameGenerators
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.externalSystem.util.ui.DataView
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory.createSingleLocalFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.properties.transform
import com.intellij.openapi.observable.properties.map
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.getCanonicalPath
import com.intellij.openapi.ui.getPresentablePath
import com.intellij.openapi.util.io.FileUtil.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.SortedComboBoxModel
import com.intellij.ui.layout.*
import java.io.File
import java.nio.file.InvalidPathException
import java.nio.file.Paths
import java.util.Comparator.comparing
import java.util.function.Function
import javax.swing.JList
import javax.swing.JTextField
import javax.swing.ListCellRenderer
abstract class MavenizedStructureWizardStep<Data : Any>(val context: WizardContext) : ModuleWizardStep() {
abstract fun createView(data: Data): DataView<Data>
abstract fun findAllParents(): List<Data>
private val propertyGraph = PropertyGraph()
private val entityNameProperty = propertyGraph.graphProperty(::suggestName)
private val locationProperty = propertyGraph.graphProperty { suggestLocationByName() }
private val parentProperty = propertyGraph.graphProperty(::suggestParentByLocation)
private val groupIdProperty = propertyGraph.graphProperty(::suggestGroupIdByParent)
private val artifactIdProperty = propertyGraph.graphProperty(::suggestArtifactIdByName)
private val versionProperty = propertyGraph.graphProperty(::suggestVersionByParent)
var entityName by entityNameProperty.map { it.trim() }
var location by locationProperty
var parent by parentProperty
var groupId by groupIdProperty.map { it.trim() }
var artifactId by artifactIdProperty.map { it.trim() }
var version by versionProperty.map { it.trim() }
val parents by lazy { parentsData.map(::createView) }
val parentsData by lazy { findAllParents() }
var parentData: Data?
get() = DataView.getData(parent)
set(value) {
parent = if (value == null) EMPTY_VIEW else createView(value)
}
init {
entityNameProperty.dependsOn(locationProperty, ::suggestNameByLocation)
entityNameProperty.dependsOn(artifactIdProperty, ::suggestNameByArtifactId)
parentProperty.dependsOn(locationProperty, ::suggestParentByLocation)
locationProperty.dependsOn(parentProperty) { suggestLocationByParentAndName() }
locationProperty.dependsOn(entityNameProperty) { suggestLocationByParentAndName() }
groupIdProperty.dependsOn(parentProperty, ::suggestGroupIdByParent)
artifactIdProperty.dependsOn(entityNameProperty, ::suggestArtifactIdByName)
versionProperty.dependsOn(parentProperty, ::suggestVersionByParent)
}
private val contentPanel by lazy {
panel {
if (!context.isCreatingNewProject) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.parent.label")) {
val presentationName = Function<DataView<Data>, String> { it.presentationName }
val parentComboBoxModel = SortedComboBoxModel(comparing(presentationName, String.CASE_INSENSITIVE_ORDER))
parentComboBoxModel.add(EMPTY_VIEW)
parentComboBoxModel.addAll(parents)
comboBox(parentComboBoxModel, parentProperty, renderer = getParentRenderer())
}
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.label")) {
textField(entityNameProperty)
.withValidationOnApply { validateName() }
.withValidationOnInput { validateName() }
.constraints(pushX)
.focused()
installNameGenerators(getBuilderId(), entityNameProperty)
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.label")) {
val fileChooserDescriptor = createSingleLocalFileDescriptor().withFileFilter { it.isDirectory }
val fileChosen = { file: VirtualFile -> getPresentablePath(file.path) }
val title = IdeBundle.message("title.select.project.file.directory", context.presentationName)
val property = locationProperty.transform(::getPresentablePath, ::getCanonicalPath)
textFieldWithBrowseButton(property, title, context.project, fileChooserDescriptor, fileChosen)
.withValidationOnApply { validateLocation() }
.withValidationOnInput { validateLocation() }
}
hideableRow(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.coordinates.title")) {
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.label")) {
textField(groupIdProperty)
.withValidationOnApply { validateGroupId() }
.withValidationOnInput { validateGroupId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.help"))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.label")) {
textField(artifactIdProperty)
.withValidationOnApply { validateArtifactId() }
.withValidationOnInput { validateArtifactId() }
.comment(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.help", context.presentationName))
}
row(ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.label")) {
textField(versionProperty)
.withValidationOnApply { validateVersion() }
.withValidationOnInput { validateVersion() }
}
}
}.apply {
registerValidators(context.disposable)
}
}
protected open fun getBuilderId(): String? = null
override fun getPreferredFocusedComponent() = contentPanel.preferredFocusedComponent
override fun getComponent() = contentPanel
override fun updateStep() = (preferredFocusedComponent as JTextField).selectAll()
private fun getParentRenderer(): ListCellRenderer<DataView<Data>?> {
return object : SimpleListCellRenderer<DataView<Data>?>() {
override fun customize(list: JList<out DataView<Data>?>,
value: DataView<Data>?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
val view = value ?: EMPTY_VIEW
text = view.presentationName
icon = DataView.getIcon(view)
}
}
}
protected open fun suggestName(): String {
val projectFileDirectory = File(context.projectFileDirectory)
val moduleNames = findAllModules().map { it.name }.toSet()
return createSequentFileName(projectFileDirectory, "untitled", "") {
!it.exists() && it.name !in moduleNames
}
}
protected fun findAllModules(): List<Module> {
val project = context.project ?: return emptyList()
val moduleManager = ModuleManager.getInstance(project)
return moduleManager.modules.toList()
}
protected open fun suggestNameByLocation(): String {
return File(location).name
}
protected open fun suggestNameByArtifactId(): String {
return artifactId
}
protected open fun suggestLocationByParentAndName(): String {
if (!parent.isPresent) return suggestLocationByName()
return join(parent.location, entityName)
}
protected open fun suggestLocationByName(): String {
return join(context.projectFileDirectory, entityName)
}
protected open fun suggestParentByLocation(): DataView<Data> {
val location = location
return parents.find { isAncestor(it.location, location, true) } ?: EMPTY_VIEW
}
protected open fun suggestGroupIdByParent(): String {
return parent.groupId
}
protected open fun suggestArtifactIdByName(): String {
return entityName
}
protected open fun suggestVersionByParent(): String {
return parent.version
}
override fun validate(): Boolean {
return contentPanel.validateCallbacks
.asSequence()
.mapNotNull { it() }
.all { it.okEnabled }
}
protected open fun ValidationInfoBuilder.validateGroupId() = superValidateGroupId()
protected fun ValidationInfoBuilder.superValidateGroupId(): ValidationInfo? {
if (groupId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.group.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateArtifactId() = superValidateArtifactId()
protected fun ValidationInfoBuilder.superValidateArtifactId(): ValidationInfo? {
if (artifactId.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.artifact.id.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateVersion() = superValidateVersion()
protected fun ValidationInfoBuilder.superValidateVersion(): ValidationInfo? {
if (version.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.version.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateName() = superValidateName()
protected fun ValidationInfoBuilder.superValidateName(): ValidationInfo? {
if (entityName.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.name.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val moduleNames = findAllModules().map { it.name }.toSet()
if (entityName in moduleNames) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.entity.name.exists.error",
context.presentationName.capitalize(), entityName)
return error(message)
}
return null
}
protected open fun ValidationInfoBuilder.validateLocation() = superValidateLocation()
protected fun ValidationInfoBuilder.superValidateLocation(): ValidationInfo? {
val location = location
if (location.isEmpty()) {
val propertyPresentation = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.location.presentation")
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.missing.error",
context.presentationName, propertyPresentation)
return error(message)
}
val locationPath = try {
Paths.get(location)
}
catch (ex: InvalidPathException) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.invalid", ex.reason)
return error(message)
}
for (project in ProjectManager.getInstance().openProjects) {
if (ProjectUtil.isSameProject(locationPath, project)) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.already.taken.error", project.name)
return error(message)
}
}
val file = locationPath.toFile()
if (file.exists()) {
if (!file.canWrite()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.writable.error")
return error(message)
}
val children = file.list()
if (children == null) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.file.not.directory.error")
return error(message)
}
if (!ApplicationManager.getApplication().isUnitTestMode) {
if (children.isNotEmpty()) {
val message = ExternalSystemBundle.message("external.system.mavenized.structure.wizard.directory.not.empty.warning")
return warning(message)
}
}
}
return null
}
override fun updateDataModel() {
val location = location
context.projectName = entityName
context.setProjectFileDirectory(location)
createDirectory(File(location))
updateProjectData()
}
abstract fun updateProjectData()
companion object {
private val EMPTY_VIEW = object : DataView<Nothing>() {
override val data: Nothing get() = throw UnsupportedOperationException()
override val location: String = ""
override val icon: Nothing get() = throw UnsupportedOperationException()
override val presentationName: String = "<None>"
override val groupId: String = "org.example"
override val version: String = "1.0-SNAPSHOT"
override val isPresent: Boolean = false
}
}
}
| apache-2.0 | 2eea8340f39124f56dcaa0052b74c311 | 43.770186 | 140 | 0.72912 | 5.317595 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/AfterConversionPass.kt | 1 | 1281 | // 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.j2k
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.psi.KtFile
class AfterConversionPass(val project: Project, private val postProcessor: PostProcessor) {
@JvmOverloads
fun run(
kotlinFile: KtFile,
converterContext: ConverterContext?,
range: TextRange?,
onPhaseChanged: ((Int, String) -> Unit)? = null
) {
postProcessor.doAdditionalProcessing(
when {
range != null -> JKPieceOfCodePostProcessingTarget(kotlinFile, range.toRangeMarker(kotlinFile))
else -> JKMultipleFilesPostProcessingTarget(listOf(kotlinFile))
},
converterContext,
onPhaseChanged
)
}
}
fun TextRange.toRangeMarker(file: KtFile): RangeMarker =
runReadAction { file.viewProvider.document!!.createRangeMarker(startOffset, endOffset) }.apply {
isGreedyToLeft = true
isGreedyToRight = true
} | apache-2.0 | 13b5cae642ad4590e640f8d3fa6dab10 | 36.705882 | 158 | 0.704137 | 4.852273 | false | false | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/gui/base/Root.kt | 1 | 1131 | package de.theunknownxy.mcdocs.gui.base
import de.theunknownxy.mcdocs.gui.container.SingleContainer
import de.theunknownxy.mcdocs.gui.event.MouseButton
import net.minecraft.client.gui.GuiScreen
import java.util.HashMap
public class Root(public val gui: GuiScreen) : SingleContainer(null) {
public var mouse_pos: Point = Point(0f, 0f)
public var named_widgets: HashMap<String, Widget> = HashMap()
public var selected_widget: Widget? = null
override fun onMouseClick(pos: Point, button: MouseButton): Widget? {
val new_selected = super.onMouseClick(pos, button)
if (new_selected != selected_widget) {
// Unfocus old one
selected_widget?.onUnfocus()
selected_widget = new_selected
}
return selected_widget
}
override fun onMouseClickMove(pos: Point) {
// Send the move events to the last clicked widget
selected_widget?.onMouseClickMove(pos)
}
override fun onKeyTyped(ch: Char, t: Int) {
selected_widget?.onKeyTyped(ch, t)
}
override fun recalculateChildren() {
child?.rect = rect
}
} | mit | 514adff84dcae77b5b33adfd46af3d88 | 31.342857 | 73 | 0.676393 | 4.127737 | false | false | false | false |
allotria/intellij-community | build/launch/src/com/intellij/tools/launch/PathsProvider.kt | 3 | 1233 | package com.intellij.tools.launch
import java.io.File
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
interface PathsProvider {
val productId: String
val ultimateRootFolder: File
val communityRootFolder: File
val outputRootFolder: File
val tempFolder: File
get() = TeamCityHelper.tempDirectory ?: ultimateRootFolder.resolve("out").resolve("tmp")
val launcherFolder: File
get() = tempFolder.resolve("launcher").resolve(productId)
val logFolder: File
get() = launcherFolder.resolve("log")
val configFolder: File
get() = launcherFolder.resolve("config")
val systemFolder: File
get() = launcherFolder.resolve("system")
val javaHomeFolder: File
get() = File(SystemProperties.getJavaHome())
val mavenRepositoryFolder: File
get() = File(System.getProperty("user.home")).resolve(".m2/repository")
val communityBinFolder: File
get() = communityRootFolder.resolve("bin")
val javaExecutable: File
get() = when {
SystemInfo.isWindows -> javaHomeFolder.resolve("bin").resolve("java.exe")
else -> javaHomeFolder.resolve("bin").resolve("java")
}
val dockerVolumesToWritable: Map<File, Boolean>
get() = emptyMap()
} | apache-2.0 | 3e368e3f1b5918d0d9ebf9a33cf68f0f | 26.422222 | 92 | 0.722628 | 4.326316 | false | false | false | false |
allotria/intellij-community | platform/statistics/src/com/intellij/internal/statistic/utils/StatisticsUtil.kt | 2 | 3387 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.utils
import com.intellij.internal.statistic.eventLog.EventLogConfiguration
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.getProjectCacheFileName
import java.text.SimpleDateFormat
import java.time.ZoneOffset
import java.util.*
fun addPluginInfoTo(info: PluginInfo, data: MutableMap<String, Any>) {
data["plugin_type"] = info.type.name
if (!info.type.isSafeToReport()) return
val id = info.id
if (!id.isNullOrEmpty()) {
data["plugin"] = id
}
val version = info.version
if (!version.isNullOrEmpty()) {
data["plugin_version"] = version
}
}
object StatisticsUtil {
private const val kilo = 1000
private const val mega = kilo * kilo
@JvmStatic
fun getProjectId(project: Project, recorderId: String): String {
return EventLogConfiguration.getOrCreate(recorderId).anonymize(project.getProjectCacheFileName())
}
/**
* Anonymizes sensitive project properties by rounding it to the next power of two
* See `com.intellij.internal.statistic.collectors.fus.fileTypes.FileTypeUsagesCollector`
*/
@JvmStatic
fun getNextPowerOfTwo(value: Int): Int = if (value <= 1) 1 else Integer.highestOneBit(value - 1) shl 1
/**
* Anonymizes value by finding upper bound in provided bounds.
* Allows more fine tuning then `com.intellij.internal.statistic.utils.StatisticsUtil#getNextPowerOfTwo`
* but requires manual maintaining.
*
* @param bounds is an integer array sorted in ascending order (required, but not checked)
* @return value upper bound or next power of two if no bounds were provided (as fallback)
* */
@JvmStatic
fun getUpperBound(value: Int, bounds: IntArray): Int {
if (bounds.isEmpty()) return getNextPowerOfTwo(value)
for (bound in bounds)
if (value <= bound) return bound
return bounds.last()
}
/**
* Anonymizes sensitive project properties by rounding it to the next value in steps list.
* See `com.intellij.internal.statistic.collectors.fus.fileTypes.FileTypeUsagesCollector`
*/
fun getCountingStepName(value: Int, steps: List<Int>): String {
if (steps.isEmpty()) return value.toString()
if (value < steps[0]) return "<" + steps[0]
var stepIndex = 0
while (stepIndex < steps.size - 1) {
if (value < steps[stepIndex + 1]) break
stepIndex++
}
val step = steps[stepIndex]
val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1
return humanize(step) + if (addPlus) "+" else ""
}
/**
* Returns current hour in UTC as "yyMMddHH"
*/
fun getCurrentHourInUTC(calendar: Calendar = Calendar.getInstance(Locale.ENGLISH)): String {
calendar[Calendar.YEAR] = calendar[Calendar.YEAR].coerceIn(2000, 2099)
val format = SimpleDateFormat("yyMMddHH", Locale.ENGLISH)
format.timeZone = TimeZone.getTimeZone(ZoneOffset.UTC)
return format.format(calendar.time)
}
private fun humanize(number: Int): String {
if (number == 0) return "0"
val m = number / mega
val k = (number % mega) / kilo
val r = (number % kilo)
val ms = if (m > 0) "${m}M" else ""
val ks = if (k > 0) "${k}K" else ""
val rs = if (r > 0) "${r}" else ""
return ms + ks + rs
}
} | apache-2.0 | 52d369d96df4a91e8e75aa447eb67ddd | 33.927835 | 140 | 0.69442 | 3.938372 | false | false | false | false |
himaaaatti/spigot-plugins | auto_craft/auto_craft.kt | 1 | 9560 | package com.github.himaaaatti.spigot.plugin.auto_craft
import org.bukkit.material.Sign
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.block.BlockFace
import org.bukkit.material.Attachable
import org.bukkit.inventory.ShapedRecipe
import org.bukkit.inventory.Recipe
import org.bukkit.inventory.ItemStack
import org.bukkit.event.block.SignChangeEvent
import org.bukkit.event.block.BlockRedstoneEvent
import org.bukkit.inventory.InventoryHolder
import org.bukkit.Bukkit
import org.bukkit.block.Chest
class AutoCraft: JavaPlugin() {
val AUTO_CRAFT_TEXT = "auto craft"
override fun onEnable() {
getServer().getPluginManager().registerEvents(
object : Listener {
@EventHandler
fun onChange(e: SignChangeEvent)
{
val sign = e.getBlock().getState().getData() as Sign
val holder = e.getBlock().getRelative(sign.getAttachedFace())
if(holder.getType() != Material.WORKBENCH)
{
return
}
if(e.getLine(0) != AUTO_CRAFT_TEXT)
{
return
}
e.setLine(1,"↑ Recipe")
e.setLine(2, "<-Input|Output->");
e.setLine(3, "[ok]");
}
@EventHandler
fun onRedStone(e: BlockRedstoneEvent)
{
if(!(e.getOldCurrent() == 0 && e.getNewCurrent() != 0))
{
return
}
val pumpkin = e.block.getRelative(0, -1, 0)
if(pumpkin.getType() != Material.PUMPKIN)
{
return
}
val w_face = when
{
pumpkin.getRelative(BlockFace.EAST).getType() == Material.WORKBENCH
-> BlockFace.EAST
pumpkin.getRelative(BlockFace.WEST).getType() == Material.WORKBENCH
-> BlockFace.WEST
pumpkin.getRelative(BlockFace.SOUTH).getType() == Material.WORKBENCH
-> BlockFace.SOUTH
pumpkin.getRelative(BlockFace.NORTH).getType() == Material.WORKBENCH
-> BlockFace.NORTH
else -> return@onRedStone
}
val work_bench = pumpkin.getRelative(w_face)
val face: BlockFace? = getSignAttachedFace(work_bench)
if(face == null)
{
getLogger().info("getSignAttachedFace")
return
}
val recipe_block = work_bench.getRelative(0, 1, 0)
if(recipe_block.getType() != Material.CHEST)
{
getLogger().info("above block is not CHEST")
return
}
val chest_faces = when(face) {
BlockFace.NORTH -> Pair(BlockFace.EAST, BlockFace.WEST)
BlockFace.EAST -> Pair(BlockFace.SOUTH, BlockFace.NORTH)
BlockFace.SOUTH -> Pair(BlockFace.WEST, BlockFace.EAST)
BlockFace.WEST -> Pair(BlockFace.NORTH, BlockFace.SOUTH)
else -> return@onRedStone
}
val source_chest = work_bench.getRelative(chest_faces.first)
if(source_chest.getType() != Material.CHEST)
{
getLogger().info("left block is not CHEST")
return
}
val dest_chest = work_bench.getRelative(chest_faces.second)
if(dest_chest.getType() != Material.CHEST)
{
getLogger().info("right block is not CHEST")
return
}
val recipe_invent = (recipe_block.getState() as InventoryHolder).getInventory()
val item = recipe_invent.getItem(0);
if(item == null)
{
getLogger().info("getItem 0 is empty")
return
}
val source_invent =
(source_chest.getState() as Chest).getBlockInventory()
var materials: MutableList<Pair<ItemStack, Int>>? = null
for(recipe: Recipe in Bukkit.getRecipesFor(item))
{
if(recipe is ShapedRecipe)
{
val shapes = recipe.getShape()
val map :Map<Char, ItemStack> = recipe.getIngredientMap()
for(c in shapes[0])
{
val stack = map.get(c)
if(stack == null)
{
continue
}
val type = stack.getType()
val index = source_invent.first(type)
if(index == -1)
{
return
}
val ingred_stack = source_invent.getItem(index)
if(materials == null)
{
materials = mutableListOf(Pair(ingred_stack, index))
}
else {
materials.add(Pair(ingred_stack, index))
}
}
}
}
val reduce_stack = fun(m: MutableList<Pair<ItemStack, Int>>?)
{
if(m == null)
{
return
}
for(p in m.listIterator())
{
if(p.first.getAmount() == 1)
{
source_invent.setItem(p.second, null);
}
else {
p.first.setAmount(p.first.getAmount() - 1)
}
}
}
val dest_invent = (dest_chest.getState() as Chest).getBlockInventory()
for(stack in dest_invent.iterator())
{
if(stack == null)
{
continue
}
if(stack.getType() != item.getType())
{
continue
}
if(stack.getMaxStackSize() == stack.getAmount())
{
continue
}
stack.setAmount(stack.getAmount() + 1)
reduce_stack(materials)
return
}
val empty_index = dest_invent.firstEmpty()
if(empty_index == -1)
{
return
}
item.setAmount(1)
dest_invent.setItem(empty_index, item)
reduce_stack(materials)
}
},
this
)
}
fun getSignAttachedFace(block: Block) : BlockFace?
{
val face = when {
block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN
-> BlockFace.WEST
block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN
-> BlockFace.EAST
block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN
-> BlockFace.SOUTH
block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN
-> BlockFace.NORTH
else -> return@getSignAttachedFace null
}
val sign_block = block.getRelative(face)
val sign = sign_block.getState() as org.bukkit.block.Sign
if(sign.getLine(0) != AUTO_CRAFT_TEXT)
{
return null
}
val attached_face = (sign.getData() as Attachable).getAttachedFace()
return when {
(face == BlockFace.EAST) && (attached_face == BlockFace.WEST)
-> BlockFace.EAST
(face == BlockFace.WEST) && (attached_face == BlockFace.EAST)
-> BlockFace.WEST
(face == BlockFace.SOUTH) && (attached_face == BlockFace.NORTH)
-> BlockFace.SOUTH
(face == BlockFace.NORTH) && (attached_face == BlockFace.SOUTH)
-> BlockFace.NORTH
else -> null
}
}
}
| mit | 513fde8f1f1194349e547f8461f7338d | 36.629921 | 99 | 0.414208 | 5.817407 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-cache/src/main/kotlin/slatekit/cache/SimpleSyncCache.kt | 1 | 2190 | package slatekit.cache
import slatekit.common.Identity
import slatekit.common.log.Logger
import slatekit.results.Outcome
class SimpleSyncCache(private val cache: Cache) : Cache {
override val id: Identity get() = cache.id
override val settings: CacheSettings = cache.settings
override val listener: ((CacheEvent) -> Unit)? get() = cache.listener
override val logger: Logger? get() = cache.logger
@Synchronized
override fun size(): Int = cache.size()
@Synchronized
override fun keys(): List<String> = cache.keys()
@Synchronized
override fun contains(key: String): Boolean = cache.contains(key)
@Synchronized
override fun stats(): List<CacheStats> = cache.stats()
@Synchronized
override fun stats(key:String): CacheStats? = cache.stats(key)
@Synchronized
override fun <T> get(key: String): T? = cache.get(key)
@Synchronized
override fun <T> getOrLoad(key: String): T? = cache.getOrLoad(key)
@Synchronized
override fun <T> getFresh(key: String): T? = cache.getFresh(key)
@Synchronized
override fun <T> put(key: String, desc: String, seconds: Int, fetcher: suspend () -> T?) = cache.put(key, desc, seconds, fetcher)
@Synchronized
override fun <T> set(key: String, value: T?) = cache.set(key, value)
@Synchronized
override fun delete(key: String): Outcome<Boolean> = cache.delete(key)
@Synchronized
override fun deleteAll(): Outcome<Boolean> = cache.deleteAll()
@Synchronized
override fun refresh(key: String):Outcome<Boolean> = cache.refresh(key)
@Synchronized
override fun expire(key: String):Outcome<Boolean> = cache.expire(key)
@Synchronized
override fun expireAll():Outcome<Boolean> = cache.expireAll()
companion object {
/**
* Convenience method to build async cache using Default channel coordinator
*/
fun of(id:Identity, settings: CacheSettings? = null, listener:((CacheEvent) -> Unit)? = null):SimpleSyncCache {
val raw = SimpleCache(id,settings ?: CacheSettings(10), listener )
val syncCache = SimpleSyncCache(raw)
return syncCache
}
}
}
| apache-2.0 | fcd96ba95f8f6b36799ecdee61eb8ce3 | 29.416667 | 133 | 0.671689 | 4.147727 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/channelgraph/ChannelAxisLabelTest.kt | 1 | 3671 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.channelgraph
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import com.vrem.util.EMPTY
import com.vrem.wifianalyzer.MainContextHelper
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.band.WiFiChannels
import com.vrem.wifianalyzer.wifi.graphutils.MAX_Y
import com.vrem.wifianalyzer.wifi.graphutils.MIN_Y
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
class ChannelAxisLabelTest {
private val settings = MainContextHelper.INSTANCE.settings
private val fixture = ChannelAxisLabel(WiFiBand.GHZ2, WiFiBand.GHZ2.wiFiChannels.wiFiChannelPairs()[0])
@After
fun tearDown() {
verifyNoMoreInteractions(settings)
MainContextHelper.INSTANCE.restore()
}
@Test
fun testYAxis() {
// execute & verify
assertEquals(String.EMPTY, fixture.formatLabel(MIN_Y.toDouble(), false))
assertEquals("-99", fixture.formatLabel(MIN_Y + 1.toDouble(), false))
assertEquals("0", fixture.formatLabel(MAX_Y.toDouble(), false))
assertEquals(String.EMPTY, fixture.formatLabel(MAX_Y + 1.toDouble(), false))
}
@Test
fun testXAxis() {
// setup
val (channel, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelFirst()
whenever(settings.countryCode()).thenReturn(Locale.US.country)
// execute
val actual = fixture.formatLabel(frequency.toDouble(), true)
// validate
assertEquals("" + channel, actual)
verify(settings).countryCode()
}
@Test
fun testXAxisWithFrequencyInRange() {
// setup
val (channel, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelFirst()
whenever(settings.countryCode()).thenReturn(Locale.US.country)
// execute & validate
assertEquals("" + channel, fixture.formatLabel(frequency - 2.toDouble(), true))
assertEquals("" + channel, fixture.formatLabel(frequency + 2.toDouble(), true))
verify(settings, times(2)).countryCode()
}
@Test
fun testXAxisWithFrequencyNotAllowedInLocale() {
// setup
val (_, frequency) = WiFiBand.GHZ2.wiFiChannels.wiFiChannelLast()
// execute
val actual = fixture.formatLabel(frequency.toDouble(), true)
// validate
assertEquals(String.EMPTY, actual)
}
@Test
fun testXAxisWithUnknownFrequencyReturnEmptyString() {
// setup
val wiFiChannels = WiFiBand.GHZ2.wiFiChannels
val (_, frequency) = wiFiChannels.wiFiChannelFirst()
// execute
val actual = fixture.formatLabel(frequency - WiFiChannels.FREQUENCY_OFFSET.toDouble(), true)
// validate
assertEquals(String.EMPTY, actual)
}
} | gpl-3.0 | 8aca881d12622a4c5cc0a14e505c2d26 | 36.85567 | 107 | 0.707164 | 4.482295 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/property/augAssignmentAndIncInClassViaConvention.kt | 3 | 783 | // FILE: 1.kt
package test
class Test(var result: Int)
class A {
var result = Test(1)
inline var z: Test
get() = result
set(value) {
result = value
}
}
operator fun Test.plus(p: Int): Test {
return Test(result + p)
}
operator fun Test.inc(): Test {
return Test(result + 1)
}
// FILE: 2.kt
import test.*
fun box(): String {
val a = A()
a.z = Test(1)
a.z += 1
if (a.result.result != 2) return "fail 1: ${a.result.result}"
var p = a.z++
if (a.result.result != 3) return "fail 2: ${a.result.result}"
if (p.result != 2) return "fail 3: ${p.result}"
p = ++a.z
if (a.result.result != 4) return "fail 4: ${a.result.result}"
if (p.result != 4) return "fail 5: ${p.result}"
return "OK"
} | apache-2.0 | eba3eef6d9b96e7dae2449e937d8af36 | 17.666667 | 65 | 0.537676 | 2.9 | false | true | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/IndexUpToDateCheckIn.kt | 4 | 1253 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing
import com.intellij.openapi.util.ThrowableComputable
internal object IndexUpToDateCheckIn {
private val upToDateCheckState = ThreadLocal<Int>()
@JvmStatic
fun <T, E : Throwable?> disableUpToDateCheckIn(runnable: ThrowableComputable<T, E>): T {
disableUpToDateCheckForCurrentThread()
return try {
runnable.compute()
}
finally {
enableUpToDateCheckForCurrentThread()
}
}
@JvmStatic
fun isUpToDateCheckEnabled(): Boolean {
val value: Int? = upToDateCheckState.get()
return value == null || value == 0
}
private fun disableUpToDateCheckForCurrentThread() {
val currentValue = upToDateCheckState.get()
upToDateCheckState.set(if (currentValue == null) 1 else currentValue.toInt() + 1)
}
private fun enableUpToDateCheckForCurrentThread() {
val currentValue = upToDateCheckState.get()
if (currentValue != null) {
val newValue = currentValue.toInt() - 1
if (newValue != 0) {
upToDateCheckState.set(newValue)
}
else {
upToDateCheckState.remove()
}
}
}
} | apache-2.0 | dbc4531111ee605f9c5ea044a23b0294 | 28.162791 | 140 | 0.69593 | 4.675373 | false | false | false | false |
smmribeiro/intellij-community | build/launch/src/com/intellij/tools/launch/TeamCityHelper.kt | 4 | 1524 | package com.intellij.tools.launch
import java.io.File
import java.util.*
object TeamCityHelper {
val systemProperties: Map<String, String> by lazy {
if (!isUnderTeamCity) {
return@lazy mapOf<String, String>()
}
val systemPropertiesEnvName = "TEAMCITY_BUILD_PROPERTIES_FILE"
val systemPropertiesFile = System.getenv(systemPropertiesEnvName)
if (systemPropertiesFile == null || systemPropertiesFile.isEmpty()) {
throw RuntimeException("TeamCity environment variable $systemPropertiesEnvName was not found while running under TeamCity")
}
val file = File(systemPropertiesFile)
if (!file.exists()) {
throw RuntimeException("TeamCity system properties file is not found: $file")
}
return@lazy loadPropertiesFile(file)
}
val isUnderTeamCity: Boolean by lazy {
val version = System.getenv("TEAMCITY_VERSION")
if (version != null) {
println("TeamCityHelper: running under TeamCity $version")
}
else {
println("TeamCityHelper: NOT running under TeamCity")
}
version != null
}
val tempDirectory: File? by lazy {
systemProperties["teamcity.build.tempDir"]?.let { File(it) }
}
private fun loadPropertiesFile(file: File): Map<String, String> {
val result = mutableMapOf<String, String>()
val properties = Properties()
file.reader(Charsets.UTF_8).use { properties.load(it) }
for (entry in properties.entries) {
result[entry.key as String] = entry.value as String
}
return result
}
} | apache-2.0 | 2be08711863a1af4337b171494343ab8 | 27.240741 | 129 | 0.694226 | 4.430233 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/checker/WhenNonExhaustive.kt | 3 | 2690 | fun nonExhaustiveInt(x: Int) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(x) {
0 -> false
}
fun nonExhaustiveBoolean(b: Boolean) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'true' branch or 'else' branch instead">when</error>(b) {
false -> 0
}
fun nonExhaustiveNullableBoolean(b: Boolean?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead">when</error>(b) {
false -> 0
true -> 1
}
enum class Color {
RED,
GREEN,
BLUE
}
fun nonExhaustiveEnum(c: Color) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'RED', 'BLUE' branches or 'else' branch instead">when</error>(c) {
Color.GREEN -> 0xff00
}
fun nonExhaustiveNullable(c: Color?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'GREEN', 'null' branches or 'else' branch instead">when</error>(c) {
Color.RED -> 0xff
Color.BLUE -> 0xff0000
}
fun whenOnEnum(c: Color) {
<warning descr="[NON_EXHAUSTIVE_WHEN] 'when' expression on enum is recommended to be exhaustive, add 'RED' branch or 'else' branch instead">when</warning>(c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
enum class EnumInt {
A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15
}
fun whenOnLongEnum(i: EnumInt) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', ... branches or 'else' branch instead">when</error> (i) {
EnumInt.A7 -> 7
}
sealed class Variant {
object Singleton : Variant()
class Something : Variant()
object Another : Variant()
}
fun nonExhaustiveSealed(v: Variant) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'is Something' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
}
fun nonExhaustiveNullableSealed(v: Variant?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'null' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
is Variant.Something -> true
}
sealed class Empty
fun nonExhaustiveEmpty(e: Empty) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning>e</warning>) {}
fun nonExhaustiveNullableEmpty(e: Empty?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning>e</warning>) {}
| apache-2.0 | b216391458b287a03dd844fac9661ad2 | 40.384615 | 216 | 0.680297 | 3.3625 | false | false | false | false |
google/intellij-community | platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/binaryReproducibility/FileTreeContentTest.kt | 3 | 6467 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.testFramework.binaryReproducibility
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.Decompressor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestInputStream
import java.security.MessageDigest
import java.util.*
import kotlin.io.path.*
import kotlin.streams.toList
class FileTreeContentTest(private val diffDir: Path = Path.of(System.getProperty("user.dir")).resolve(".diff"),
private val tempDir: Path = Files.createTempDirectory(this::class.java.simpleName)) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
require(args.count() == 2)
val path1 = Path.of(args[0])
val path2 = Path.of(args[1])
require(path1.exists())
require(path2.exists())
val test = FileTreeContentTest()
val assertion = when {
path1.isDirectory() && path2.isDirectory() -> test.assertTheSameDirectoryContent(path1, path2)
path1.isRegularFile() && path2.isRegularFile() -> test.assertTheSameFile(path1, path2)
else -> throw IllegalArgumentException()
}
if (assertion != null) throw assertion
}
}
init {
FileUtil.delete(diffDir)
Files.createDirectories(diffDir)
}
private fun listingDiff(firstIteration: Set<Path>, nextIteration: Set<Path>) =
((firstIteration - nextIteration) + (nextIteration - firstIteration))
.filterNot { it.name == ".DS_Store" }
fun assertTheSameFile(relativeFilePath: Path, dir1: Path, dir2: Path): AssertionError? {
val path1 = dir1.resolve(relativeFilePath)
val path2 = dir2.resolve(relativeFilePath)
return assertTheSameFile(path1, path2, "$relativeFilePath")
}
private fun assertTheSameFile(path1: Path, path2: Path, relativeFilePath: String = path1.name): AssertionError? {
if (!Files.exists(path1) ||
!Files.exists(path2) ||
!path1.isRegularFile() ||
path1.checksum() == path2.checksum() &&
path1.permissions() == path2.permissions()) {
return null
}
println("Failed for $relativeFilePath")
require(path1.extension == path2.extension)
val contentError = when (path1.extension) {
"tar.gz", "gz", "tar" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Tar(path1).extract(it) },
path2.unpackingDir().also { Decompressor.Tar(path2).extract(it) }
) ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
"zip", "jar", "ijx" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Zip(path1).withZipExtensions().extract(it) },
path2.unpackingDir().also { Decompressor.Zip(path2).withZipExtensions().extract(it) }
) ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
else -> if (path1.checksum() != path2.checksum()) {
saveDiff(relativeFilePath, path1, path2)
AssertionError("Checksum mismatch for $relativeFilePath")
}
else null
}
if (path1.permissions() != path2.permissions()) {
val permError = AssertionError("Permissions mismatch for $relativeFilePath: ${path1.permissions()} vs ${path2.permissions()}")
contentError?.addSuppressed(permError) ?: return permError
}
requireNotNull(contentError)
return contentError
}
private fun saveDiff(relativePath: String, file1: Path, file2: Path) {
fun fileIn(subdir: String): Path {
val textFileName = relativePath.removeSuffix(".txt") + ".txt"
val target = diffDir.resolve(subdir)
.resolve(relativePath)
.resolveSibling(textFileName)
target.parent.createDirectories()
return target
}
val a = fileIn("a")
val b = fileIn("b")
file1.writeContent(a)
file2.writeContent(b)
fileIn("diff").writeText(diff(a, b))
}
private fun Path.checksum(): String = inputStream().buffered().use { input ->
val digest = MessageDigest.getInstance("SHA-256")
DigestInputStream(input, digest).use {
var bytesRead = 0
val buffer = ByteArray(1024 * 8)
while (bytesRead != -1) {
bytesRead = it.read(buffer)
}
}
Base64.getEncoder().encodeToString(digest.digest())
}
private fun Path.permissions(): Set<PosixFilePermission> =
Files.getFileAttributeView(this, PosixFileAttributeView::class.java)
?.readAttributes()?.permissions() ?: emptySet()
private fun Path.writeContent(target: Path) {
when (extension) {
"jar", "zip", "tar.gz", "gz", "tar", "ijx" -> error("$this is expected to be already unpacked")
"class" -> target.writeText(process("javap", "-verbose", "$this"))
else -> copyTo(target, overwrite = true)
}
}
private fun Path.unpackingDir(): Path {
val unpackingDir = tempDir
.resolve("unpacked")
.resolve("$fileName".replace(".", "_"))
.resolve(UUID.randomUUID().toString())
FileUtil.delete(unpackingDir)
return unpackingDir
}
private fun diff(path1: Path, path2: Path) = process("git", "diff", "--no-index", "--", "$path1", "$path2")
private fun process(vararg command: String): String {
val process = ProcessBuilder(*command).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
process.waitFor()
return output
}
fun assertTheSameDirectoryContent(dir1: Path, dir2: Path): AssertionError? {
require(dir1.isDirectory())
require(dir2.isDirectory())
val listing1 = Files.walk(dir1).use { it.toList() }
val listing2 = Files.walk(dir2).use { it.toList() }
val relativeListing1 = listing1.map(dir1::relativize)
val listingDiff = listingDiff(relativeListing1.toSet(), listing2.map(dir2::relativize).toSet())
val contentComparisonFailures = relativeListing1.mapNotNull { assertTheSameFile(it, dir1, dir2) }
return when {
listingDiff.isNotEmpty() -> AssertionError(listingDiff.joinToString(prefix = "Listing diff for $dir1 and $dir2:\n", separator = "\n"))
contentComparisonFailures.isNotEmpty() -> AssertionError("$dir1 doesn't match $dir2")
else -> null
}?.apply {
contentComparisonFailures.forEach(::addSuppressed)
}
}
}
| apache-2.0 | aed7120841e735a503763cf419e9d889 | 39.93038 | 140 | 0.680841 | 4.111252 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/LoginActivity.kt | 1 | 26868 | package com.habitrpg.android.habitica.ui.activities
import android.accounts.AccountManager
import android.animation.*
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.text.SpannableString
import android.text.style.UnderlineSpan
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.GoogleAuthException
import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException
import com.google.android.gms.auth.UserRecoverableAuthException
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.GooglePlayServicesUtil
import com.google.android.gms.common.Scopes
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.HostConfig
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.extensions.addCloseButton
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.helpers.*
import com.habitrpg.android.habitica.models.auth.UserAuthResponse
import com.habitrpg.android.habitica.proxy.CrashlyticsProxy
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.login.LockableScrollView
import com.habitrpg.android.habitica.ui.views.login.LoginBackgroundView
import com.willowtreeapps.signinwithapplebutton.SignInWithAppleConfiguration
import io.reactivex.Flowable
import io.reactivex.exceptions.Exceptions
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import javax.inject.Inject
class LoginActivity : BaseActivity(), Consumer<UserAuthResponse> {
@Inject
lateinit var apiClient: ApiClient
@Inject
lateinit var sharedPrefs: SharedPreferences
@Inject
lateinit var hostConfig: HostConfig
@Inject
internal lateinit var userRepository: UserRepository
@Inject
@JvmField
var keyHelper: KeyHelper? = null
@Inject
lateinit var crashlyticsProxy: CrashlyticsProxy
@Inject
lateinit var configManager: AppConfigManager
private var isRegistering: Boolean = false
private var isShowingForm: Boolean = false
private val backgroundContainer: LockableScrollView by bindView(R.id.background_container)
internal val backgroundView: LoginBackgroundView by bindView(R.id.background_view)
internal val newGameButton: Button by bindView(R.id.new_game_button)
internal val showLoginButton: Button by bindView(R.id.show_login_button)
internal val scrollView: ScrollView by bindView(R.id.login_scrollview)
private val formWrapper: LinearLayout by bindView(R.id.login_linear_layout)
private val backButton: Button by bindView(R.id.back_button)
private val logoView: ImageView by bindView(R.id.logo_view)
private val mLoginNormalBtn: Button by bindView(R.id.login_btn)
private val mProgressBar: ProgressBar by bindView(R.id.PB_AsyncTask)
private val mUsernameET: EditText by bindView(R.id.username)
private val mPasswordET: EditText by bindView(R.id.password)
private val mEmail: EditText by bindView(R.id.email)
private val mConfirmPassword: EditText by bindView(R.id.confirm_password)
private val forgotPasswordButton: Button by bindView(R.id.forgot_password)
private val facebookLoginButton: Button by bindView(R.id.fb_login_button)
private val googleLoginButton: Button by bindView(R.id.google_login_button)
private val appleLoginButton: Button by bindView(R.id.apple_login_button)
private var callbackManager = CallbackManager.Factory.create()
private var googleEmail: String? = null
private var loginManager = LoginManager.getInstance()
private val loginClick = View.OnClickListener {
mProgressBar.visibility = View.VISIBLE
if (isRegistering) {
val username: String = mUsernameET.text.toString().trim { it <= ' ' }
val email: String = mEmail.text.toString().trim { it <= ' ' }
val password: String = mPasswordET.text.toString()
val confirmPassword: String = mConfirmPassword.text.toString()
if (username.isEmpty() || password.isEmpty() || email.isEmpty() || confirmPassword.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
if (password.length < configManager.minimumPasswordLength()) {
showValidationError(getString(R.string.password_too_short, configManager.minimumPasswordLength()))
return@OnClickListener
}
apiClient.registerUser(username, email, password, confirmPassword)
.subscribe(this@LoginActivity,
Consumer {
hideProgress()
RxErrorHandler.reportError(it)
})
} else {
val username: String = mUsernameET.text.toString().trim { it <= ' ' }
val password: String = mPasswordET.text.toString()
if (username.isEmpty() || password.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
apiClient.connectUser(username, password).subscribe(this@LoginActivity,
Consumer {
hideProgress()
RxErrorHandler.reportError(it)
})
}
}
override fun getLayoutResId(): Int {
window.requestFeature(Window.FEATURE_ACTION_BAR)
return R.layout.activity_login
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.hide()
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false)
setupFacebookLogin()
mLoginNormalBtn.setOnClickListener(loginClick)
val content = SpannableString(forgotPasswordButton.text)
content.setSpan(UnderlineSpan(), 0, content.length, 0)
forgotPasswordButton.text = content
this.isRegistering = true
val additionalData = HashMap<String, Any>()
additionalData["page"] = this.javaClass.simpleName
AmplitudeManager.sendEvent("navigate", AmplitudeManager.EVENT_CATEGORY_NAVIGATION, AmplitudeManager.EVENT_HITTYPE_PAGEVIEW, additionalData)
backgroundContainer.post { backgroundContainer.scrollTo(0, backgroundContainer.bottom) }
backgroundContainer.setScrollingEnabled(false)
val window = window
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, R.color.black_20_alpha)
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
newGameButton.setOnClickListener { newGameButtonClicked() }
showLoginButton.setOnClickListener { showLoginButtonClicked() }
backButton.setOnClickListener { backButtonClicked() }
forgotPasswordButton.setOnClickListener { onForgotPasswordClicked() }
facebookLoginButton.setOnClickListener { handleFacebookLogin() }
googleLoginButton.setOnClickListener { handleGoogleLogin() }
appleLoginButton.setOnClickListener {
val configuration = SignInWithAppleConfiguration(
clientId = BuildConfig.APPLE_AUTH_CLIENT_ID,
redirectUri = "${hostConfig.address}/api/v4/user/auth/apple",
scope = "name email"
)
val fragmentTag = "SignInWithAppleButton-SignInWebViewDialogFragment"
SignInWithAppleService(supportFragmentManager, fragmentTag, configuration) { result ->
when (result) {
is SignInWithAppleResult.Success -> {
val response = UserAuthResponse()
response.id = result.userID
response.apiToken = result.apiKey
response.newUser = result.newUser
}
}
}.show()
}
}
private fun setupFacebookLogin() {
callbackManager = CallbackManager.Factory.create()
loginManager.registerCallback(callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
val accessToken = AccessToken.getCurrentAccessToken()
compositeSubscription.add(apiClient.connectSocial("facebook", accessToken.userId, accessToken.token)
.subscribe(this@LoginActivity, RxErrorHandler.handleEmptyError()))
}
override fun onCancel() { /* no-on */ }
override fun onError(exception: FacebookException) {
exception.printStackTrace()
}
})
}
override fun onBackPressed() {
if (isShowingForm) {
hideForm()
} else {
super.onBackPressed()
}
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
private fun resetLayout() {
if (this.isRegistering) {
if (this.mEmail.visibility == View.GONE) {
show(this.mEmail)
}
if (this.mConfirmPassword.visibility == View.GONE) {
show(this.mConfirmPassword)
}
} else {
if (this.mEmail.visibility == View.VISIBLE) {
hide(this.mEmail)
}
if (this.mConfirmPassword.visibility == View.VISIBLE) {
hide(this.mConfirmPassword)
}
}
}
private fun startMainActivity() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun startSetupActivity() {
val intent = Intent(this@LoginActivity, SetupActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun toggleRegistering() {
this.isRegistering = (!this.isRegistering)
this.setRegistering()
}
private fun setRegistering() {
if (this.isRegistering) {
this.mLoginNormalBtn.text = getString(R.string.register_btn)
mUsernameET.setHint(R.string.username)
mPasswordET.imeOptions = EditorInfo.IME_ACTION_NEXT
facebookLoginButton.setText(R.string.register_btn_fb)
googleLoginButton.setText(R.string.register_btn_google)
} else {
this.mLoginNormalBtn.text = getString(R.string.login_btn)
mUsernameET.setHint(R.string.email_username)
mPasswordET.imeOptions = EditorInfo.IME_ACTION_DONE
facebookLoginButton.setText(R.string.login_btn_fb)
googleLoginButton.setText(R.string.login_btn_google)
}
this.resetLayout()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
callbackManager.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == Activity.RESULT_OK) {
googleEmail = data?.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
handleGoogleLoginResult()
}
}
if (requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR) {
// RESULT_CANCELED occurs when user denies requested permissions. In this case we don't
// want to immediately ask them to accept permissions again. See Issue #1290 on github.
if (resultCode != Activity.RESULT_CANCELED) {
handleGoogleLoginResult()
}
}
if (requestCode == FacebookSdk.getCallbackRequestCodeOffset()) {
//This is necessary because the regular login callback is not called for some reason
val accessToken = AccessToken.getCurrentAccessToken()
if (accessToken != null && accessToken.token != null) {
compositeSubscription.add(apiClient.connectSocial("facebook", accessToken.userId, accessToken.token)
.subscribe(this@LoginActivity, Consumer { hideProgress() }))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_toggleRegistering -> toggleRegistering()
}
return super.onOptionsItemSelected(item)
}
@Throws(Exception::class)
private fun saveTokens(api: String, user: String) {
this.apiClient.updateAuthenticationCredentials(user, api)
sharedPrefs.edit {
putString(getString(R.string.SP_userID), user)
val encryptedKey = if (keyHelper != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
keyHelper?.encrypt(api)
} catch (e: Exception) {
null
}
} else null
if (encryptedKey?.length ?: 0 > 5) {
putString(user, encryptedKey)
} else {
//Something might have gone wrong with encryption, so fall back to this.
putString(getString(R.string.SP_APIToken), api)
}
}
}
private fun hideProgress() {
runOnUiThread {
mProgressBar.visibility = View.GONE
}
}
private fun showValidationError(resourceMessageString: Int) {
showValidationError(getString(resourceMessageString))
}
private fun showValidationError(message: String) {
mProgressBar.visibility = View.GONE
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.login_validation_error_title)
alert.setMessage(message)
alert.addOkButton()
alert.show()
}
override fun accept(userAuthResponse: UserAuthResponse) {
hideProgress()
try {
saveTokens(userAuthResponse.token, userAuthResponse.id)
} catch (e: Exception) {
crashlyticsProxy.logException(e)
}
HabiticaBaseApplication.reloadUserComponent()
compositeSubscription.add(userRepository.retrieveUser(true)
.subscribe(Consumer {
if (userAuthResponse.newUser) {
this.startSetupActivity()
} else {
AmplitudeManager.sendEvent("login", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT)
this.startMainActivity()
}
}, RxErrorHandler.handleEmptyError()))
}
private fun handleFacebookLogin() {
loginManager.logInWithReadPermissions(this, listOf("user_friends"))
}
private fun handleGoogleLogin() {
if (!checkPlayServices()) {
return
}
val accountTypes = arrayOf("com.google")
val intent = AccountManager.newChooseAccountIntent(null, null,
accountTypes, true, null, null, null, null)
try {
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT)
} catch (e: ActivityNotFoundException) {
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.authentication_error_title)
alert.setMessage(R.string.google_services_missing)
alert.addCloseButton()
alert.show()
}
}
private fun handleGoogleLoginResult() {
val scopesString = Scopes.PROFILE + " " + Scopes.EMAIL
val scopes = "oauth2:$scopesString"
Flowable.defer<String> {
try {
@Suppress("Deprecation")
return@defer Flowable.just(GoogleAuthUtil.getToken(this, googleEmail, scopes))
} catch (e: IOException) {
throw Exceptions.propagate(e)
} catch (e: GoogleAuthException) {
throw Exceptions.propagate(e)
}
}
.subscribeOn(Schedulers.io())
.flatMap { token -> apiClient.connectSocial("google", googleEmail ?: "", token) }
.subscribe(this@LoginActivity, Consumer { throwable ->
throwable.printStackTrace()
hideProgress()
throwable.cause?.let {
if (GoogleAuthException::class.java.isAssignableFrom(it.javaClass)) {
handleGoogleAuthException(throwable.cause as GoogleAuthException)
}
}
})
}
private fun handleGoogleAuthException(e: Exception) {
if (e is GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
val statusCode = e
.connectionStatusCode
GoogleApiAvailability.getInstance()
@Suppress("DEPRECATION")
GooglePlayServicesUtil.showErrorDialogFragment(statusCode,
this@LoginActivity,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR) {
}
} else if (e is UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
val intent = e.intent
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
}
}
private fun checkPlayServices(): Boolean {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(this)
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result, PLAY_SERVICES_RESOLUTION_REQUEST).show()
}
return false
}
return true
}
private fun newGameButtonClicked() {
isRegistering = true
showForm()
setRegistering()
}
private fun showLoginButtonClicked() {
isRegistering = false
showForm()
setRegistering()
}
private fun backButtonClicked() {
if (isShowingForm) {
hideForm()
}
}
private fun showForm() {
isShowingForm = true
val panAnimation = ObjectAnimator.ofInt(backgroundContainer, "scrollY", 0).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat<View>(newGameButton, View.ALPHA, 0.toFloat())
val showLoginAlphaAnimation = ObjectAnimator.ofFloat<View>(showLoginButton, View.ALPHA, 0.toFloat())
val scaleLogoAnimation = ValueAnimator.ofInt(logoView.measuredHeight, (logoView.measuredHeight * 0.75).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int ?: 0
val layoutParams = logoView.layoutParams
layoutParams.height = value
logoView.layoutParams = layoutParams
}
if (isRegistering) {
newGameAlphaAnimation.startDelay = 600
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.GONE
showLoginButton.visibility = View.GONE
scrollView.visibility = View.VISIBLE
scrollView.alpha = 1f
}
})
} else {
showLoginAlphaAnimation.startDelay = 600
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.GONE
showLoginButton.visibility = View.GONE
scrollView.visibility = View.VISIBLE
scrollView.alpha = 1f
}
})
}
val backAlphaAnimation = ObjectAnimator.ofFloat<View>(backButton, View.ALPHA, 1.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, newGameAlphaAnimation, showLoginAlphaAnimation, scaleLogoAnimation)
showAnimation.play(backAlphaAnimation).after(panAnimation)
for (i in 0 until formWrapper.childCount) {
val view = formWrapper.getChildAt(i)
view.alpha = 0f
val animator = ObjectAnimator.ofFloat<View>(view, View.ALPHA, 1.toFloat()).setDuration(400)
animator.startDelay = (100 * i).toLong()
showAnimation.play(animator).after(panAnimation)
}
showAnimation.start()
}
private fun hideForm() {
isShowingForm = false
val panAnimation = ObjectAnimator.ofInt(backgroundContainer, "scrollY", backgroundContainer.bottom).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat<View>(newGameButton, View.ALPHA, 1.toFloat()).setDuration(700)
val showLoginAlphaAnimation = ObjectAnimator.ofFloat<View>(showLoginButton, View.ALPHA, 1.toFloat()).setDuration(700)
val scaleLogoAnimation = ValueAnimator.ofInt(logoView.measuredHeight, (logoView.measuredHeight * 1.333333).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int
val layoutParams = logoView.layoutParams
layoutParams.height = value ?: 0
logoView.layoutParams = layoutParams
}
showLoginAlphaAnimation.startDelay = 300
val scrollViewAlphaAnimation = ObjectAnimator.ofFloat<View>(scrollView, View.ALPHA, 0.toFloat()).setDuration(800)
scrollViewAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.VISIBLE
showLoginButton.visibility = View.VISIBLE
scrollView.visibility = View.INVISIBLE
}
})
val backAlphaAnimation = ObjectAnimator.ofFloat<View>(backButton, View.ALPHA, 0.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, scrollViewAlphaAnimation, backAlphaAnimation, scaleLogoAnimation)
showAnimation.play(newGameAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.play(showLoginAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.start()
dismissKeyboard()
}
private fun onForgotPasswordClicked() {
val input = EditText(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
input.setAutofillHints(EditText.AUTOFILL_HINT_EMAIL_ADDRESS)
}
input.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT)
input.layoutParams = lp
val alertDialog = HabiticaAlertDialog(this)
alertDialog.setTitle(R.string.forgot_password_title)
alertDialog.setMessage(R.string.forgot_password_description)
alertDialog.setAdditionalContentView(input)
alertDialog.addButton(R.string.send, true) { _, _ ->
userRepository.sendPasswordResetEmail(input.text.toString()).subscribe(Consumer { showPasswordEmailConfirmation() }, RxErrorHandler.handleEmptyError())
}
alertDialog.addCancelButton()
alertDialog.show()
}
private fun showPasswordEmailConfirmation() {
val alert = HabiticaAlertDialog(this)
alert.setMessage(R.string.forgot_password_confirmation)
alert.addOkButton()
alert.show()
}
companion object {
internal const val REQUEST_CODE_PICK_ACCOUNT = 1000
private const val REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001
private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
fun show(v: View) {
v.visibility = View.VISIBLE
}
fun hide(v: View) {
v.visibility = View.GONE
}
}
}
| gpl-3.0 | f7fee02d7768cac8fe75244c3b8f4b57 | 41.901961 | 171 | 0.636556 | 5.378979 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/models/ProjectFaq.kt | 1 | 1487 | package com.kickstarter.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.joda.time.DateTime
/**
* Frequently Asked Questions Data Structure
*
* Note: This data model is written in kotlin and using kotlin
* parcelize because it's meant to be used only with GraphQL
* networking client.
*/
@Parcelize
class ProjectFaq private constructor(
val id: Long,
val answer: String,
val createdAt: DateTime? = null,
val question: String
) : Parcelable {
@Parcelize
data class Builder(
var id: Long = -1,
var answer: String = "",
var createdAt: DateTime? = null,
var question: String = ""
) : Parcelable {
fun id(id: Long) = apply { this.id = id }
fun answer(answer: String) = apply { this.answer = answer }
fun createdAt(createdAt: DateTime?) = apply { this.createdAt = createdAt }
fun question(question: String) = apply { this.question = question }
fun build() = ProjectFaq(id = id, answer = answer, createdAt = createdAt, question = question)
}
companion object {
fun builder() = Builder()
}
fun toBuilder() = Builder(this.id, this.answer, this.createdAt, this.question)
override fun equals(other: Any?): Boolean =
if (other is ProjectFaq) {
other.id == this.id && other.answer == this.answer &&
other.createdAt == this.createdAt && other.question == this.question
} else false
}
| apache-2.0 | 80e95dd147e531f016bc258e3a6ce8fd | 30.638298 | 102 | 0.640215 | 4.224432 | false | false | false | false |
webscene/webscene-client | src/main/kotlin/org/webscene/client/html/HtmlCreator.kt | 1 | 2966 | package org.webscene.client.html
import org.webscene.client.createHtmlElement
import org.webscene.client.createHtmlHeading
import org.webscene.client.createHtmlImage
import org.webscene.client.createParentHtmlElement
import org.webscene.client.html.element.HtmlElement
import org.webscene.client.html.element.ImageElement
import org.webscene.client.html.element.ParentHtmlElement
@Suppress("unused")
/**
* Manages creating HTML elements.
*/
object HtmlCreator {
/**
* Creates a new parent HTML element that can contain child HTML elements.
* @param tagName Name of the tag.
* @param block Initialisation block for setting up the HTML element.
* @return A new [parent HTML element][ParentHtmlElement].
*/
fun parentElement(tagName: String, block: ParentHtmlElement.() -> Unit) =
createParentHtmlElement(tagName, block)
/**
* Creates a new HTML element which doesn't have any child HTML elements.
* @param tagName Name of the tag.
* @param block Initialisation block for setting up the HTML element.
* @return A new [HTML element][HtmlElement].
*/
fun element(tagName: String, block: HtmlElement.() -> Unit) = createHtmlElement(tagName, block)
/**
* Creates a new HTML **span** element that can contain HTML elements, and is used to group element in a document.
* @param block Initialisation block for setting up the span element.
* @return A new span element.
*/
fun span(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("span", block)
/**
* Creates a new HTML **div** element that can contain HTML elements, and is used to layout elements in a document.
* @param block Initialisation block for setting up the div element.
* @return A new div element.
*/
fun div(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("div", block)
/**
* Creates a new HTML heading that can contain HTML elements, and is used to display a heading.
* @param level A number between 1-6 for the size of the heading. Using a bigger number results in a smaller
* heading being displayed.
* @param block Initialisation block for setting up the heading.
* @return A new heading.
*/
fun heading(level: Int = 1, block: ParentHtmlElement.() -> Unit): ParentHtmlElement = createHtmlHeading(
level, block)
fun header(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("header", block)
fun footer(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("footer", block)
fun image(src: String, alt: String = "", block: ImageElement.() -> Unit): ImageElement = createHtmlImage(
src = src, alt = alt, block = block)
fun bold(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("b", block)
fun italic(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("i", block)
}
| apache-2.0 | ec918f970e6fb71e0f083b2ce02c72ca | 43.268657 | 119 | 0.705327 | 4.619938 | false | false | false | false |
radiKal07/pc-notifications | mobile/app/src/main/kotlin/com/radikal/pcnotifications/model/service/impl/SharedPreferencesServerDetailsDao.kt | 1 | 1556 | package com.radikal.pcnotifications.model.service.impl
import android.content.SharedPreferences
import com.radikal.pcnotifications.exceptions.ServerDetailsNotFoundException
import com.radikal.pcnotifications.model.domain.ServerDetails
import com.radikal.pcnotifications.model.service.ServerDetailsDao
import javax.inject.Inject
/**
* Created by tudor on 26.02.2017.
*/
class SharedPreferencesServerDetailsDao @Inject constructor(var sharedPreferences: SharedPreferences) : ServerDetailsDao{
val SERVER_HOSTNAME = "server_hostname"
val SERVER_IP = "server_ip"
val SERVER_PORT = "server_port"
override fun save(serverDetails: ServerDetails) {
val editor = sharedPreferences.edit()
editor.putString(SERVER_HOSTNAME, serverDetails.hostname)
editor.putString(SERVER_IP, serverDetails.ip)
editor.putInt(SERVER_PORT, serverDetails.port)
editor.apply()
}
override fun retrieve(): ServerDetails {
val hostname = sharedPreferences.getString(SERVER_HOSTNAME, "Default")
val ip = sharedPreferences.getString(SERVER_IP, null)
val port = sharedPreferences.getInt(SERVER_PORT, -1)
if (ip == null || port == -1) {
throw ServerDetailsNotFoundException("Server details not found")
}
return ServerDetails(hostname, ip, port)
}
override fun delete() {
val editor = sharedPreferences.edit()
editor.remove(SERVER_HOSTNAME)
editor.remove(SERVER_IP)
editor.remove(SERVER_PORT)
editor.apply()
}
} | apache-2.0 | 9b915b64ac65e064cf9c8952622336fc | 34.386364 | 121 | 0.712725 | 4.60355 | false | false | false | false |
google/MOE | client/src/main/java/com/google/devtools/moe/client/codebase/expressions/RepositoryExpression.kt | 2 | 1768 | /*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.moe.client.codebase.expressions
/**
* An [Expression] describing a repository checkout. This is the starting point for building
* Expressions, e.g.: `RepositoryExpression("myGitRepo").atRevision("12345").translateTo("public").`
*/
data class RepositoryExpression(val term: Term) : Expression() {
constructor(repositoryName: String) : this(Term(repositoryName))
val repositoryName: String
get() = term.identifier
/** Add an option name-value pair to the expression, e.g. "myRepo" -> "myRepo(revision=4)". */
fun withOption(optionName: String, optionValue: String): RepositoryExpression =
RepositoryExpression(term.withOption(optionName, optionValue))
/** Add multiple options to a repository. */
fun withOptions(options: Map<String, String>): RepositoryExpression =
RepositoryExpression(term.withOptions(options))
/** A helper method for adding a "revision" option with the given value. */
fun atRevision(revId: String): RepositoryExpression = withOption("revision", revId)
fun getOption(optionName: String): String? = term.options[optionName]
override fun toString(): String = term.toString()
}
| apache-2.0 | fd828da0ff111ddfa6db97690bb9e4ca | 39.181818 | 100 | 0.739253 | 4.322738 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadFragment.kt | 2 | 9043 | package eu.kanade.tachiyomi.ui.download
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.util.plusAssign
import kotlinx.android.synthetic.main.fragment_download_queue.*
import nucleus.factory.RequiresPresenter
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Fragment that shows the currently active downloads.
* Uses R.layout.fragment_download_queue.
*/
@RequiresPresenter(DownloadPresenter::class)
class DownloadFragment : BaseRxFragment<DownloadPresenter>() {
/**
* Adapter containing the active downloads.
*/
private lateinit var adapter: DownloadAdapter
/**
* Menu item to start the queue.
*/
private var startButton: MenuItem? = null
/**
* Menu item to pause the queue.
*/
private var pauseButton: MenuItem? = null
/**
* Menu item to clear the queue.
*/
private var clearButton: MenuItem? = null
/**
* Subscription list to be cleared during [onDestroyView].
*/
private val subscriptions by lazy { CompositeSubscription() }
/**
* Map of subscriptions for active downloads.
*/
private val progressSubscriptions by lazy { HashMap<Download, Subscription>() }
/**
* Whether the download queue is running or not.
*/
private var isRunning: Boolean = false
companion object {
/**
* Creates a new instance of this fragment.
*
* @return a new instance of [DownloadFragment].
*/
fun newInstance(): DownloadFragment {
return DownloadFragment()
}
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View {
return inflater.inflate(R.layout.fragment_download_queue, container, false)
}
override fun onViewCreated(view: View, savedState: Bundle?) {
setToolbarTitle(R.string.label_download_queue)
// Check if download queue is empty and update information accordingly.
setInformationView()
// Initialize adapter.
adapter = DownloadAdapter(activity)
recycler.adapter = adapter
// Set the layout manager for the recycler and fixed size.
recycler.layoutManager = LinearLayoutManager(activity)
recycler.setHasFixedSize(true)
// Suscribe to changes
subscriptions += presenter.downloadManager.runningSubject
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onQueueStatusChange(it) }
subscriptions += presenter.getStatusObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onStatusChange(it) }
subscriptions += presenter.getProgressObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onUpdateDownloadedPages(it) }
}
override fun onDestroyView() {
for (subscription in progressSubscriptions.values) {
subscription.unsubscribe()
}
progressSubscriptions.clear()
subscriptions.clear()
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.download_queue, menu)
// Set start button visibility.
startButton = menu.findItem(R.id.start_queue).apply {
isVisible = !isRunning && !presenter.downloadQueue.isEmpty()
}
// Set pause button visibility.
pauseButton = menu.findItem(R.id.pause_queue).apply {
isVisible = isRunning
}
// Set clear button visibility.
clearButton = menu.findItem(R.id.clear_queue).apply {
if (!presenter.downloadQueue.isEmpty()) {
isVisible = true
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.start_queue -> DownloadService.start(activity)
R.id.pause_queue -> DownloadService.stop(activity)
R.id.clear_queue -> {
DownloadService.stop(activity)
presenter.clearQueue()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
/**
* Called when the status of a download changes.
*
* @param download the download whose status has changed.
*/
private fun onStatusChange(download: Download) {
when (download.status) {
Download.DOWNLOADING -> {
observeProgress(download)
// Initial update of the downloaded pages
onUpdateDownloadedPages(download)
}
Download.DOWNLOADED -> {
unsubscribeProgress(download)
onUpdateProgress(download)
onUpdateDownloadedPages(download)
}
Download.ERROR -> unsubscribeProgress(download)
}
}
/**
* Observe the progress of a download and notify the view.
*
* @param download the download to observe its progress.
*/
private fun observeProgress(download: Download) {
val subscription = Observable.interval(50, TimeUnit.MILLISECONDS)
// Get the sum of percentages for all the pages.
.flatMap {
Observable.from(download.pages)
.map { it.progress }
.reduce { x, y -> x + y }
}
// Keep only the latest emission to avoid backpressure.
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { progress ->
// Update the view only if the progress has changed.
if (download.totalProgress != progress) {
download.totalProgress = progress
onUpdateProgress(download)
}
}
// Avoid leaking subscriptions
progressSubscriptions.remove(download)?.unsubscribe()
progressSubscriptions.put(download, subscription)
}
/**
* Unsubscribes the given download from the progress subscriptions.
*
* @param download the download to unsubscribe.
*/
private fun unsubscribeProgress(download: Download) {
progressSubscriptions.remove(download)?.unsubscribe()
}
/**
* Called when the queue's status has changed. Updates the visibility of the buttons.
*
* @param running whether the queue is now running or not.
*/
private fun onQueueStatusChange(running: Boolean) {
isRunning = running
startButton?.isVisible = !running && !presenter.downloadQueue.isEmpty()
pauseButton?.isVisible = running
clearButton?.isVisible = !presenter.downloadQueue.isEmpty()
// Check if download queue is empty and update information accordingly.
setInformationView()
}
/**
* Called from the presenter to assign the downloads for the adapter.
*
* @param downloads the downloads from the queue.
*/
fun onNextDownloads(downloads: List<Download>) {
adapter.setItems(downloads)
}
fun onDownloadRemoved(position: Int) {
adapter.notifyItemRemoved(position)
}
/**
* Called when the progress of a download changes.
*
* @param download the download whose progress has changed.
*/
fun onUpdateProgress(download: Download) {
getHolder(download)?.notifyProgress()
}
/**
* Called when a page of a download is downloaded.
*
* @param download the download whose page has been downloaded.
*/
fun onUpdateDownloadedPages(download: Download) {
getHolder(download)?.notifyDownloadedPages()
}
/**
* Returns the holder for the given download.
*
* @param download the download to find.
* @return the holder of the download or null if it's not bound.
*/
private fun getHolder(download: Download): DownloadHolder? {
return recycler.findViewHolderForItemId(download.chapter.id!!) as? DownloadHolder
}
/**
* Set information view when queue is empty
*/
private fun setInformationView() {
(activity as MainActivity).updateEmptyView(presenter.downloadQueue.isEmpty(),
R.string.information_no_downloads, R.drawable.ic_file_download_black_128dp)
}
}
| gpl-3.0 | 16f7cfcf529438f177429f7aa2793539 | 31.528777 | 107 | 0.631981 | 5.263679 | false | false | false | false |
WeAthFoLD/Momentum | Runtime/src/main/kotlin/momentum/rt/resource/ResourceManager.kt | 1 | 2812 | package momentum.rt.resource
import java.io.InputStream
import java.io.Reader
import java.util.*
import kotlin.reflect.KClass
interface ResourceLoader {
/**
* Returns a character stream corresponding for resource in this path
* @throws ResourceNotFoundException if there is no resource in this path
*/
fun load(path: String): InputStream
}
class ResourceManager {
companion object {
fun makePath(path: String, sub: String): String {
// TODO: Ensure this is correct
if (sub.startsWith("/")) {
return sub
} else if (sub.isEmpty()) {
return path
} else if (path == "/") {
return sub
} else {
var pre = path
if (!pre.endsWith("/")) {
pre += "/"
}
return pre + sub
}
}
fun getFolder(path: String): String {
val idx = path.lastIndexOf('/')
return if (idx == -1) "/" else path.substring(0, idx)
}
}
enum class CacheOption {
Cache, NotCache
}
private data class AssetKey(val path: String, val type: KClass<*>)
private val loaders = ArrayList<ResourceLoader>()
private val cachedResources = HashMap<AssetKey, Any>()
fun registerLoader(loader: ResourceLoader) {
loaders.add(loader)
}
fun getStream(path: String): InputStream {
for (loader in loaders) {
try {
return loader.load(path)
} catch (e: ResourceNotFoundException) {
// not found for this loader, skip
}
}
throw ResourceNotFoundException(path)
}
inline fun<reified T: Any> load(path: String, cacheOption: CacheOption = CacheOption.Cache): T {
return load(T::class, path, cacheOption)
}
fun <T: Any> load(type: KClass<T>, path: String, cacheOption: CacheOption = CacheOption.Cache): T {
val key = AssetKey(path, type)
if (cachedResources.containsKey(key)) {
@Suppress("UNCHECKED_CAST")
return cachedResources[key] as T
} else {
val stream = getStream(path)
if (type == InputStream::class) {
@Suppress("UNCHECKED_CAST")
return stream as T
}
try {
val asset = AssetManager.load(this, type, path, stream)
if (cacheOption == CacheOption.Cache) {
cachedResources.put(key, asset as Any)
}
return asset
} finally {
stream.close()
}
}
}
}
class ResourceNotFoundException(path: String) : RuntimeException("Resource $path not found.") | mit | a5cf83253e89b84a91d6d3cc00eb1a15 | 26.31068 | 103 | 0.538051 | 4.848276 | false | false | false | false |
vhromada/Catalog | web/src/test/kotlin/com/github/vhromada/catalog/web/utils/MusicUtils.kt | 1 | 2638 | package com.github.vhromada.catalog.web.utils
import com.github.vhromada.catalog.web.connector.entity.ChangeMusicRequest
import com.github.vhromada.catalog.web.connector.entity.Music
import com.github.vhromada.catalog.web.fo.MusicFO
import org.assertj.core.api.SoftAssertions.assertSoftly
/**
* A class represents utility class for music.
*
* @author Vladimir Hromada
*/
object MusicUtils {
/**
* Returns FO for music.
*
* @return FO for music
*/
fun getMusicFO(): MusicFO {
return MusicFO(
uuid = TestConstants.UUID,
name = TestConstants.NAME,
wikiEn = TestConstants.EN_WIKI,
wikiCz = TestConstants.CZ_WIKI,
mediaCount = TestConstants.MEDIA.toString(),
note = TestConstants.NOTE
)
}
/**
* Returns music.
*
* @return music
*/
fun getMusic(): Music {
return Music(
uuid = TestConstants.UUID,
name = TestConstants.NAME,
wikiEn = TestConstants.EN_WIKI,
wikiCz = TestConstants.CZ_WIKI,
mediaCount = TestConstants.MEDIA,
note = TestConstants.NOTE,
songsCount = 1,
length = TestConstants.LENGTH,
formattedLength = TestConstants.FORMATTED_LENGTH
)
}
/**
* Asserts music deep equals.
*
* @param expected expected music
* @param actual actual FO for music
*/
fun assertMusicDeepEquals(expected: Music, actual: MusicFO) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount.toString())
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts FO for music and request deep equals.
*
* @param expected expected FO for music
* @param actual actual request for changing music
*/
fun assertRequestDeepEquals(expected: MusicFO, actual: ChangeMusicRequest) {
assertSoftly {
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount!!.toInt())
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
}
| mit | 1574bf2ef34693a6d082de234dd0b3a2 | 30.783133 | 86 | 0.627369 | 4.669027 | false | true | false | false |
apollographql/apollo-android | apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/AndroidAndKotlinPluginFacade.kt | 1 | 798 | package com.apollographql.apollo3.gradle.internal
import com.android.build.gradle.api.AndroidSourceSet
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.HasConvention
// Copied from kotlin plugin
private fun Any.getConvention(name: String): Any? =
(this as HasConvention).convention.plugins[name]
// Copied from kotlin plugin
internal fun AndroidSourceSet.kotlinSourceSet(): SourceDirectorySet? {
val convention = (getConvention("kotlin") ?: getConvention("kotlin2js")) ?: return null
val kotlinSourceSet = convention.javaClass.interfaces.find { it.name == "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet" }
val getKotlin = kotlinSourceSet?.methods?.find { it.name == "getKotlin" } ?: return null
return getKotlin(convention) as? SourceDirectorySet
}
| mit | 54ea4b046d689707a93f2c57f706e298 | 43.333333 | 128 | 0.784461 | 4.290323 | false | false | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothGattCharacteristic.kt | 3 | 18299 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.os.Build
import android.os.Bundle
import android.bluetooth.BluetoothGattCharacteristic as FwkBluetoothGattCharacteristic
import android.annotation.SuppressLint
import androidx.annotation.RequiresApi
import java.util.UUID
/**
* @hide
*/
class BluetoothGattCharacteristic internal constructor(
fwkCharacteristic: FwkBluetoothGattCharacteristic
) : Bundleable {
companion object {
/**
* Characteristic value format type float (32-bit float)
*/
const val FORMAT_FLOAT = FwkBluetoothGattCharacteristic.FORMAT_FLOAT
/**
* Characteristic value format type sfloat (16-bit float)
*/
const val FORMAT_SFLOAT = FwkBluetoothGattCharacteristic.FORMAT_SFLOAT
/**
* Characteristic value format type uint16
*/
const val FORMAT_SINT16 = FwkBluetoothGattCharacteristic.FORMAT_SINT16
/**
* Characteristic value format type sint32
*/
const val FORMAT_SINT32 = FwkBluetoothGattCharacteristic.FORMAT_SINT32
/**
* Characteristic value format type sint8
*/
const val FORMAT_SINT8 = FwkBluetoothGattCharacteristic.FORMAT_SINT8
/**
* Characteristic value format type uint16
*/
const val FORMAT_UINT16 = FwkBluetoothGattCharacteristic.FORMAT_UINT16
/**
* Characteristic value format type uint32
*/
const val FORMAT_UINT32 = FwkBluetoothGattCharacteristic.FORMAT_UINT32
/**
* Characteristic value format type uint8
*/
const val FORMAT_UINT8 = FwkBluetoothGattCharacteristic.FORMAT_UINT8
/**
* Characteristic property: Characteristic is broadcastable.
*/
const val PROPERTY_BROADCAST =
FwkBluetoothGattCharacteristic.PROPERTY_BROADCAST
/**
* Characteristic property: Characteristic is readable.
*/
const val PROPERTY_READ = FwkBluetoothGattCharacteristic.PROPERTY_READ
/**
* Characteristic property: Characteristic can be written without response.
*/
const val PROPERTY_WRITE_NO_RESPONSE =
FwkBluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
/**
* Characteristic property: Characteristic can be written.
*/
const val PROPERTY_WRITE = FwkBluetoothGattCharacteristic.PROPERTY_WRITE
/**
* Characteristic property: Characteristic supports notification
*/
const val PROPERTY_NOTIFY = FwkBluetoothGattCharacteristic.PROPERTY_NOTIFY
/**
* Characteristic property: Characteristic supports indication
*/
const val PROPERTY_INDICATE =
FwkBluetoothGattCharacteristic.PROPERTY_BROADCAST
/**
* Characteristic property: Characteristic supports write with signature
*/
const val PROPERTY_SIGNED_WRITE =
FwkBluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE
/**
* Characteristic property: Characteristic has extended properties
*/
const val PROPERTY_EXTENDED_PROPS =
FwkBluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS
/**
* Characteristic read permission
*/
const val PERMISSION_READ = FwkBluetoothGattCharacteristic.PERMISSION_READ
/**
* Characteristic permission: Allow encrypted read operations
*/
const val PERMISSION_READ_ENCRYPTED =
FwkBluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED
/**
* Characteristic permission: Allow reading with person-in-the-middle protection
*/
const val PERMISSION_READ_ENCRYPTED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM
/**
* Characteristic write permission
*/
const val PERMISSION_WRITE = FwkBluetoothGattCharacteristic.PERMISSION_WRITE
/**
* Characteristic permission: Allow encrypted writes
*/
const val PERMISSION_WRITE_ENCRYPTED =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED
/**
* Characteristic permission: Allow encrypted writes with person-in-the-middle protection
*/
const val PERMISSION_WRITE_ENCRYPTED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM
/**
* Characteristic permission: Allow signed write operations
*/
const val PERMISSION_WRITE_SIGNED =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED
/**
* Characteristic permission: Allow signed write operations with
* person-in-the-middle protection
*/
const val PERMISSION_WRITE_SIGNED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM
/**
* Write characteristic, requesting acknowledgement by the remote device
*/
const val WRITE_TYPE_DEFAULT =
FwkBluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
/**
* Write characteristic without requiring a response by the remote device
*/
const val WRITE_TYPE_NO_RESPONSE =
FwkBluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
/**
* Write characteristic including authentication signature
*/
const val WRITE_TYPE_SIGNED =
FwkBluetoothGattCharacteristic.WRITE_TYPE_SIGNED
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
/**
* A companion object to create [BluetoothGattCharacteristic] from bundle
*/
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
if (Build.VERSION.SDK_INT >= 24) {
GattCharacteristicImplApi24.CREATOR
} else {
GattCharacteristicImplApi21.CREATOR
}
}
/**
* Implementation based on version
*/
private val impl: GattCharacteristicImpl =
if (Build.VERSION.SDK_INT >= 24) {
GattCharacteristicImplApi24(fwkCharacteristic, this)
} else {
GattCharacteristicImplApi21(fwkCharacteristic, this)
}
/**
* Underlying framework's [android.bluetooth.BluetoothGattCharacteristic]
*/
internal val fwkCharacteristic
get() = impl.fwkCharacteristic
/**
* the UUID of this characteristic.
*/
val uuid
get() = impl.uuid
/**
* Characteristic properties
*/
val properties
get() = impl.properties
/**
* Write type for this characteristic.
*/
val permissions
get() = impl.permissions
/**
* Write type for this characteristic.
*/
val instanceId
get() = impl.instanceId
/**
* Write type for this characteristic.
*/
var writeType: Int
get() = impl.writeType
set(value) {
impl.writeType = value
}
/**
* Library's [BluetoothGattDescriptor] list that this characteristic owns
*/
val descriptors: List<BluetoothGattDescriptor>
get() = impl.descriptors
/**
* Library's [BluetoothGattService] that this belongs to
*/
var service: BluetoothGattService?
get() = impl.service
internal set(value) {
impl.service = value
}
/**
* Create a new BluetoothGattCharacteristic.
*
* @param uuid The UUID for this characteristic
* @param properties Properties of this characteristic
* @param permissions Permissions for this characteristic
*/
constructor (uuid: UUID, properties: Int, permissions: Int) : this(
FwkBluetoothGattCharacteristic(uuid, properties, permissions)
)
/**
* Adds a descriptor to this characteristic.
*
* @param descriptor Descriptor to be added to this characteristic.
* @return true, if the descriptor was added to the characteristic
*/
fun addDescriptor(descriptor: BluetoothGattDescriptor): Boolean {
return impl.addDescriptor(descriptor)
}
/**
* Get a descriptor by UUID
*/
fun getDescriptor(uuid: UUID): BluetoothGattDescriptor? {
return impl.getDescriptor(uuid)
}
/**
* Create a [Bundle] from this object
*/
override fun toBundle(): Bundle {
return impl.toBundle()
}
private interface GattCharacteristicImpl : Bundleable {
val fwkCharacteristic: FwkBluetoothGattCharacteristic
val uuid: UUID
val properties: Int
val permissions: Int
val instanceId: Int
var writeType: Int
val descriptors: List<BluetoothGattDescriptor>
var service: BluetoothGattService?
fun addDescriptor(descriptor: BluetoothGattDescriptor): Boolean
fun getDescriptor(uuid: UUID): BluetoothGattDescriptor?
override fun toBundle(): Bundle
}
private open class GattCharacteristicImplApi21(
final override val fwkCharacteristic: FwkBluetoothGattCharacteristic,
private val characteristic: BluetoothGattCharacteristic,
) : GattCharacteristicImpl {
companion object {
internal const val FIELD_FWK_CHARACTERISTIC_UUID = 1
internal const val FIELD_FWK_CHARACTERISTIC_INSTANCE_ID = 2
internal const val FIELD_FWK_CHARACTERISTIC_PROPERTIES = 3
internal const val FIELD_FWK_CHARACTERISTIC_PERMISSIONS = 4
internal const val FIELD_FWK_CHARACTERISTIC_WRITE_TYPE = 5
internal const val FIELD_FWK_CHARACTERISTIC_KEY_SIZE = 6
internal const val FIELD_FWK_CHARACTERISTIC_DESCRIPTORS = 7
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
object : Bundleable.Creator<BluetoothGattCharacteristic> {
@SuppressLint("SoonBlockedPrivateApi")
override fun fromBundle(bundle: Bundle): BluetoothGattCharacteristic {
val uuid = bundle.getString(keyForField(FIELD_FWK_CHARACTERISTIC_UUID))
?: throw IllegalArgumentException("Bundle doesn't include uuid")
val instanceId =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_INSTANCE_ID), 0)
val properties =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_PROPERTIES), -1)
val permissions =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_PERMISSIONS), -1)
val writeType =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_WRITE_TYPE), -1)
val keySize =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_KEY_SIZE), -1)
if (permissions == -1) {
throw IllegalArgumentException("Bundle doesn't include permission")
}
if (properties == -1) {
throw IllegalArgumentException("Bundle doesn't include properties")
}
if (writeType == -1) {
throw IllegalArgumentException("Bundle doesn't include writeType")
}
if (keySize == -1) {
throw IllegalArgumentException("Bundle doesn't include keySize")
}
val fwkCharacteristicWithoutPrivateField = FwkBluetoothGattCharacteristic(
UUID.fromString(uuid),
properties,
permissions,
)
val fwkCharacteristic = fwkCharacteristicWithoutPrivateField.runCatching {
this.writeType = writeType
this.javaClass.getDeclaredField("mKeySize").let {
it.isAccessible = true
it.setInt(this, keySize)
}
this.javaClass.getDeclaredField("mInstanceId").let {
it.isAccessible = true
it.setInt(this, instanceId)
}
this
}.getOrDefault(fwkCharacteristicWithoutPrivateField)
val gattCharacteristic = BluetoothGattCharacteristic(fwkCharacteristic)
Utils.getParcelableArrayListFromBundle(
bundle,
keyForField(FIELD_FWK_CHARACTERISTIC_DESCRIPTORS),
Bundle::class.java
).forEach {
gattCharacteristic.addDescriptor(
BluetoothGattDescriptor.CREATOR.fromBundle(it)
)
}
return gattCharacteristic
}
}
}
override val uuid: UUID
get() = fwkCharacteristic.uuid
override val properties
get() = fwkCharacteristic.properties
override val permissions
get() = fwkCharacteristic.permissions
override val instanceId
get() = fwkCharacteristic.instanceId
override var writeType: Int
get() = fwkCharacteristic.writeType
set(value) {
fwkCharacteristic.writeType = value
}
private var _descriptors = mutableListOf<BluetoothGattDescriptor>()
override val descriptors
get() = _descriptors.toList()
override var service: BluetoothGattService? = null
init {
fwkCharacteristic.descriptors.forEach {
val descriptor = BluetoothGattDescriptor(it)
_descriptors.add(descriptor)
descriptor.characteristic = characteristic
}
}
override fun addDescriptor(
descriptor: BluetoothGattDescriptor,
): Boolean {
return if (fwkCharacteristic.addDescriptor(descriptor.fwkDescriptor)) {
_descriptors.add(descriptor)
descriptor.characteristic = characteristic
true
} else {
false
}
}
override fun getDescriptor(uuid: UUID): BluetoothGattDescriptor? {
return _descriptors.firstOrNull {
it.uuid == uuid
}
}
override fun toBundle(): Bundle {
assert(Build.VERSION.SDK_INT < 24)
val bundle = Bundle()
bundle.putString(keyForField(FIELD_FWK_CHARACTERISTIC_UUID), uuid.toString())
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_INSTANCE_ID), instanceId)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_PROPERTIES), properties)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_PERMISSIONS), permissions)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_WRITE_TYPE), writeType)
// Asserted, this will always work
if (Build.VERSION.SDK_INT < 24) {
bundle.putInt(
keyForField(FIELD_FWK_CHARACTERISTIC_KEY_SIZE),
fwkCharacteristic.javaClass.getDeclaredField("mKeySize").runCatching {
this.isAccessible = true
this.getInt(fwkCharacteristic)
}.getOrDefault(16) // 16 is the default value in framework
)
}
val descriptorBundles = ArrayList(descriptors.map { it.toBundle() })
bundle.putParcelableArrayList(
keyForField(FIELD_FWK_CHARACTERISTIC_DESCRIPTORS),
descriptorBundles
)
return bundle
}
}
@RequiresApi(Build.VERSION_CODES.N)
private class GattCharacteristicImplApi24(
fwkCharacteristic: FwkBluetoothGattCharacteristic,
characteristic: BluetoothGattCharacteristic,
) : GattCharacteristicImplApi21(fwkCharacteristic, characteristic) {
companion object {
internal const val FIELD_FWK_CHARACTERISTIC = 0
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
object : Bundleable.Creator<BluetoothGattCharacteristic> {
@Suppress("deprecation")
override fun fromBundle(bundle: Bundle): BluetoothGattCharacteristic {
val fwkCharacteristic =
Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_CHARACTERISTIC),
FwkBluetoothGattCharacteristic::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include framework characteristic"
)
return BluetoothGattCharacteristic(fwkCharacteristic)
}
}
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(
keyForField(FIELD_FWK_CHARACTERISTIC),
fwkCharacteristic
)
return bundle
}
}
}
| apache-2.0 | dd971d5f3600684d0a01f2d14fe969f0 | 37.687104 | 98 | 0.594022 | 6.320898 | false | false | false | false |
androidx/androidx | compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/tasks/IconSourceTasks.kt | 3 | 6554 | /*
* 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.material.icons.generator.tasks
import androidx.compose.material.icons.generator.CoreIcons
import androidx.compose.material.icons.generator.IconWriter
import org.gradle.api.Project
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Jar
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import java.io.File
/**
* Task responsible for converting core icons from xml to a programmatic representation.
*/
@CacheableTask
open class CoreIconGenerationTask : IconGenerationTask() {
override fun run() =
IconWriter(loadIcons()).generateTo(generatedSrcMainDirectory) { it in CoreIcons }
companion object {
/**
* Registers [CoreIconGenerationTask] in [project].
*/
@Suppress("DEPRECATION") // BaseVariant
fun register(project: Project, variant: com.android.build.gradle.api.BaseVariant? = null) {
val (task, buildDirectory) = project.registerGenerationTask(
"generateCoreIcons",
CoreIconGenerationTask::class.java,
variant
)
// Multiplatform
if (variant == null) {
registerIconGenerationTask(project, task, buildDirectory)
}
// AGP
else variant.registerIconGenerationTask(project, task, buildDirectory)
}
}
}
/**
* Task responsible for converting extended icons from xml to a programmatic representation.
*/
@CacheableTask
open class ExtendedIconGenerationTask : IconGenerationTask() {
override fun run() =
IconWriter(loadIcons()).generateTo(generatedSrcMainDirectory) { it !in CoreIcons }
companion object {
/**
* Registers [ExtendedIconGenerationTask] in [project]. (for use with mpp)
*/
@Suppress("DEPRECATION") // BaseVariant
fun register(project: Project, variant: com.android.build.gradle.api.BaseVariant? = null) {
val (task, buildDirectory) = project.registerGenerationTask(
"generateExtendedIcons",
ExtendedIconGenerationTask::class.java,
variant
)
// Multiplatform
if (variant == null) {
registerIconGenerationTask(project, task, buildDirectory)
}
// AGP
else variant.registerIconGenerationTask(project, task, buildDirectory)
}
/**
* Registers the icon generation task just for source jar generation, and not for
* compilation. This is temporarily needed since we manually parallelize compilation in
* material-icons-extended for the AGP build. When we remove that parallelization code,
* we can remove this too.
*/
@JvmStatic
@Suppress("DEPRECATION") // BaseVariant
fun registerSourceJarOnly(
project: Project,
variant: com.android.build.gradle.api.BaseVariant
) {
// Setup the source jar task if this is the release variant
if (variant.name == "release") {
val (task, buildDirectory) = project.registerGenerationTask(
"generateExtendedIcons",
ExtendedIconGenerationTask::class.java,
variant
)
val generatedSrcMainDirectory = buildDirectory.resolve(GeneratedSrcMain)
project.addToSourceJar(generatedSrcMainDirectory, task)
}
}
}
}
/**
* Helper to register [task] that outputs to [buildDirectory] as the Kotlin source generating
* task for [project].
*/
private fun registerIconGenerationTask(
project: Project,
task: TaskProvider<*>,
buildDirectory: File
) {
val sourceSet = project.getMultiplatformSourceSet(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME)
val generatedSrcMainDirectory = buildDirectory.resolve(IconGenerationTask.GeneratedSrcMain)
sourceSet.kotlin.srcDir(project.files(generatedSrcMainDirectory).builtBy(task))
// add it to the multiplatform sources as well.
project.tasks.named("multiplatformSourceJar", Jar::class.java).configure {
it.from(task.map { generatedSrcMainDirectory })
}
project.addToSourceJar(generatedSrcMainDirectory, task)
}
/**
* Helper to register [task] as the java source generating task that outputs to [buildDirectory].
*/
@Suppress("DEPRECATION") // BaseVariant
private fun com.android.build.gradle.api.BaseVariant.registerIconGenerationTask(
project: Project,
task: TaskProvider<*>,
buildDirectory: File
) {
val generatedSrcMainDirectory = buildDirectory.resolve(IconGenerationTask.GeneratedSrcMain)
registerJavaGeneratingTask(task, generatedSrcMainDirectory)
// Setup the source jar task if this is the release variant
if (name == "release") {
project.addToSourceJar(generatedSrcMainDirectory, task)
}
}
/**
* Adds the contents of [buildDirectory] to the source jar generated for this [Project] by [task]
*/
// TODO: b/191485164 remove when AGP lets us get generated sources from a TestedExtension or
// similar, then we can just add generated sources in SourceJarTaskHelper for all projects,
// instead of needing one-off support here.
private fun Project.addToSourceJar(buildDirectory: File, task: TaskProvider<*>) {
afterEvaluate {
val sourceJar = tasks.named("sourceJarRelease", Jar::class.java)
sourceJar.configure {
// Generating source jars requires the generation task to run first. This shouldn't
// be needed for the MPP build because we use builtBy to set up the dependency
// (https://github.com/gradle/gradle/issues/17250) but the path is different for AGP,
// so we will still need this for the AGP build.
it.dependsOn(task)
it.from(buildDirectory)
}
}
}
| apache-2.0 | 39bc6fc5925c793d4c7d6f04f1c768e4 | 38.963415 | 99 | 0.677754 | 4.968916 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/CodeVisionListData.kt | 4 | 2089 | package com.intellij.codeInsight.codeVision.ui.model
import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.map
import com.jetbrains.rd.util.throttleLast
import java.time.Duration
class CodeVisionListData(
val lifetime: Lifetime,
val projectModel: ProjectCodeVisionModel,
val rangeCodeVisionModel: RangeCodeVisionModel,
val inlay: Inlay<*>,
val anchoredLens: List<CodeVisionEntry>,
val anchor: CodeVisionAnchorKind
) {
companion object {
@JvmField
val KEY: Key<CodeVisionListData> = Key.create<CodeVisionListData>("CodeVisionListData")
}
var isPainted: Boolean = false
get() = field
set(value) {
if (field != value) {
field = value
if ((inlay.editor as? EditorImpl)?.isPurePaintingMode != true)
inlay.update()
}
}
val visibleLens: ArrayList<CodeVisionEntry> = ArrayList<CodeVisionEntry>()
private var throttle = false
init {
projectModel.hoveredInlay.map {
it == inlay
}.throttleLast(Duration.ofMillis(300), SwingScheduler).advise(lifetime) {
throttle = it
inlay.repaint()
}
updateVisible()
}
private fun updateVisible() {
val count = projectModel.maxVisibleLensCount[anchor]
visibleLens.clear()
if (count == null) {
visibleLens.addAll(anchoredLens)
return
}
val visibleCount = minOf(count, anchoredLens.size)
visibleLens.addAll(anchoredLens.subList(0, visibleCount))
}
fun state(): RangeCodeVisionModel.InlayState = rangeCodeVisionModel.state()
fun isMoreLensActive(): Boolean = throttle && Registry.`is`("editor.codeVision.more.inlay")
fun isHoveredEntry(entry: CodeVisionEntry): Boolean = projectModel.hoveredEntry.value == entry && projectModel.hoveredInlay.value == inlay
}
| apache-2.0 | 91c57d40ccb6ce5f7a2fb0cb5d80856d | 28.842857 | 140 | 0.736237 | 4.343035 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/customization/ActionIconInfo.kt | 2 | 3852 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui.customization
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionStubBase
import com.intellij.openapi.util.IconLoader
import com.intellij.util.text.nullize
import org.jetbrains.annotations.Nls
import java.io.IOException
import javax.swing.Icon
internal val NONE = ActionIconInfo(null, IdeBundle.message("default.icons.none.text"), "", null)
internal val SEPARATOR = ActionIconInfo(null, "", "", null)
/**
* @param actionId id of the action that use this icon.
* @param iconPath path or URL of the icon.
* @param text template presentation text of the action or file name.
*/
internal class ActionIconInfo(val icon: Icon?,
@Nls val text: String,
val actionId: String?,
val iconPath: String?) {
val iconReference: String
get() = iconPath ?: actionId ?: error("Either actionId or iconPath should be set")
override fun toString(): String {
return text
}
}
internal fun getDefaultIcons(): List<ActionIconInfo> {
val icons = listOf(
getIconInfo(AllIcons.Toolbar.Unknown, IdeBundle.message("default.icons.unknown.text")),
getIconInfo(AllIcons.General.Add, IdeBundle.message("default.icons.add.text")),
getIconInfo(AllIcons.General.Remove, IdeBundle.message("default.icons.remove.text")),
getIconInfo(AllIcons.Actions.Edit, IdeBundle.message("default.icons.edit.text")),
getIconInfo(AllIcons.General.Filter, IdeBundle.message("default.icons.filter.text")),
getIconInfo(AllIcons.Actions.Find, IdeBundle.message("default.icons.find.text")),
getIconInfo(AllIcons.General.GearPlain, IdeBundle.message("default.icons.gear.plain.text")),
getIconInfo(AllIcons.Actions.ListFiles, IdeBundle.message("default.icons.list.files.text")),
getIconInfo(AllIcons.ToolbarDecorator.Export, IdeBundle.message("default.icons.export.text")),
getIconInfo(AllIcons.ToolbarDecorator.Import, IdeBundle.message("default.icons.import.text"))
)
return icons.filterNotNull()
}
private fun getIconInfo(icon: Icon, @Nls text: String): ActionIconInfo? {
val iconUrl = (icon as? IconLoader.CachedImageIcon)?.url
return iconUrl?.let { ActionIconInfo(icon, text, null, it.toString()) }
}
internal fun getAvailableIcons(): List<ActionIconInfo> {
val actionManager = ActionManager.getInstance()
return actionManager.getActionIdList("").mapNotNull { actionId ->
val action = actionManager.getActionOrStub(actionId) ?: return@mapNotNull null
val icon = if (action is ActionStubBase) {
val path = action.iconPath ?: return@mapNotNull null
IconLoader.findIcon(path, action.plugin.classLoader)
}
else {
val presentation = action.templatePresentation
presentation.getClientProperty(CustomActionsSchema.PROP_ORIGINAL_ICON) ?: presentation.icon
}
icon?.let { ActionIconInfo(it, action.templateText.nullize() ?: actionId, actionId, null) }
}
}
internal fun getCustomIcons(schema: CustomActionsSchema): List<ActionIconInfo> {
val actionManager = ActionManager.getInstance()
return schema.iconCustomizations.mapNotNull { (actionId, iconReference) ->
if (actionId == null || iconReference == null) return@mapNotNull null
val action = actionManager.getAction(iconReference)
if (action == null) {
val icon = try {
CustomActionsSchema.loadCustomIcon(iconReference)
}
catch (ex: IOException) {
null
}
if (icon != null) {
ActionIconInfo(icon, iconReference.substringAfterLast("/"), actionId, iconReference)
}
else null
}
else null
}
} | apache-2.0 | 8a539cd19e16b922f5df36790963cf84 | 41.811111 | 120 | 0.724818 | 4.473868 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/formatter/trailingComma/typeParameters/TypeParameterList.call.after.kt | 16 | 3736 | class A1<
x : String,
y : String,
>
class F<x : String, y : String>
class F2<
x : String,
y
: String,
>
class B1<
x : String,
y : String,
>
class C1<
x : String,
y : String,
>
class D1<
x : String,
y : String,
>
class A2<
x : String,
y : String,
z : String,
>
class B2<
x : String,
y : String,
z : String,
>
class C2<
x : String,
y : String,
z : String,
>
class D2<
x : String,
y : String,
z : String,
>
class A3<
x : String,
>
class B3<
x : String,
>
class C3<
x : String,
>
class D3<
x : String,
>
class A4<
x : String,
y : String,
z,
>
class B4<
x : String,
y,
z : String,
>
class C4<
x : String,
y : String,
z : String,
>
class D4<
x : String,
y,
z : String,
>
class E1<
x, y : String,
z : String,
>
class E2<
x : String, y : String, z : String,
>
class C<
z : String, v,
>
fun <
x : String,
y : String,
> a1() = Unit
fun <
x : String,
y : String,
> b1() = Unit
fun <
x : String,
y : String,
> c1() = Unit
fun <
x : String,
y : String,
> d1() = Unit
fun <
x : String,
y : String,
z : String,
> a2() = Unit
fun <
x : String,
y : String,
z : String,
> b2() = Unit
fun <
x : String,
y : String,
z : String,
> c2() = Unit
fun <
x : String,
y : String,
z : String,
> d2() = Unit
fun <
x : String,
> a3() = Unit
fun <
x : String,
> b3() = Unit
fun <
x : String,
> c3() = Unit
fun <
x : String,
> d3() = Unit
fun <
x : String,
y : String,
z : String,
> a4() = Unit
fun <
x : String,
y : String,
z : String,
> b4() = Unit
fun <
x : String,
y : String,
z : String,
> c4() = Unit
fun <
x : String,
y : String,
z : String,
> d4() = Unit
fun <
x,
> foo() {
}
fun <T> ag() {
}
fun <T> ag() {
}
fun <
T,
> ag() {
}
class C<
x : Int,
>
class G<
x : String, y : String,
/* */ z : String,
>
class G<
x : String, y : String,
/* */ /* */ z : String,
>()
class H<
x : String,
/*
*/
y : String,
z : String,
>
class J<
x : String, y : String, z : String,
/*
*/
>
class K<
x : String, y : String,
z : String,
>
class L<
x : String, y : String, z : String,
>
class C<
x : Int, // adad
>
class G<
x : String, y : String,
/* */ z : String, // adad
>
class G<
x : String, y : String,
/* */ /* */ z : String, /**/
>()
class H<
x : String,
/*
*/
y : String,
z : String,
/*
*/
>
class J<
x : String, y : String, z : String,
/*
*/
/**/
>
class K<
x : String, y : String,
z : String, // aw
>
class L<
x : String, y : String, z : String, //awd
>
// SET_TRUE: ALLOW_TRAILING_COMMA
| apache-2.0 | fee76fcb41021c29d0e5a23dee8d53cd | 12.017422 | 49 | 0.335653 | 3.303271 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/SwitcherActions.kt | 2 | 8889 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.Switcher.SwitcherPanel
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.util.BitUtil.isSet
import com.intellij.util.ui.accessibility.ScreenReader
import java.awt.event.*
import java.util.function.Consumer
import javax.swing.AbstractAction
import javax.swing.JList
import javax.swing.KeyStroke
private fun forward(event: AnActionEvent) = true != event.inputEvent?.isShiftDown
internal class ShowSwitcherForwardAction : BaseSwitcherAction(true)
internal class ShowSwitcherBackwardAction : BaseSwitcherAction(false)
internal abstract class BaseSwitcherAction(val forward: Boolean?) : DumbAwareAction() {
private fun isControlTab(event: KeyEvent?) = event?.run { isControlDown && keyCode == KeyEvent.VK_TAB } ?: false
private fun isControlTabDisabled(event: AnActionEvent) = ScreenReader.isActive() && isControlTab(event.inputEvent as? KeyEvent)
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = event.project != null && !isControlTabDisabled(event)
event.presentation.isVisible = forward == null
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
val switcher = Switcher.SWITCHER_KEY.get(project)
if (switcher != null && (!switcher.recent || forward != null)) {
switcher.go(forward ?: forward(event))
}
else {
FeatureUsageTracker.getInstance().triggerFeatureUsed("switcher")
SwitcherPanel(project, message("window.title.switcher"), event.inputEvent, null, forward ?: forward(event))
}
}
}
internal class ShowRecentFilesAction : LightEditCompatible, BaseRecentFilesAction(false)
internal class ShowRecentlyEditedFilesAction : BaseRecentFilesAction(true)
internal abstract class BaseRecentFilesAction(private val onlyEditedFiles: Boolean) : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = event.project != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
Switcher.SWITCHER_KEY.get(project)?.cbShowOnlyEditedFiles?.apply { isSelected = !isSelected }
?: SwitcherPanel(project, message("title.popup.recent.files"), null, onlyEditedFiles, true)
}
}
internal class SwitcherIterateThroughItemsAction : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = Switcher.SWITCHER_KEY.get(event.project) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(event: AnActionEvent) {
Switcher.SWITCHER_KEY.get(event.project)?.go(forward(event))
}
}
internal class SwitcherToggleOnlyEditedFilesAction : DumbAwareToggleAction() {
private fun getCheckBox(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.cbShowOnlyEditedFiles
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getCheckBox(event) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun isSelected(event: AnActionEvent) = getCheckBox(event)?.isSelected ?: false
override fun setSelected(event: AnActionEvent, selected: Boolean) {
getCheckBox(event)?.isSelected = selected
}
}
internal class SwitcherNextProblemAction : SwitcherProblemAction(true)
internal class SwitcherPreviousProblemAction : SwitcherProblemAction(false)
internal abstract class SwitcherProblemAction(val forward: Boolean) : DumbAwareAction() {
private fun getFileList(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.let { if (it.pinned) it.files else null }
private fun getErrorIndex(list: JList<SwitcherVirtualFile>): Int? {
val model = list.model ?: return null
val size = model.size
if (size <= 0) return null
val range = 0 until size
val start = when (forward) {
true -> list.leadSelectionIndex.let { if (range.first <= it && it < range.last) it + 1 else range.first }
else -> list.leadSelectionIndex.let { if (range.first < it && it <= range.last) it - 1 else range.last }
}
for (i in range) {
val index = when (forward) {
true -> (start + i).let { if (it > range.last) it - size else it }
else -> (start - i).let { if (it < range.first) it + size else it }
}
if (model.getElementAt(index)?.isProblemFile == true) return index
}
return null
}
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getFileList(event) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(event: AnActionEvent) {
val list = getFileList(event) ?: return
val index = getErrorIndex(list) ?: return
list.selectedIndex = index
list.ensureIndexIsVisible(index)
}
}
internal class SwitcherListFocusAction(val fromList: JList<*>, val toList: JList<*>, vararg listActionIds: String)
: FocusListener, AbstractAction() {
override fun actionPerformed(event: ActionEvent) {
if (toList.isShowing) toList.requestFocusInWindow()
}
override fun focusLost(event: FocusEvent) = Unit
override fun focusGained(event: FocusEvent) {
val size = toList.model.size
if (size > 0) {
val fromIndex = fromList.selectedIndex
when {
fromIndex >= 0 -> toIndex = fromIndex.coerceAtMost(size - 1)
toIndex < 0 -> toIndex = 0
}
}
}
private var toIndex: Int
get() = toList.selectedIndex
set(index) {
fromList.clearSelection()
toList.selectedIndex = index
toList.ensureIndexIsVisible(index)
}
init {
listActionIds.forEach { fromList.actionMap.put(it, this) }
toList.addFocusListener(this)
toList.addListSelectionListener {
if (!fromList.isSelectionEmpty && !toList.isSelectionEmpty) {
fromList.selectionModel.clearSelection()
}
}
}
}
internal class SwitcherKeyReleaseListener(event: InputEvent?, val consumer: Consumer<InputEvent>) : KeyAdapter() {
private val wasAltDown = true == event?.isAltDown
private val wasAltGraphDown = true == event?.isAltGraphDown
private val wasControlDown = true == event?.isControlDown
private val wasMetaDown = true == event?.isMetaDown
val isEnabled = wasAltDown || wasAltGraphDown || wasControlDown || wasMetaDown
private val initialModifiers = if (!isEnabled) null
else StringBuilder().apply {
if (wasAltDown) append("alt ")
if (wasAltGraphDown) append("altGraph ")
if (wasControlDown) append("control ")
if (wasMetaDown) append("meta ")
}.toString()
val forbiddenMnemonic = (event as? KeyEvent)?.keyCode?.let { getMnemonic(it) }
fun getForbiddenMnemonic(keyStroke: KeyStroke) = when {
isSet(keyStroke.modifiers, InputEvent.ALT_DOWN_MASK) != wasAltDown -> null
isSet(keyStroke.modifiers, InputEvent.ALT_GRAPH_DOWN_MASK) != wasAltGraphDown -> null
isSet(keyStroke.modifiers, InputEvent.CTRL_DOWN_MASK) != wasControlDown -> null
isSet(keyStroke.modifiers, InputEvent.META_DOWN_MASK) != wasMetaDown -> null
else -> getMnemonic(keyStroke.keyCode)
}
private fun getMnemonic(keyCode: Int) = when (keyCode) {
in KeyEvent.VK_0..KeyEvent.VK_9 -> keyCode.toChar().toString()
in KeyEvent.VK_A..KeyEvent.VK_Z -> keyCode.toChar().toString()
else -> null
}
fun getShortcuts(vararg keys: String): CustomShortcutSet {
val modifiers = initialModifiers ?: return CustomShortcutSet.fromString(*keys)
val list = mutableListOf<String>()
keys.mapTo(list) { modifiers + it }
keys.mapTo(list) { modifiers + "shift " + it }
return CustomShortcutSet.fromStrings(list)
}
override fun keyReleased(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ALT -> if (wasAltDown) consumer.accept(keyEvent)
KeyEvent.VK_ALT_GRAPH -> if (wasAltGraphDown) consumer.accept(keyEvent)
KeyEvent.VK_CONTROL -> if (wasControlDown) consumer.accept(keyEvent)
KeyEvent.VK_META -> if (wasMetaDown) consumer.accept(keyEvent)
}
}
}
| apache-2.0 | 01f11b6333161a50e5b4bacb8b462ef9 | 37.314655 | 158 | 0.734841 | 4.46011 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/code-insight-common/src/org/jetbrains/kotlin/idea/gradleCodeInsightCommon/SettingsScriptBuilder.kt | 2 | 3236 | // 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.gradleCodeInsightCommon
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
abstract class SettingsScriptBuilder<T: PsiFile>(private val scriptFile: T) {
private val builder = StringBuilder(scriptFile.text)
private fun findBlockBody(blockName: String, startFrom: Int = 0): Int {
val blockOffset = builder.indexOf(blockName, startFrom)
if (blockOffset < 0) return -1
return builder.indexOf('{', blockOffset + 1) + 1
}
private fun getOrPrependTopLevelBlockBody(blockName: String): Int {
val blockBody = findBlockBody(blockName)
if (blockBody >= 0) return blockBody
builder.insert(0, "$blockName {}\n")
return findBlockBody(blockName)
}
private fun getOrAppendInnerBlockBody(blockName: String, offset: Int): Int {
val repositoriesBody = findBlockBody(blockName, offset)
if (repositoriesBody >= 0) return repositoriesBody
builder.insert(offset, "\n$blockName {}\n")
return findBlockBody(blockName, offset)
}
private fun appendExpressionToBlockIfAbsent(expression: String, offset: Int) {
var braceCount = 1
var blockEnd = offset
for (i in offset..builder.lastIndex) {
when (builder[i]) {
'{' -> braceCount++
'}' -> braceCount--
}
if (braceCount == 0) {
blockEnd = i
break
}
}
if (!builder.substring(offset, blockEnd).contains(expression.trim())) {
builder.insert(blockEnd, "\n$expression\n")
}
}
private fun getOrCreatePluginManagementBody() = getOrPrependTopLevelBlockBody("pluginManagement")
protected fun addPluginRepositoryExpression(expression: String) {
val repositoriesBody = getOrAppendInnerBlockBody("repositories", getOrCreatePluginManagementBody())
appendExpressionToBlockIfAbsent(expression, repositoriesBody)
}
fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
abstract fun addPluginRepository(repository: RepositoryDescription)
fun addResolutionStrategy(pluginId: String) {
val resolutionStrategyBody = getOrAppendInnerBlockBody("resolutionStrategy", getOrCreatePluginManagementBody())
val eachPluginBody = getOrAppendInnerBlockBody("eachPlugin", resolutionStrategyBody)
appendExpressionToBlockIfAbsent(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent(),
eachPluginBody
)
}
fun addIncludedModules(modules: List<String>) {
builder.append(modules.joinToString(prefix = "include ", postfix = "\n") { "'$it'" })
}
fun build() = builder.toString()
abstract fun buildPsiFile(project: Project): T
}
| apache-2.0 | 46ad827343840a94cc59da5dd0537f2f | 38.463415 | 158 | 0.665019 | 5.375415 | false | false | false | false |
mr-max/anko | preview/attrs/src/org/jetbrains/kotlin/android/Attrs.kt | 2 | 1392 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.attrs
import java.io.File
public data class NameValue(
val name: String = "",
val value: String = "")
public data class Attr(
val name: String = "",
val format: List<String> = listOf(),
val flags: List<NameValue>? = null,
val enum: List<NameValue>? = null)
public val NoAttr: Attr = Attr()
public data class Styleable(
val name: String = "",
val attrs: List<Attr> = listOf())
public data class Attrs(
val free: List<Attr> = listOf(),
val styleables: Map<String, Styleable> = mapOf())
public fun readResource(filename: String): String {
return Attrs::class.java.classLoader.getResourceAsStream(filename)?.reader()?.readText()
?: File(filename).readText()
} | apache-2.0 | f8b19e59245ef9a49652feedcbf6d1aa | 30.659091 | 92 | 0.677443 | 4.082111 | false | false | false | false |
adobe/S3Mock | integration-tests/src/test/kotlin/com/adobe/testing/s3mock/its/ObjectTaggingV2IT.kt | 1 | 3739 | /*
* Copyright 2017-2022 Adobe.
*
* 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.adobe.testing.s3mock.its
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInfo
import software.amazon.awssdk.core.sync.RequestBody
import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest
import software.amazon.awssdk.services.s3.model.PutObjectRequest
import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest
import software.amazon.awssdk.services.s3.model.Tag
import software.amazon.awssdk.services.s3.model.Tagging
internal class ObjectTaggingV2IT : S3TestBase() {
@Test
fun testGetObjectTagging_noTags(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key("foo") },
RequestBody.fromString("foo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("foo")
}
.tagSet())
.isEmpty()
}
@Test
fun testPutAndGetObjectTagging(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
val key = "foo"
val tag1 = Tag.builder().key("tag1").value("foo").build()
val tag2 = Tag.builder().key("tag2").value("bar").build()
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key(key) },
RequestBody.fromString("foo")
)
s3ClientV2.putObjectTagging(
PutObjectTaggingRequest.builder().bucket(bucketName).key(key)
.tagging(Tagging.builder().tagSet(tag1, tag2).build()).build()
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key(key)
}
.tagSet())
.contains(
tag1,
tag2
)
}
@Test
fun testPutObjectAndGetObjectTagging_withTagging(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key("foo").tagging("msv=foo") },
RequestBody.fromString("foo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("foo")
}
.tagSet())
.contains(Tag.builder().key("msv").value("foo").build())
}
/**
* Verify that tagging with multiple tags can be obtained and returns expected content.
*/
@Test
fun testPutObjectAndGetObjectTagging_multipleTags(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
val tag1 = Tag.builder().key("tag1").value("foo").build()
val tag2 = Tag.builder().key("tag2").value("bar").build()
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder ->
b.bucket(bucketName).key("multipleFoo")
.tagging(Tagging.builder().tagSet(tag1, tag2).build())
}, RequestBody.fromString("multipleFoo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("multipleFoo")
}
.tagSet())
.contains(
tag1,
tag2
)
}
}
| apache-2.0 | 72cdfa7e85a344e53794e55d3b50fb6f | 30.420168 | 92 | 0.681733 | 3.948258 | false | true | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/util/components/SnackbarComponent.kt | 1 | 660 | package sk.styk.martin.apkanalyzer.util.components
import android.view.View
import com.google.android.material.snackbar.Snackbar
import sk.styk.martin.apkanalyzer.util.TextInfo
data class SnackBarComponent(val message: TextInfo, val duration: Int = Snackbar.LENGTH_LONG,
val action: TextInfo? = null, val callback: View.OnClickListener? = null)
fun SnackBarComponent.toSnackbar(seekFromView: View) : Snackbar {
val snack = Snackbar.make(seekFromView, message.getText(seekFromView.context), duration)
if (action != null) {
snack.setAction(action.getText(seekFromView.context), callback)
}
return snack
}
| gpl-3.0 | 5ee2a06b84f6d309355096464c34a9d1 | 37.823529 | 102 | 0.737879 | 4.074074 | false | false | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/util/NotificationCreator.kt | 1 | 5723 | package com.mapzen.erasermap.util
import android.app.Activity
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.SharedPreferences
import android.os.IBinder
import android.preference.PreferenceManager
import android.support.v4.app.NotificationCompat
import android.support.v4.app.TaskStackBuilder
import com.mapzen.erasermap.R
import com.mapzen.erasermap.service.NotificationService
import com.mapzen.erasermap.controller.MainActivity
class NotificationCreator(private val mainActivity: Activity) {
private var builder: NotificationCompat.Builder? = null
private var bigTextStyle: NotificationCompat.BigTextStyle? = null
private var stackBuilder: TaskStackBuilder? = null
private var notificationIntent: Intent? = null
private var exitNavigationIntent: Intent? = null
private var pendingNotificationIntent: PendingIntent? = null
private var pendingExitNavigationIntent: PendingIntent? = null
private val notificationManager: NotificationManager
private val serviceConnection: NotificationServiceConnection
private val preferences: SharedPreferences
private val serviceIntent: Intent
companion object {
const val EXIT_NAVIGATION = "exit_navigation"
const val NOTIFICATION_TAG_ROUTE = "route"
}
init {
notificationManager = mainActivity.getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
serviceConnection = NotificationServiceConnection(mainActivity)
preferences = PreferenceManager.getDefaultSharedPreferences(mainActivity)
serviceIntent = Intent(mainActivity, NotificationService::class.java)
}
/**
* All notifications created through this class should be killed using the
* {@link NotificationCreator#killNotification()}, do not call
* {@link NotificationManager#cancelAll()} directly
*
* Before we create a notification, we bind to a stub service so that when app is killed
* {@link MainActivity#onDestroy} is reliably called. This triggers a
* call to {@link NotificationCreator#killNotification} which removes notification from manager
*/
fun createNewNotification(title: String, content: String) {
initBuilder(title, content)
initBigTextStyle(title, content)
builder?.setStyle(bigTextStyle)
initNotificationIntent()
initExitNavigationIntent()
initStackBuilder(notificationIntent)
builder?.addAction(R.drawable.ic_dismiss, mainActivity.getString(R.string.exit_navigation),
pendingExitNavigationIntent)
builder?.setContentIntent(PendingIntent.getActivity(
mainActivity.applicationContext, 0, notificationIntent, 0))
mainActivity.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
notificationManager.notify(NOTIFICATION_TAG_ROUTE, 0, builder!!.build())
}
private fun initExitNavigationIntent() {
exitNavigationIntent = Intent(mainActivity, NotificationBroadcastReceiver::class.java)
exitNavigationIntent?.putExtra(EXIT_NAVIGATION, true)
pendingExitNavigationIntent = PendingIntent.getBroadcast(
mainActivity, 0, exitNavigationIntent, PendingIntent.FLAG_CANCEL_CURRENT)
}
private fun initNotificationIntent() {
notificationIntent = Intent(mainActivity, MainActivity::class.java)
notificationIntent?.setAction(Intent.ACTION_MAIN)
notificationIntent?.addCategory(Intent.CATEGORY_LAUNCHER)
notificationIntent?.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
pendingNotificationIntent = PendingIntent.getActivity(
mainActivity, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun initStackBuilder(intent: Intent?) {
stackBuilder = TaskStackBuilder.create(mainActivity)
stackBuilder?.addParentStack(mainActivity.javaClass)
stackBuilder?.addNextIntent(intent)
}
private fun initBigTextStyle(title: String, content: String) {
bigTextStyle = NotificationCompat.BigTextStyle()
bigTextStyle?.setBigContentTitle(title)
bigTextStyle?.bigText(content)
}
private fun initBuilder(title: String, content: String) {
builder = NotificationCompat.Builder(mainActivity.baseContext)
builder?.setContentTitle(title)
builder?.setContentText(content)
builder?.setSmallIcon(R.drawable.ic_notif)
builder?.setPriority(NotificationCompat.PRIORITY_MAX)
builder?.setOngoing(true)
}
fun killNotification() {
notificationManager.cancelAll()
serviceConnection.service?.stopService(serviceIntent)
}
/**
* In charge of starting the stub service we bind to
*/
private class NotificationServiceConnection: ServiceConnection {
val activity: Activity
var service: NotificationService? = null
constructor(activity: Activity) {
this.activity = activity
}
override fun onServiceConnected(component: ComponentName?, inBinder: IBinder?) {
if (inBinder == null) {
return
}
val binder = inBinder as NotificationService.NotificationBinder
val intent: Intent = Intent(activity, NotificationService::class.java)
this.service = binder.service
binder.service.startService(intent)
}
override fun onServiceDisconnected(component: ComponentName?) {
}
}
}
| gpl-3.0 | 0e1030f3d4678ed25eb741fd87160bc1 | 40.773723 | 103 | 0.728639 | 5.599804 | false | false | false | false |
duftler/clouddriver | clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/events.kt | 1 | 5166 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.saga
import com.fasterxml.jackson.annotation.JsonTypeName
import com.netflix.spinnaker.clouddriver.event.AbstractSpinnakerEvent
import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent
import com.netflix.spinnaker.clouddriver.saga.models.Saga
import com.netflix.spinnaker.kork.exceptions.SpinnakerException
/**
* Root event type for [Saga]s.
*/
interface SagaEvent : SpinnakerEvent
/**
* Warning: Do not use with Lombok @Value classes.
*/
abstract class AbstractSagaEvent : AbstractSpinnakerEvent(), SagaEvent
/**
* Emitted whenever a [Saga] is saved.
*
* This event does not attempt to find a difference in state, trading off persistence verbosity for a little bit
* of a simpler implementation.
*
* @param sequence The [Saga]'s latest sequence
*/
@JsonTypeName("sagaSaved")
class SagaSaved(
val sequence: Long
) : AbstractSagaEvent()
/**
* Emitted whenever an internal error has occurred while applying a [Saga].
*
* @param reason A human-readable cause for the error
* @param error The Exception (if any) that caused the error condition
* @param retryable Flags whether or not this error is recoverable
* @param data Additional data that can help with diagnostics of the error
*/
@JsonTypeName("sagaInternalErrorOccurred")
class SagaInternalErrorOccurred(
val reason: String,
val error: Exception? = null,
val retryable: Boolean = true,
val data: Map<String, String> = mapOf()
) : AbstractSagaEvent()
/**
* Emitted whenever an error has occurred within a [SagaAction] while applying a [Saga].
*
* @param actionName The Java simpleName of the handler
* @param error The Exception that caused the error condition
* @param retryable Flags whether or not this error is recoverable
*/
@JsonTypeName("sagaActionErrorOccurred")
class SagaActionErrorOccurred(
val actionName: String,
val error: Exception,
val retryable: Boolean
) : AbstractSagaEvent()
/**
* Informational log that can be added to a [Saga] for end-user feedback, as well as operational insight.
* This is a direct tie-in for the Kato Task Status concept with some additional bells and whistles.
*
* @param message A tuple message that allows passing end-user- and operator-focused messages
* @param diagnostics Additional metadata that can help provide context to the message
*/
@JsonTypeName("sagaLogAppended")
class SagaLogAppended(
val message: Message,
val diagnostics: Diagnostics? = null
) : AbstractSagaEvent() {
/**
* @param user An end-user friendly message
* @param system An operator friendly message
*/
data class Message(
val user: String? = null,
val system: String? = null
)
/**
* @param error An error, if one exists. This must be a [SpinnakerException] to provide retryable metadata
* @param data Additional metadata
*/
data class Diagnostics(
val error: SpinnakerException? = null,
val data: Map<String, String> = mapOf()
)
}
/**
* Emitted when all actions for a [Saga] have been applied.
*/
@JsonTypeName("sagaCompleted")
class SagaCompleted(
val success: Boolean
) : AbstractSagaEvent()
/**
* Emitted when a [Saga] enters a rollback state.
*/
@JsonTypeName("sagaRollbackStarted")
class SagaRollbackStarted : AbstractSagaEvent()
/**
* Emitted when all rollback actions for a [Saga] have been applied.
*/
@JsonTypeName("sagaRollbackCompleted")
class SagaRollbackCompleted : AbstractSagaEvent()
/**
* The root event type for all mutating [Saga] operations.
*/
interface SagaCommand : SagaEvent
/**
* The root event type for all [Saga] rollback operations.
*/
interface SagaRollbackCommand : SagaCommand
/**
* Marker event for recording that the work associated with a particular [SagaCommand] event has been completed.
*
* @param command The [SagaCommand] name
*/
@JsonTypeName("sagaCommandCompleted")
class SagaCommandCompleted(
val command: String
) : AbstractSagaEvent() {
fun matches(candidateCommand: Class<out SagaCommand>): Boolean =
candidateCommand.getAnnotation(JsonTypeName::class.java)?.value == command
}
/**
* A [SagaCommand] wrapper for [SagaAction]s that need to return more than one [SagaCommand].
*
* This event is unwrapped prior to being added to the event log; so all [SagaCommand]s defined within this
* wrapper will show up as their own distinct log entries.
*/
@JsonTypeName("sagaManyCommandsWrapper")
class ManyCommands(
command1: SagaCommand,
vararg extraCommands: SagaCommand
) : AbstractSagaEvent(), SagaCommand {
val commands = listOf(command1).plus(extraCommands)
}
| apache-2.0 | 3c3b93c95caeff962bb9f89aa5a261f5 | 30.309091 | 112 | 0.747967 | 4.323013 | false | false | false | false |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/MainActivityUI.kt | 1 | 7426 | package net.ketc.numeri.presentation.view.activity.ui
import android.content.Context
import android.graphics.Color
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.NavigationView
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.View
import android.view.ViewManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import net.ketc.numeri.R
import net.ketc.numeri.presentation.view.activity.MainActivity
import net.ketc.numeri.util.android.getResourceId
import net.ketc.numeri.util.android.startOf
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.design.navigationView
import org.jetbrains.anko.support.v4.drawerLayout
class MainActivityUI : IMainActivityUI {
override lateinit var drawer: DrawerLayout
private set
override lateinit var navigation: NavigationView
private set
override lateinit var showAccountIndicator: ImageView
private set
override lateinit var navigationContent: RelativeLayout
private set
override lateinit var showAccountRelative: RelativeLayout
private set
override lateinit var addAccountButton: RelativeLayout
private set
override lateinit var accountsLinear: LinearLayout
private set
override lateinit var columnGroupWrapper: CoordinatorLayout
private set
override lateinit var toolbar: Toolbar
private set
override lateinit var tweetButton: FloatingActionButton
private set
override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
drawerLayout {
drawer = this
id = R.id.drawer
coordinatorLayout {
appBarLayout {
toolbar {
id = R.id.toolbar
toolbar = this
}.lparams(matchParent, wrapContent) {
scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or
AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
}
}.lparams(matchParent, wrapContent)
coordinatorLayout {
columnGroupWrapper = this
id = R.id.column_group_wrapper_coordinator
}.lparams(matchParent, matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
floatingActionButton {
tweetButton = this
image = ctx.getDrawable(R.drawable.ic_mode_edit_white_24dp)
size = FloatingActionButton.SIZE_AUTO
}.lparams {
margin = dimen(R.dimen.margin_medium)
anchorGravity = Gravity.BOTTOM or Gravity.END
anchorId = R.id.column_group_wrapper_coordinator
}
}
navigationView {
id = R.id.navigation
navigation = this
inflateMenu(R.menu.main_navigation)
addHeaderView(navigationHeader(ctx))
navigationContent()
}.lparams(wrapContent, matchParent) {
gravity = Gravity.START
}
}
}
private fun navigationHeader(ctx: Context) = ctx.relativeLayout {
lparams(matchParent, dip(160))
backgroundColor = Color.parseColor("#10505050")
imageView {
id = R.id.icon_image
image = ctx.getDrawable(R.mipmap.ic_launcher)
}.lparams(dimen(R.dimen.image_icon_large), dimen(R.dimen.image_icon_large)) {
topMargin = dimen(R.dimen.margin_medium)
marginStart = dimen(R.dimen.margin_medium)
}
relativeLayout {
showAccountRelative = this
id = R.id.show_account_relative
lparams(matchParent, dip(72)) {
alignParentBottom()
}
relativeLayout {
lparams {
alignParentBottom()
bottomMargin = dimen(R.dimen.margin_small)
}
backgroundResource = ctx.getResourceId(android.R.attr.selectableItemBackground)
textView {
id = R.id.user_name_text
text = "アカウント一覧"
lines = 1
}.lparams {
startOf(R.id.show_account_indicator)
alignParentStart()
centerVertically()
margin = dimen(R.dimen.margin_text_medium)
}
imageView {
showAccountIndicator = this
id = R.id.show_account_indicator
image = ctx.getDrawable(R.drawable.ic_expand_more_white_24dp)
backgroundColor = ctx.getColor(R.color.transparent)
scaleType = ImageView.ScaleType.CENTER_INSIDE
}.lparams(dip(16), dip(16)) {
alignParentEnd()
centerVertically()
marginEnd = dimen(R.dimen.margin_text_medium)
}
}
}
}
private fun ViewManager.navigationContent() = relativeLayout {
id = R.id.navigation_content
navigationContent = this
visibility = View.GONE
topPadding = dip(168)
lparams(matchParent, matchParent)
relativeLayout {
lparams(matchParent, matchParent)
linearLayout {
accountsLinear = this
id = R.id.accounts_linear
lparams(matchParent, wrapContent) {
backgroundColor = context.getColor(R.color.transparent)
}
orientation = LinearLayout.VERTICAL
}
relativeLayout {
addAccountButton = this
id = R.id.add_account_button
lparams(matchParent, dip(48)) {
below(R.id.accounts_linear)
}
backgroundResource = context.getResourceId(android.R.attr.selectableItemBackground)
isClickable = true
textView {
text = context.getString(R.string.add_account)
lines = 1
}.lparams(matchParent, wrapContent) {
centerVertically()
marginStart = dimen(R.dimen.margin_medium)
marginEnd = dimen(R.dimen.margin_medium)
}
}
}
}
}
interface IMainActivityUI : AnkoComponent<MainActivity> {
val toolbar: Toolbar
val drawer: DrawerLayout
val navigation: NavigationView
val showAccountIndicator: ImageView
val navigationContent: RelativeLayout
val showAccountRelative: RelativeLayout
val addAccountButton: RelativeLayout
val accountsLinear: LinearLayout
val columnGroupWrapper: CoordinatorLayout
val tweetButton: FloatingActionButton
} | mit | c8d29bf448d8fb8c32b9bf5bf448e4d0 | 37.21134 | 99 | 0.595656 | 5.482249 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/settings/LibGDXPluginConfigurable.kt | 1 | 2681 | package com.gmail.blueboxware.libgdxplugin.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.intellij.ui.EditorNotifications
import javax.swing.JComponent
/*
* Copyright 2016 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@State(name = "LibGDXPluginConfigurable")
class LibGDXPluginConfigurable(val project: Project) : Configurable {
private var form: LibGDXPluginSettingsPane? = null
override fun isModified() = getForm()?.isModified == true
override fun disposeUIResources() {
form = null
}
override fun getDisplayName() = "LibGDXPlugin"
override fun apply() {
getForm()?.apply()
EditorNotifications.getInstance(project).updateAllNotifications()
}
override fun createComponent(): JComponent? {
val settings = project.getService(LibGDXPluginSettings::class.java)
return getForm()?.createPanel(project, settings)
}
override fun reset() {
getForm()?.reset()
}
override fun getHelpTopic(): String? = null
private fun getForm(): LibGDXPluginSettingsPane? {
if (form == null) {
form = LibGDXPluginSettingsPane()
}
return form
}
}
@State(name = "LibGDXPluginSettings")
class LibGDXPluginSettings : PersistentStateComponent<LibGDXPluginSettings> {
var enableColorAnnotations: Boolean = true
var enableColorAnnotationsInJson: Boolean = true
var enableColorAnnotationsInSkin: Boolean = true
var neverAskAboutSkinFiles: Boolean = false
var neverAskAboutJsonFiles: Boolean = false
override fun loadState(state: LibGDXPluginSettings) {
enableColorAnnotations = state.enableColorAnnotations
enableColorAnnotationsInJson = state.enableColorAnnotationsInJson
enableColorAnnotationsInSkin = state.enableColorAnnotationsInSkin
neverAskAboutSkinFiles = state.neverAskAboutSkinFiles
neverAskAboutJsonFiles = state.neverAskAboutJsonFiles
}
override fun getState() = this
}
| apache-2.0 | 73bf02d2e4fa24714975a07242868f7e | 31.695122 | 77 | 0.736665 | 5.020599 | false | false | false | false |
erubit-open/platform | erubit.platform/src/main/java/a/erubit/platform/course/Progress.kt | 1 | 501 | package a.erubit.platform.course
import a.erubit.platform.R
import android.content.Context
abstract class Progress {
var nextInteractionDate: Long = 0
var interactionDate: Long = 0
var trainDate: Long = 0
var familiarity = 0
var progress = 0
open fun getExplanation(context: Context): String {
val r = context.resources
return when (interactionDate) {
0L -> r.getString(R.string.unopened)
else -> r.getString(
R.string.progress_explanation,
progress, familiarity)
}
}
}
| gpl-3.0 | 2e2b97aa94507710c94f944301e5c8a8 | 20.782609 | 52 | 0.726547 | 3.253247 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/ResidualProgramCompiler.kt | 3 | 27425 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.api.Project
import org.gradle.api.internal.file.temp.TemporaryFileProvider
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.hash.HashCode
import org.gradle.internal.hash.Hashing
import org.gradle.kotlin.dsl.execution.ResidualProgram.Dynamic
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction
import org.gradle.kotlin.dsl.execution.ResidualProgram.Static
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildScript
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildscriptAndPluginsBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinInitScript
import org.gradle.kotlin.dsl.support.CompiledKotlinInitscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinPluginsBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsBuildscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsPluginManagementBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsScript
import org.gradle.kotlin.dsl.support.ImplicitReceiver
import org.gradle.kotlin.dsl.support.KotlinScriptHost
import org.gradle.kotlin.dsl.support.bytecode.ALOAD
import org.gradle.kotlin.dsl.support.bytecode.ARETURN
import org.gradle.kotlin.dsl.support.bytecode.ASTORE
import org.gradle.kotlin.dsl.support.bytecode.CHECKCAST
import org.gradle.kotlin.dsl.support.bytecode.DUP
import org.gradle.kotlin.dsl.support.bytecode.GETSTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEINTERFACE
import org.gradle.kotlin.dsl.support.bytecode.INVOKESPECIAL
import org.gradle.kotlin.dsl.support.bytecode.INVOKESTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEVIRTUAL
import org.gradle.kotlin.dsl.support.bytecode.InternalName
import org.gradle.kotlin.dsl.support.bytecode.LDC
import org.gradle.kotlin.dsl.support.bytecode.NEW
import org.gradle.kotlin.dsl.support.bytecode.RETURN
import org.gradle.kotlin.dsl.support.bytecode.TRY_CATCH
import org.gradle.kotlin.dsl.support.bytecode.internalName
import org.gradle.kotlin.dsl.support.bytecode.loadByteArray
import org.gradle.kotlin.dsl.support.bytecode.publicClass
import org.gradle.kotlin.dsl.support.bytecode.publicDefaultConstructor
import org.gradle.kotlin.dsl.support.bytecode.publicMethod
import org.gradle.kotlin.dsl.support.compileKotlinScriptToDirectory
import org.gradle.kotlin.dsl.support.messageCollectorFor
import org.gradle.kotlin.dsl.support.scriptDefinitionFromTemplate
import org.gradle.plugin.management.internal.MultiPluginRequests
import org.gradle.plugin.use.internal.PluginRequestCollector
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.ClassWriter
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Type
import org.slf4j.Logger
import java.io.File
import kotlin.reflect.KClass
import kotlin.script.experimental.api.KotlinType
internal
typealias CompileBuildOperationRunner = (String, String, () -> String) -> String
/**
* Compiles the given [residual program][ResidualProgram] to an [ExecutableProgram] subclass named `Program`
* stored in the given [outputDir].
*/
internal
class ResidualProgramCompiler(
private val outputDir: File,
private val classPath: ClassPath = ClassPath.EMPTY,
private val originalSourceHash: HashCode,
private val programKind: ProgramKind,
private val programTarget: ProgramTarget,
private val implicitImports: List<String> = emptyList(),
private val logger: Logger = interpreterLogger,
private val temporaryFileProvider: TemporaryFileProvider,
private val compileBuildOperationRunner: CompileBuildOperationRunner = { _, _, action -> action() },
private val pluginAccessorsClassPath: ClassPath = ClassPath.EMPTY,
private val packageName: String? = null,
private val injectedProperties: Map<String, KotlinType> = mapOf()
) {
fun compile(program: ResidualProgram) = when (program) {
is Static -> emitStaticProgram(program)
is Dynamic -> emitDynamicProgram(program)
}
private
fun emitStaticProgram(program: Static) {
program<ExecutableProgram> {
overrideExecute {
emit(program.instructions)
}
}
}
private
fun emitDynamicProgram(program: Dynamic) {
program<ExecutableProgram.StagedProgram> {
overrideExecute {
emit(program.prelude.instructions)
emitEvaluateSecondStageOf()
}
overrideGetSecondStageScriptText(program.source.text)
overrideLoadSecondStageFor()
}
}
private
fun ClassWriter.overrideGetSecondStageScriptText(secondStageScriptText: String) {
publicMethod(
"getSecondStageScriptText",
"()Ljava/lang/String;",
"()Ljava/lang/String;"
) {
if (mightBeLargerThan64KB(secondStageScriptText)) {
// Large scripts are stored as a resource to overcome
// the 64KB string constant limitation
val resourcePath = storeStringToResource(secondStageScriptText)
ALOAD(0)
LDC(resourcePath)
INVOKEVIRTUAL(
ExecutableProgram.StagedProgram::class.internalName,
ExecutableProgram.StagedProgram::loadScriptResource.name,
"(Ljava/lang/String;)Ljava/lang/String;"
)
} else {
LDC(secondStageScriptText)
}
ARETURN()
}
}
private
fun mightBeLargerThan64KB(secondStageScriptText: String) =
// We use a simple heuristic to avoid converting the string to bytes
// if all code points were in UTF32, 16K code points would require 64K bytes
secondStageScriptText.length >= 16 * 1024
private
fun storeStringToResource(secondStageScriptText: String): String {
val hash = Hashing.hashString(secondStageScriptText)
val resourcePath = "scripts/$hash.gradle.kts"
writeResourceFile(resourcePath, secondStageScriptText)
return resourcePath
}
private
fun writeResourceFile(resourcePath: String, resourceText: String) {
outputFile(resourcePath).apply {
parentFile.mkdir()
writeText(resourceText)
}
}
private
fun MethodVisitor.emit(instructions: List<Instruction>) {
instructions.forEach {
emit(it)
}
}
private
fun MethodVisitor.emit(instruction: Instruction) = when (instruction) {
is Instruction.SetupEmbeddedKotlin -> emitSetupEmbeddedKotlinFor()
is Instruction.CloseTargetScope -> emitCloseTargetScopeOf()
is Instruction.Eval -> emitEval(instruction.script)
is Instruction.ApplyBasePlugins -> emitApplyBasePluginsTo()
is Instruction.ApplyDefaultPluginRequests -> emitApplyEmptyPluginRequestsTo()
is Instruction.ApplyPluginRequestsOf -> {
val program = instruction.program
when (program) {
is Program.Plugins -> emitPrecompiledPluginsBlock(program)
is Program.PluginManagement -> emitStage1Sequence(program)
is Program.Stage1Sequence -> emitStage1Sequence(program.pluginManagement, program.buildscript, program.plugins)
else -> throw IllegalStateException("Expecting a residual program with plugins, got `$program'")
}
}
}
private
fun MethodVisitor.emitSetupEmbeddedKotlinFor() {
// programHost.setupEmbeddedKotlinFor(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("setupEmbeddedKotlinFor", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.emitEval(source: ProgramSource) {
val scriptDefinition = stage1ScriptDefinition
val precompiledScriptClass = compileStage1(source, scriptDefinition)
emitInstantiationOfPrecompiledScriptClass(precompiledScriptClass, scriptDefinition)
}
private
val Program.Stage1.fragment: ProgramSourceFragment
get() = when (this) {
is Program.Buildscript -> fragment
is Program.Plugins -> fragment
is Program.PluginManagement -> fragment
else -> TODO("Unsupported fragment: $fragment")
}
private
fun MethodVisitor.emitStage1Sequence(vararg stage1Seq: Program.Stage1?) {
emitStage1Sequence(listOfNotNull(*stage1Seq))
}
private
fun MethodVisitor.emitStage1Sequence(stage1Seq: List<Program.Stage1>) {
val scriptDefinition = buildscriptWithPluginsScriptDefinition
val plugins = stage1Seq.filterIsInstance<Program.Plugins>().singleOrNull()
val firstElement = stage1Seq.first()
val precompiledBuildscriptWithPluginsBlock =
compileStage1(
firstElement.fragment.source.map {
it.preserve(stage1Seq.map { stage1 -> stage1.fragment.range })
},
scriptDefinition,
pluginsBlockClassPath
)
val implicitReceiverType = implicitReceiverOf(scriptDefinition)!!
precompiledScriptClassInstantiation(precompiledBuildscriptWithPluginsBlock) {
emitPluginRequestCollectorInstantiation()
NEW(precompiledBuildscriptWithPluginsBlock)
ALOAD(Vars.ScriptHost)
// ${plugins}(temp.createSpec(lineNumber))
emitPluginRequestCollectorCreateSpecFor(plugins)
loadTargetOf(implicitReceiverType)
emitLoadExtensions()
INVOKESPECIAL(
precompiledBuildscriptWithPluginsBlock,
"<init>",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/use/PluginDependenciesSpec;L${implicitReceiverType.internalName};$injectedPropertiesDescriptors)V"
)
emitApplyPluginsTo()
}
}
/**
* programHost.applyPluginsTo(scriptHost, collector.getPluginRequests())
*/
private
fun MethodVisitor.emitApplyPluginsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
emitPluginRequestCollectorGetPluginRequests()
invokeApplyPluginsTo()
}
private
fun MethodVisitor.emitApplyBasePluginsTo() {
ALOAD(Vars.ProgramHost)
loadTargetOf(Project::class)
invokeHost(
"applyBasePluginsTo",
"(Lorg/gradle/api/Project;)V"
)
}
private
fun MethodVisitor.loadTargetOf(expectedType: KClass<*>) {
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getTarget",
"()Ljava/lang/Object;"
)
CHECKCAST(expectedType.internalName)
}
private
fun MethodVisitor.emitApplyEmptyPluginRequestsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
GETSTATIC(
MultiPluginRequests::class.internalName,
"EMPTY",
"Lorg/gradle/plugin/management/internal/PluginRequests;"
)
invokeApplyPluginsTo()
}
fun emitStage2ProgramFor(scriptFile: File, originalPath: String) {
val scriptDef = stage2ScriptDefinition
val precompiledScriptClass = compileScript(
scriptFile,
originalPath,
scriptDef,
StableDisplayNameFor.stage2
)
program<ExecutableProgram> {
overrideExecute {
emitInstantiationOfPrecompiledScriptClass(
precompiledScriptClass,
scriptDef
)
}
}
}
private
fun MethodVisitor.emitPrecompiledPluginsBlock(program: Program.Plugins) {
val precompiledPluginsBlock = compilePlugins(program)
precompiledScriptClassInstantiation(precompiledPluginsBlock) {
/*
* val collector = PluginRequestCollector(kotlinScriptHost.scriptSource)
*/
emitPluginRequestCollectorInstantiation()
// ${precompiledPluginsBlock}(collector.createSpec(lineNumber))
NEW(precompiledPluginsBlock)
emitPluginRequestCollectorCreateSpecFor(program)
emitLoadExtensions()
INVOKESPECIAL(
precompiledPluginsBlock,
"<init>",
"(Lorg/gradle/plugin/use/PluginDependenciesSpec;$injectedPropertiesDescriptors)V"
)
emitApplyPluginsTo()
}
}
private
val injectedPropertiesDescriptors
get() = injectedProperties.values
.map { Type.getType(it.fromClass?.java).descriptor }
.joinToString(separator = "")
/**
* extensions.getByName(name) as ExtensionType
*/
private
fun MethodVisitor.emitLoadExtension(name: String, type: KotlinType) {
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getTarget",
"()Ljava/lang/Object;"
)
CHECKCAST(ExtensionAware::class)
INVOKEINTERFACE(
ExtensionAware::class.internalName,
"getExtensions",
"()Lorg/gradle/api/plugins/ExtensionContainer;"
)
LDC(name)
INVOKEINTERFACE(
ExtensionContainer::class.internalName,
"getByName",
"(Ljava/lang/String;)Ljava/lang/Object;"
)
CHECKCAST(type.fromClass!!)
}
/**
* val collector = PluginRequestCollector(kotlinScriptHost.scriptSource)
*/
private
fun MethodVisitor.emitPluginRequestCollectorInstantiation() {
NEW(pluginRequestCollectorType)
DUP()
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getScriptSource",
"()Lorg/gradle/groovy/scripts/ScriptSource;"
)
INVOKESPECIAL(
pluginRequestCollectorType,
"<init>",
"(Lorg/gradle/groovy/scripts/ScriptSource;)V"
)
ASTORE(Vars.PluginRequestCollector)
}
private
fun MethodVisitor.emitPluginRequestCollectorGetPluginRequests() {
ALOAD(Vars.PluginRequestCollector)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"getPluginRequests",
"()Lorg/gradle/plugin/management/internal/PluginRequests;"
)
}
private
fun MethodVisitor.emitPluginRequestCollectorCreateSpecFor(plugins: Program.Plugins?) {
ALOAD(Vars.PluginRequestCollector)
LDC(plugins?.fragment?.lineNumber ?: 0)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"createSpec",
"(I)Lorg/gradle/plugin/use/PluginDependenciesSpec;"
)
}
private
val pluginRequestCollectorType = PluginRequestCollector::class.internalName
private
fun MethodVisitor.invokeApplyPluginsTo() {
invokeHost(
"applyPluginsTo",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/management/internal/PluginRequests;)V"
)
}
private
fun ClassWriter.overrideLoadSecondStageFor() {
publicMethod(
name = "loadSecondStageFor",
desc = loadSecondStageForDescriptor
) {
ALOAD(Vars.ProgramHost)
ALOAD(0)
ALOAD(Vars.ScriptHost)
ALOAD(3)
ALOAD(4)
GETSTATIC(programKind)
GETSTATIC(programTarget)
ALOAD(5)
invokeHost(
ExecutableProgram.Host::compileSecondStageOf.name,
compileSecondStageOfDescriptor
)
ARETURN()
}
}
private
fun MethodVisitor.emitEvaluateSecondStageOf() {
// programHost.evaluateSecondStageOf(...)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.Program)
ALOAD(Vars.ScriptHost)
LDC(programTarget.name + "/" + programKind.name + "/stage2")
// Move HashCode value to a static field so it's cached across invocations
loadHashCode(originalSourceHash)
if (requiresAccessors()) emitAccessorsClassPathForScriptHost() else GETSTATIC(ClassPath::EMPTY)
invokeHost(
ExecutableProgram.Host::evaluateSecondStageOf.name,
"(" +
stagedProgramType +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;" +
"Ljava/lang/String;" +
"Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")V"
)
}
private
val stagedProgram = Type.getType(ExecutableProgram.StagedProgram::class.java)
private
val stagedProgramType = stagedProgram.descriptor
private
val loadSecondStageForDescriptor = Type.getMethodDescriptor(
Type.getType(CompiledScript::class.java),
Type.getType(ExecutableProgram.Host::class.java),
Type.getType(KotlinScriptHost::class.java),
Type.getType(String::class.java),
Type.getType(HashCode::class.java),
Type.getType(ClassPath::class.java)
)
private
val compileSecondStageOfDescriptor = Type.getMethodDescriptor(
Type.getType(CompiledScript::class.java),
stagedProgram,
Type.getType(KotlinScriptHost::class.java),
Type.getType(String::class.java),
Type.getType(HashCode::class.java),
Type.getType(ProgramKind::class.java),
Type.getType(ProgramTarget::class.java),
Type.getType(ClassPath::class.java)
)
private
fun requiresAccessors() =
requiresAccessors(programTarget, programKind)
private
fun MethodVisitor.emitAccessorsClassPathForScriptHost() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost(
"accessorsClassPathFor",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)Lorg/gradle/internal/classpath/ClassPath;"
)
}
private
fun ClassVisitor.overrideExecute(methodBody: MethodVisitor.() -> Unit) {
publicMethod("execute", programHostToKotlinScriptHostToVoid, "(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost<*>;)V") {
methodBody()
RETURN()
}
}
private
fun compilePlugins(program: Program.Plugins) =
compileStage1(
program.fragment.source.map { it.preserve(program.fragment.range) },
pluginsScriptDefinition,
pluginsBlockClassPath
)
private
val pluginsBlockClassPath
get() = classPath + pluginAccessorsClassPath
private
fun MethodVisitor.loadHashCode(hashCode: HashCode) {
loadByteArray(hashCode.toByteArray())
INVOKESTATIC(
HashCode::class.internalName,
"fromBytes",
"([B)Lorg/gradle/internal/hash/HashCode;"
)
}
private
fun MethodVisitor.emitInstantiationOfPrecompiledScriptClass(
precompiledScriptClass: InternalName,
scriptDefinition: ScriptDefinition
) {
val implicitReceiverType = implicitReceiverOf(scriptDefinition)
precompiledScriptClassInstantiation(precompiledScriptClass) {
// ${precompiledScriptClass}(scriptHost)
NEW(precompiledScriptClass)
val constructorSignature =
if (implicitReceiverType != null) {
ALOAD(Vars.ScriptHost)
loadTargetOf(implicitReceiverType)
emitLoadExtensions()
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;L${implicitReceiverType.internalName};$injectedPropertiesDescriptors)V"
} else {
ALOAD(Vars.ScriptHost)
emitLoadExtensions()
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;$injectedPropertiesDescriptors)V"
}
INVOKESPECIAL(precompiledScriptClass, "<init>", constructorSignature)
}
}
private
fun MethodVisitor.emitLoadExtensions() {
injectedProperties.forEach { name, type ->
emitLoadExtension(name, type)
}
}
private
fun MethodVisitor.precompiledScriptClassInstantiation(precompiledScriptClass: InternalName, instantiation: MethodVisitor.() -> Unit) {
TRY_CATCH<Throwable>(
tryBlock = {
instantiation()
},
catchBlock = {
emitOnScriptException(precompiledScriptClass)
}
)
}
private
fun MethodVisitor.emitOnScriptException(precompiledScriptClass: InternalName) {
// Exception is on the stack
ASTORE(4)
ALOAD(Vars.ProgramHost)
ALOAD(4)
LDC(Type.getType("L$precompiledScriptClass;"))
ALOAD(Vars.ScriptHost)
invokeHost(
"handleScriptException",
"(Ljava/lang/Throwable;Ljava/lang/Class;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
)
}
private
fun MethodVisitor.emitCloseTargetScopeOf() {
// programHost.closeTargetScopeOf(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("closeTargetScopeOf", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.invokeHost(name: String, desc: String) {
INVOKEINTERFACE(ExecutableProgram.Host::class.internalName, name, desc)
}
private
object Vars {
const val Program = 0
const val ProgramHost = 1
const val ScriptHost = 2
// Only valid within the context of `overrideExecute`
const val PluginRequestCollector = 3
}
private
val programHostToKotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
val kotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
inline fun <reified T : ExecutableProgram> program(noinline classBody: ClassWriter.() -> Unit = {}) {
program(T::class.internalName, classBody)
}
private
fun program(superName: InternalName, classBody: ClassWriter.() -> Unit = {}) {
writeFile(
"Program.class",
publicClass(InternalName("Program"), superName, null) {
publicDefaultConstructor(superName)
classBody()
}
)
}
private
fun writeFile(relativePath: String, bytes: ByteArray) {
outputFile(relativePath).writeBytes(bytes)
}
private
fun outputFile(relativePath: String) =
outputDir.resolve(relativePath)
private
fun compileStage1(
source: ProgramSource,
scriptDefinition: ScriptDefinition,
compileClassPath: ClassPath = classPath
): InternalName =
temporaryFileProvider.withTemporaryScriptFileFor(source.path, source.text) { scriptFile ->
val originalScriptPath = source.path
compileScript(
scriptFile,
originalScriptPath,
scriptDefinition,
StableDisplayNameFor.stage1,
compileClassPath
)
}
private
fun compileScript(
scriptFile: File,
originalPath: String,
scriptDefinition: ScriptDefinition,
stage: String,
compileClassPath: ClassPath = classPath
) = InternalName.from(
compileBuildOperationRunner(originalPath, stage) {
compileKotlinScriptToDirectory(
outputDir,
scriptFile,
scriptDefinition,
compileClassPath.asFiles,
messageCollectorFor(logger) { path ->
if (path == scriptFile.path) originalPath
else path
}
)
}.let { compiledScriptClassName ->
packageName
?.let { "$it.$compiledScriptClassName" }
?: compiledScriptClassName
}
)
/**
* Stage descriptions for build operations.
*
* Changes to these constants must be coordinated with the GE team.
*/
private
object StableDisplayNameFor {
const val stage1 = "CLASSPATH"
const val stage2 = "BODY"
}
private
val stage1ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildscriptBlock::class
ProgramTarget.Settings -> CompiledKotlinSettingsBuildscriptBlock::class
ProgramTarget.Gradle -> CompiledKotlinInitscriptBlock::class
}
)
private
val stage2ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildScript::class
ProgramTarget.Settings -> CompiledKotlinSettingsScript::class
ProgramTarget.Gradle -> CompiledKotlinInitScript::class
}
)
private
val pluginsScriptDefinition
get() = scriptDefinitionFromTemplate(CompiledKotlinPluginsBlock::class)
private
fun implicitReceiverOf(scriptDefinition: ScriptDefinition): KClass<*>? =
implicitReceiverOf(scriptDefinition.baseClassType.fromClass!!)
private
val buildscriptWithPluginsScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildscriptAndPluginsBlock::class
ProgramTarget.Settings -> CompiledKotlinSettingsPluginManagementBlock::class
else -> TODO("Unsupported program target: `$programTarget`")
}
)
private
fun scriptDefinitionFromTemplate(template: KClass<out Any>) =
scriptDefinitionFromTemplate(
template,
implicitImports,
implicitReceiverOf(template),
injectedProperties,
classPath.asFiles
)
private
fun implicitReceiverOf(template: KClass<*>) =
template.annotations.filterIsInstance<ImplicitReceiver>().map { it.type }.firstOrNull()
}
internal
fun requiresAccessors(programTarget: ProgramTarget, programKind: ProgramKind) =
programTarget == ProgramTarget.Project && programKind == ProgramKind.TopLevel
| apache-2.0 | fdcb113fe0328daa68752e18011db086 | 33.540302 | 185 | 0.660857 | 5.518109 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/FileCollectionCodec.kt | 2 | 8354 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileTree
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactSetToFileCollectionFactory
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.LocalFileDependencyBackedArtifactSet
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet
import org.gradle.api.internal.artifacts.transform.TransformedExternalArtifactSet
import org.gradle.api.internal.artifacts.transform.TransformedProjectArtifactSet
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.internal.file.FileCollectionStructureVisitor
import org.gradle.api.internal.file.FileTreeInternal
import org.gradle.api.internal.file.FilteredFileCollection
import org.gradle.api.internal.file.SubtractingFileCollection
import org.gradle.api.internal.file.collections.FailingFileCollection
import org.gradle.api.internal.file.collections.FileSystemMirroringFileTree
import org.gradle.api.internal.file.collections.MinimalFileSet
import org.gradle.api.internal.file.collections.ProviderBackedFileCollection
import org.gradle.api.internal.provider.ProviderInternal
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.util.PatternSet
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingIdentity
import org.gradle.configurationcache.serialization.encodePreservingIdentityOf
import java.io.File
internal
class FileCollectionCodec(
private val fileCollectionFactory: FileCollectionFactory,
private val artifactSetConverter: ArtifactSetToFileCollectionFactory
) : Codec<FileCollectionInternal> {
override suspend fun WriteContext.encode(value: FileCollectionInternal) {
encodePreservingIdentityOf(value) {
val visitor = CollectingVisitor()
value.visitStructure(visitor)
write(visitor.elements)
}
}
override suspend fun ReadContext.decode(): FileCollectionInternal {
return decodePreservingIdentity { id ->
val contents = read()
val collection = if (contents is Collection<*>) {
fileCollectionFactory.resolving(
contents.map { element ->
when (element) {
is File -> element
is SubtractingFileCollectionSpec -> element.left.minus(element.right)
is FilteredFileCollectionSpec -> element.collection.filter(element.filter)
is ProviderBackedFileCollectionSpec -> element.provider
is FileTree -> element
is ResolvedArtifactSet -> artifactSetConverter.asFileCollection(element)
is BeanSpec -> element.bean
else -> throw IllegalArgumentException("Unexpected item $element in file collection contents")
}
}
)
} else {
fileCollectionFactory.create(ErrorFileSet(contents as BrokenValue))
}
isolate.identities.putInstance(id, collection)
collection
}
}
}
private
class SubtractingFileCollectionSpec(val left: FileCollection, val right: FileCollection)
private
class FilteredFileCollectionSpec(val collection: FileCollection, val filter: Spec<in File>)
private
class ProviderBackedFileCollectionSpec(val provider: ProviderInternal<*>)
private
class CollectingVisitor : FileCollectionStructureVisitor {
val elements: MutableSet<Any> = mutableSetOf()
override fun startVisit(source: FileCollectionInternal.Source, fileCollection: FileCollectionInternal): Boolean =
when (fileCollection) {
is SubtractingFileCollection -> {
// TODO - when left and right are both static then we should serialize the current contents of the collection
elements.add(SubtractingFileCollectionSpec(fileCollection.left, fileCollection.right))
false
}
is FilteredFileCollection -> {
// TODO - when the collection is static then we should serialize the current contents of the collection
elements.add(FilteredFileCollectionSpec(fileCollection.collection, fileCollection.filterSpec))
false
}
is ProviderBackedFileCollection -> {
// Guard against file collection created from a task provider such as `layout.files(compileJava)`
// being referenced from a different task.
val provider = fileCollection.provider
if (provider !is TaskProvider<*>) {
elements.add(ProviderBackedFileCollectionSpec(provider))
false
} else {
true
}
}
is FileTreeInternal -> {
elements.add(fileCollection)
false
}
is FailingFileCollection -> {
elements.add(BeanSpec(fileCollection))
false
}
else -> {
true
}
}
override fun prepareForVisit(source: FileCollectionInternal.Source): FileCollectionStructureVisitor.VisitType =
if (source is TransformedProjectArtifactSet || source is LocalFileDependencyBackedArtifactSet || source is TransformedExternalArtifactSet) {
// Represents artifact transform outputs. Visit the source rather than the files
// Transforms may have inputs or parameters that are task outputs or other changing files
// When this is not the case, we should run the transform now and write the result.
// However, currently it is not easy to determine whether or not this is the case so assume that all transforms
// have changing inputs
FileCollectionStructureVisitor.VisitType.NoContents
} else {
FileCollectionStructureVisitor.VisitType.Visit
}
override fun visitCollection(source: FileCollectionInternal.Source, contents: Iterable<File>) {
when (source) {
is TransformedProjectArtifactSet -> {
elements.add(source)
}
is LocalFileDependencyBackedArtifactSet -> {
elements.add(source)
}
is TransformedExternalArtifactSet -> {
elements.add(source)
}
else -> {
elements.addAll(contents)
}
}
}
override fun visitFileTree(root: File, patterns: PatternSet, fileTree: FileTreeInternal) =
unsupportedFileTree(fileTree)
override fun visitFileTreeBackedByFile(file: File, fileTree: FileTreeInternal, sourceTree: FileSystemMirroringFileTree) =
unsupportedFileTree(fileTree)
private
fun unsupportedFileTree(fileTree: FileTreeInternal): Nothing =
throw UnsupportedOperationException(
"Unexpected file tree '$fileTree' of type '${fileTree.javaClass}' found while serializing a file collection."
)
}
private
class ErrorFileSet(private val error: BrokenValue) : MinimalFileSet {
override fun getDisplayName() =
"error-file-collection"
override fun getFiles() =
error.rethrow()
}
| apache-2.0 | c0ed0ce16b4b75e070a2c8b774046ab0 | 42.510417 | 148 | 0.686617 | 5.521481 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/operator/AtomOperator.kt | 3 | 1762 | package com.github.sybila.checker.operator
import com.github.sybila.checker.Operator
import com.github.sybila.checker.Partition
import com.github.sybila.checker.StateMap
import com.github.sybila.huctl.Formula
class FalseOperator<out Params : Any>(
partition: Partition<Params>
) : Operator<Params> {
private val value
= partition.run { emptyStateMap() }
override fun compute(): StateMap<Params> = value
}
class TrueOperator<out Params : Any>(
partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params>
= partition.run { (0 until stateCount).asStateMap(tt).restrictToPartition() }
override fun compute(): StateMap<Params> = value
}
class ReferenceOperator<out Params : Any>(
state: Int,
partition: Partition<Params>
) : Operator<Params> {
private val value = partition.run {
if (state in this) state.asStateMap(tt) else emptyStateMap()
}
override fun compute(): StateMap<Params> = value
}
class FloatOperator<out Params : Any>(
private val float: Formula.Atom.Float,
private val partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params> by lazy(LazyThreadSafetyMode.NONE) {
partition.run { float.eval().restrictToPartition() }
}
override fun compute(): StateMap<Params> = value
}
class TransitionOperator<out Params : Any>(
private val transition: Formula.Atom.Transition,
private val partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params> by lazy(LazyThreadSafetyMode.NONE) {
partition.run { transition.eval().restrictToPartition() }
}
override fun compute(): StateMap<Params> = value
} | gpl-3.0 | 6f1687aa83966ad69ccbf08602a25b9b | 25.712121 | 89 | 0.690692 | 4.165485 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/repo/data/HoldingRow.kt | 1 | 411 | package com.github.premnirmal.ticker.repo.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class HoldingRow(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "quote_symbol") val quoteSymbol: String,
@ColumnInfo(name = "shares") val shares: Float = 0.0f,
@ColumnInfo(name = "price") val price: Float = 0.0f
) | gpl-3.0 | e5f3d8671792363435ae608c56863b52 | 30.692308 | 63 | 0.73236 | 3.512821 | false | false | false | false |
ratedali/EEESE-android | app/src/main/java/edu/uofk/eeese/eeese/data/database/DatabaseHelper.kt | 1 | 4010 | /*
* Copyright 2017 Ali Salah Alddin
*
* 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 edu.uofk.eeese.eeese.data.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import edu.uofk.eeese.eeese.data.DataContract
import edu.uofk.eeese.eeese.di.scopes.ApplicationScope
import javax.inject.Inject
@ApplicationScope
class DatabaseHelper @Inject
constructor(context: Context) : SQLiteOpenHelper(context, DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "eeese.db"
private const val DATABASE_VERSION = 1
}
override fun onCreate(db: SQLiteDatabase) {
val CREATE_PROJECTS_TABLE_QUERY =
"CREATE TABLE ${DataContract.ProjectEntry.TABLE_NAME} " +
"(" +
"${DataContract.ProjectEntry._ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_ID} " +
"TEXT UNIQUE ON CONFLICT REPLACE, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_NAME} TEXT NOT NULL, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_HEAD} TEXT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_DESC} TEXT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_CATEGORY} INTEGER, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_PREREQS} TEXT" +
")"
val CREATE_EVENTS_TABLE_QUERY =
"CREATE TABLE ${DataContract.EventEntry.TABLE_NAME}" +
"( " +
"${DataContract.EventEntry._ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${DataContract.EventEntry.COLUMN_EVENT_ID} " +
"TEXT UNIQUE ON CONFLICT REPLACE, " +
"${DataContract.EventEntry.COLUMN_EVENT_NAME} TEXT NOT NULL, " +
"${DataContract.EventEntry.COLUMN_EVENT_DESC} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_IMAGE_URI} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_LOCATION} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_START_DATE} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_END_DATE} TEXT" +
")"
db.execSQL(CREATE_PROJECTS_TABLE_QUERY)
db.execSQL(CREATE_EVENTS_TABLE_QUERY)
}
override fun onUpgrade(db: SQLiteDatabase, i: Int, i1: Int) {
val DROP_PROJECTS_TABLE_QUERY =
"DROP TABLE IF EXISTS ${DataContract.ProjectEntry.TABLE_NAME}"
val DROP_EVENTS_TABLE_QUERY =
"DROP TABLE IF EXISTS ${DataContract.EventEntry.TABLE_NAME}"
db.execSQL(DROP_PROJECTS_TABLE_QUERY)
db.execSQL(DROP_EVENTS_TABLE_QUERY)
onCreate(db)
}
}
| mit | e34b5356f993e8e4553990addffb3dcc | 54.694444 | 463 | 0.644389 | 4.860606 | false | false | false | false |
andretietz/retroauth | sqlite/src/main/kotlin/com/andretietz/retroauth/Main.kt | 1 | 1571 | //package com.andretietz.retroauth
//
//import com.andretietz.retroauth.sqlite.CredentialTable
//import com.andretietz.retroauth.sqlite.DataTable
//import com.andretietz.retroauth.sqlite.DatabaseCredential
//import com.andretietz.retroauth.sqlite.DatabaseUser
//import com.andretietz.retroauth.sqlite.UserTable
//import com.andretietz.retroauth.sqlite.data.Account
//import org.jetbrains.exposed.sql.Database
//import org.jetbrains.exposed.sql.SchemaUtils
//import org.jetbrains.exposed.sql.StdOutSqlLogger
//import org.jetbrains.exposed.sql.addLogger
//import org.jetbrains.exposed.sql.selectAll
//import org.jetbrains.exposed.sql.transactions.transaction
//private const val OWNER_TYPE = "ownertype"
//
//fun main() {
// val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
//// Database.connect(
//// "jdbc:sqlite:accountdb.db",
//// user = "someuser",
//// password = "somepassword",
//// driver = "org.sqlite.JDBC"
//// )
//
// val credentialStore = SQLiteCredentialStore(database)
// val ownerStore: OwnerStorage<Account> = SQLiteOwnerStore(database)
//
// transaction(database) {
// addLogger(StdOutSqlLogger)
// SchemaUtils.create(UserTable, CredentialTable, DataTable)
//
// ownerStore.createOwner(CREDENTIAL_TYPE)?.let {
// credentialStore.storeCredentials(it, CREDENTIAL_TYPE, Credentials("myfancytoken"))
//
// val credential = credentialStore.getCredentials(it, CREDENTIAL_TYPE)
// println(credential)
// }
//
// SchemaUtils.drop(UserTable, CredentialTable, DataTable)
// }
//}
//
//
| apache-2.0 | 8d00a20536a63a1e6b6371e279e3f96e | 34.704545 | 90 | 0.738383 | 3.679157 | false | false | false | false |
AsynkronIT/protoactor-kotlin | proto-actor/src/main/kotlin/actor/proto/API.kt | 1 | 1016 | @file:JvmName("Actors")
@file:JvmMultifileClass
package actor.proto
import actor.proto.mailbox.SystemMessage
@JvmSynthetic
fun fromProducer(producer: () -> Actor): Props = Props().withProducer(producer)
@JvmSynthetic
fun fromFunc(receive: suspend Context.(msg: Any) -> Unit): Props = fromProducer {
object : Actor {
override suspend fun Context.receive(msg: Any) = receive(this, msg)
}
}
fun spawn(props: Props): PID {
val name = ProcessRegistry.nextId()
return spawnNamed(props, name)
}
fun spawnPrefix(props: Props, prefix: String): PID {
val name = prefix + ProcessRegistry.nextId()
return spawnNamed(props, name)
}
fun spawnNamed(props: Props, name: String): PID = props.spawn(name, null)
fun stop(pid: PID) {
val process = pid.cachedProcess() ?: ProcessRegistry.get(pid)
process.stop(pid)
}
fun sendSystemMessage(pid: PID, sys: SystemMessage) {
val process: Process = pid.cachedProcess() ?: ProcessRegistry.get(pid)
process.sendSystemMessage(pid, sys)
}
| apache-2.0 | 39d5faba051b23fae72d3affe70284dc | 25.736842 | 81 | 0.709646 | 3.681159 | false | false | false | false |
hblanken/Tower-v3.2.1 | Android/src/org/droidplanner/android/activities/WidgetActivity.kt | 1 | 3094 | package org.droidplanner.android.activities
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import com.o3dr.android.client.Drone
import com.o3dr.android.client.apis.CapabilityApi
import com.o3dr.android.client.apis.VehicleApi
import com.o3dr.android.client.apis.solo.SoloCameraApi
import com.o3dr.services.android.lib.coordinate.LatLong
import com.o3dr.services.android.lib.drone.attribute.AttributeEvent
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.companion.solo.SoloAttributes
import com.o3dr.services.android.lib.drone.companion.solo.SoloEvents
import com.o3dr.services.android.lib.drone.companion.solo.tlv.SoloGoproState
import org.droidplanner.android.R
import org.droidplanner.android.activities.helpers.SuperUI
import org.droidplanner.android.fragments.FlightDataFragment
import org.droidplanner.android.fragments.FlightMapFragment
import org.droidplanner.android.fragments.widget.TowerWidget
import org.droidplanner.android.fragments.widget.TowerWidgets
import org.droidplanner.android.fragments.widget.video.FullWidgetSoloLinkVideo
import org.droidplanner.android.utils.prefs.AutoPanMode
import kotlin.properties.Delegates
/**
* Created by Fredia Huya-Kouadio on 7/19/15.
*/
public class WidgetActivity : SuperUI() {
companion object {
val EXTRA_WIDGET_ID = "extra_widget_id"
}
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_widget)
val fm = supportFragmentManager
var flightDataFragment = fm.findFragmentById(R.id.map_view) as FlightDataFragment?
if(flightDataFragment == null){
flightDataFragment = FlightDataFragment()
fm.beginTransaction().add(R.id.map_view, flightDataFragment).commit()
}
handleIntent(intent)
}
override fun onNewIntent(intent: Intent?){
super.onNewIntent(intent)
if(intent != null)
handleIntent(intent)
}
private fun handleIntent(intent: Intent){
val widgetId = intent.getIntExtra(EXTRA_WIDGET_ID, 0)
val fm = supportFragmentManager
val widget = TowerWidgets.getWidgetById(widgetId)
if(widget != null){
setToolbarTitle(widget.labelResId)
val currentWidget = fm.findFragmentById(R.id.widget_view) as TowerWidget?
val currentWidgetType = if(currentWidget == null) null else currentWidget.getWidgetType()
if(widget == currentWidgetType)
return
val widgetFragment = widget.getMaximizedFragment()
fm.beginTransaction().replace(R.id.widget_view, widgetFragment).commit()
}
}
override fun getToolbarId() = R.id.actionbar_container
} | gpl-3.0 | 20a3543f8c63e1474261748ab8f89cfc | 36.289157 | 101 | 0.755979 | 4.22101 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/ResizeAppearance.kt | 1 | 2433 | /*
Tickle
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.tickle
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.physics.offset
import uk.co.nickthecoder.tickle.physics.scale
/**
* The base class for NinePatchAppearance and TiledAppearance which can both be given an arbitrary size without scaling.
*/
abstract class ResizeAppearance(actor: Actor) : AbstractAppearance(actor) {
val size = Vector2d(1.0, 1.0)
/**
* The alignment, where x,y are both in the range 0..1
* (0,0) means the Actor's position is at the bottom left of the NinePatch.
* (1,1) means the Actor's position is at the top right of the NinePatch.
*/
val sizeAlignment = Vector2d(0.5, 0.5)
internal val oldSize = Vector2d(1.0, 1.0)
protected val oldAlignment = Vector2d(0.5, 0.5)
override fun height() = size.y
override fun width() = size.x
override fun offsetX() = size.x * sizeAlignment.x
override fun offsetY() = size.y * sizeAlignment.y
override fun touching(point: Vector2d) = pixelTouching(point)
override fun resize(width: Double, height: Double) {
size.x = width
size.y = height
}
override fun updateBody() {
if (oldSize != size) {
actor.body?.jBox2DBody?.scale((size.x / oldSize.x).toFloat(), (size.y / oldSize.y).toFloat())
oldSize.set(size)
}
if (oldAlignment != sizeAlignment) {
actor.body?.let { body ->
val world = body.tickleWorld
body.jBox2DBody.offset(
world.pixelsToWorld((oldAlignment.x - sizeAlignment.x) * width()),
world.pixelsToWorld((oldAlignment.y - sizeAlignment.y) * height()))
}
oldAlignment.set(sizeAlignment)
}
}
}
| gpl-3.0 | c72730ba5b8ad1baaf0baf44e0507873 | 30.597403 | 120 | 0.6679 | 3.962541 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/memory/RealMemoryCache.kt | 1 | 1542 | package coil.memory
import coil.memory.MemoryCache.Key
import coil.util.toImmutableMap
internal class RealMemoryCache(
private val strongMemoryCache: StrongMemoryCache,
private val weakMemoryCache: WeakMemoryCache
) : MemoryCache {
override val size get() = strongMemoryCache.size
override val maxSize get() = strongMemoryCache.maxSize
override val keys get() = strongMemoryCache.keys + weakMemoryCache.keys
override fun get(key: Key): MemoryCache.Value? {
return strongMemoryCache.get(key) ?: weakMemoryCache.get(key)
}
override fun set(key: Key, value: MemoryCache.Value) {
// Ensure that stored keys and values are immutable.
strongMemoryCache.set(
key = key.copy(extras = key.extras.toImmutableMap()),
bitmap = value.bitmap,
extras = value.extras.toImmutableMap()
)
// weakMemoryCache.set() is called by strongMemoryCache when
// a value is evicted from the strong reference cache.
}
override fun remove(key: Key): Boolean {
// Do not short circuit. There is a regression test for this.
val removedStrong = strongMemoryCache.remove(key)
val removedWeak = weakMemoryCache.remove(key)
return removedStrong || removedWeak
}
override fun clear() {
strongMemoryCache.clearMemory()
weakMemoryCache.clearMemory()
}
override fun trimMemory(level: Int) {
strongMemoryCache.trimMemory(level)
weakMemoryCache.trimMemory(level)
}
}
| apache-2.0 | 498c90aab4beba3f16c2432d3e376adc | 31.125 | 75 | 0.682879 | 4.958199 | false | false | false | false |
signed/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerPathHandler.kt | 1 | 6498 | /*
* Copyright 2000-2014 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.builtInWebServer
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.io.endsWithSlash
import com.intellij.openapi.util.io.getParentPath
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VFileProperty
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.io.*
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.HttpResponseStatus
import org.jetbrains.io.orInSafeMode
import org.jetbrains.io.send
import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Pattern
val chromeVersionFromUserAgent: Pattern = Pattern.compile(" Chrome/([\\d.]+) ")
private class DefaultWebServerPathHandler : WebServerPathHandler() {
override fun process(path: String,
project: Project,
request: FullHttpRequest,
context: ChannelHandlerContext,
projectName: String,
decodedRawPath: String,
isCustomHost: Boolean): Boolean {
val channel = context.channel()
val isSignedRequest = request.isSignedRequest()
val extraHeaders = validateToken(request, channel, isSignedRequest) ?: return true
val pathToFileManager = WebServerPathToFileManager.getInstance(project)
var pathInfo = pathToFileManager.pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
pathInfo = pathToFileManager.doFindByRelativePath(path, defaultPathQuery)
if (pathInfo == null) {
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
var indexUsed = false
if (pathInfo.isDirectory()) {
var indexVirtualFile: VirtualFile? = null
var indexFile: Path? = null
if (pathInfo.file == null) {
indexFile = findIndexFile(pathInfo.ioFile!!)
}
else {
indexVirtualFile = findIndexFile(pathInfo.file!!)
}
if (indexFile == null && indexVirtualFile == null) {
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
// we must redirect only after index file check to not expose directory status
if (!endsWithSlash(decodedRawPath)) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders)
return true
}
indexUsed = true
pathInfo = PathInfo(indexFile, indexVirtualFile, pathInfo.root, pathInfo.moduleName, pathInfo.isLibrary)
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
val userAgent = request.userAgent
if (!isSignedRequest && userAgent != null && request.isRegularBrowser() && request.origin == null && request.referrer == null) {
val matcher = chromeVersionFromUserAgent.matcher(userAgent)
if (matcher.find() && StringUtil.compareVersionNumbers(matcher.group(1), "51") < 0 && !canBeAccessedDirectly(pathInfo.name)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return true
}
}
if (!indexUsed && !endsWithName(path, pathInfo.name)) {
if (endsWithSlash(decodedRawPath)) {
indexUsed = true
}
else {
// FallbackResource feature in action, /login requested, /index.php retrieved, we must not redirect /login to /login/
val parentPath = getParentPath(pathInfo.path)
if (parentPath != null && endsWithName(path, PathUtilRt.getFileName(parentPath))) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders)
return true
}
}
}
if (!checkAccess(pathInfo, channel, request)) {
return true
}
val canonicalPath = if (indexUsed) "$path/${pathInfo.name}" else path
for (fileHandler in WebServerFileHandler.EP_NAME.extensions) {
LOG.catchAndLog {
if (fileHandler.process(pathInfo!!, canonicalPath, project, request, channel, if (isCustomHost) null else projectName, extraHeaders)) {
return true
}
}
}
// we registered as a last handler, so, we should just return 404 and send extra headers
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
}
private fun checkAccess(pathInfo: PathInfo, channel: Channel, request: HttpRequest): Boolean {
if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) {
val file = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path)
if (file.isDirectory()) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
else if (!hasAccess(file)) {
// we check only file, but all directories in the path because of https://youtrack.jetbrains.com/issue/WEB-21594
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
}
else if (pathInfo.file!!.`is`(VFileProperty.HIDDEN)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
return true
}
private fun canBeAccessedDirectly(path: String): Boolean {
for (fileHandler in WebServerFileHandler.EP_NAME.extensions) {
for (ext in fileHandler.pageFileExtensions) {
if (FileUtilRt.extensionEquals(path, ext)) {
return true
}
}
}
return false
} | apache-2.0 | 1efb59971d0cc4ea7071cae5dd5c9ae9 | 38.150602 | 143 | 0.706525 | 4.618337 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/GitLogParser.kt | 1 | 5712 | package de.maibornwolff.codecharta.importer.gitlogparser
import de.maibornwolff.codecharta.filter.mergefilter.MergeFilter
import de.maibornwolff.codecharta.importer.gitlogparser.InputFormatNames.GIT_LOG_NUMSTAT_RAW_REVERSED
import de.maibornwolff.codecharta.importer.gitlogparser.converter.ProjectConverter
import de.maibornwolff.codecharta.importer.gitlogparser.input.metrics.MetricsFactory
import de.maibornwolff.codecharta.importer.gitlogparser.parser.LogParserStrategy
import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.GitLogNumstatRawParserStrategy
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.LogScanCommand
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.RepoScanCommand
import de.maibornwolff.codecharta.model.Project
import de.maibornwolff.codecharta.serialization.ProjectDeserializer
import de.maibornwolff.codecharta.serialization.ProjectSerializer
import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
import org.mozilla.universalchardet.UniversalDetector
import picocli.CommandLine
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.nio.charset.Charset
import java.nio.file.Files
import java.util.concurrent.Callable
import java.util.stream.Stream
@CommandLine.Command(
name = "gitlogparser",
description = ["git log parser - generates cc.json from git-log files"],
subcommands = [LogScanCommand::class, RepoScanCommand::class],
footer = ["Copyright(c) 2022, MaibornWolff GmbH"]
)
class GitLogParser(
private val input: InputStream = System.`in`,
private val output: PrintStream = System.out,
private val error: PrintStream = System.err
) : Callable<Void>, InteractiveParser {
private val inputFormatNames = GIT_LOG_NUMSTAT_RAW_REVERSED
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exits"])
private var help = false
private val logParserStrategy: LogParserStrategy
get() = getLogParserStrategyByInputFormat(inputFormatNames)
private val metricsFactory: MetricsFactory
get() {
val nonChurnMetrics = listOf(
"age_in_weeks",
"number_of_authors",
"number_of_commits",
"number_of_renames",
"range_of_weeks_with_commits",
"successive_weeks_of_commits",
"weeks_with_commits",
"highly_coupled_files",
"median_coupled_files"
)
return when (inputFormatNames) {
GIT_LOG_NUMSTAT_RAW_REVERSED -> MetricsFactory(nonChurnMetrics)
}
}
@Throws(IOException::class)
override fun call(): Void? {
print(" ")
return null
}
internal fun buildProject(
gitLogFile: File,
gitLsFile: File,
outputFilePath: String?,
addAuthor: Boolean,
silent: Boolean,
compress: Boolean
) {
var project = createProjectFromLog(
gitLogFile,
gitLsFile,
logParserStrategy,
metricsFactory,
addAuthor,
silent
)
val pipedProject = ProjectDeserializer.deserializeProject(input)
if (pipedProject != null) {
project = MergeFilter.mergePipedWithCurrentProject(pipedProject, project)
}
ProjectSerializer.serializeToFileOrStream(project, outputFilePath, output, compress)
}
private fun getLogParserStrategyByInputFormat(formatName: InputFormatNames): LogParserStrategy {
return when (formatName) {
GIT_LOG_NUMSTAT_RAW_REVERSED -> GitLogNumstatRawParserStrategy()
}
}
private fun readFileNameListFile(path: File): MutableList<String> {
val inputStream: InputStream = path.inputStream()
val lineList = mutableListOf<String>()
inputStream.bufferedReader().forEachLine { lineList.add(it) }
return lineList
}
private fun createProjectFromLog(
gitLogFile: File,
gitLsFile: File,
parserStrategy: LogParserStrategy,
metricsFactory: MetricsFactory,
containsAuthors: Boolean,
silent: Boolean = false
): Project {
val namesInProject = readFileNameListFile(gitLsFile)
val encoding = guessEncoding(gitLogFile) ?: "UTF-8"
if (!silent) error.println("Assumed encoding $encoding")
val lines: Stream<String> = Files.lines(gitLogFile.toPath(), Charset.forName(encoding))
val projectConverter = ProjectConverter(containsAuthors)
val logSizeInByte = gitLogFile.length()
return GitLogProjectCreator(parserStrategy, metricsFactory, projectConverter, logSizeInByte, silent).parse(
lines,
namesInProject
)
}
companion object {
private fun guessEncoding(pathToLog: File): String? {
val inputStream = pathToLog.inputStream()
val buffer = ByteArray(4096)
val detector = UniversalDetector(null)
var sizeRead = inputStream.read(buffer)
while (sizeRead > 0 && !detector.isDone) {
detector.handleData(buffer, 0, sizeRead)
sizeRead = inputStream.read(buffer)
}
detector.dataEnd()
return detector.detectedCharset
}
@JvmStatic
fun main(args: Array<String>) {
CommandLine(GitLogParser()).execute(*args)
}
}
override fun getDialog(): ParserDialogInterface = ParserDialog
}
| bsd-3-clause | 2c836aa69622d5d576219eb0970f1f04 | 35.851613 | 115 | 0.683824 | 4.820253 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/CortesFlowCommand.kt | 1 | 4711 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.awt.Color
class CortesFlowCommand(
m: LorittaBot,
) : DiscordAbstractCommandBase(
m,
listOf(
"cortesflow", "flowcortes"
),
net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES
) {
override fun command() = create {
localizedDescription("commands.command.cortesflow.description")
localizedExamples("commands.command.cortesflow.examples")
needsToUploadFiles = true
arguments {
argument(ArgumentType.TEXT) {}
argument(ArgumentType.TEXT) {}
}
executesDiscord {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "brmemes cortesflow")
if (args.isEmpty()) {
val result = loritta.http.get("https://gabriela.loritta.website/api/v1/images/cortes-flow")
.bodyAsText()
val elements = Json.parseToJsonElement(result)
.jsonArray
val availableGroupedBy = elements.groupBy { it.jsonObject["participant"]!!.jsonPrimitive.content }
.entries
.sortedByDescending { it.value.size }
val embed = EmbedBuilder()
.setTitle("${Emotes.FLOW_PODCAST} ${locale["commands.command.cortesflow.embedTitle"]}")
.setDescription(
locale.getList(
"commands.command.cortesflow.embedDescription",
locale["commands.command.cortesflow.howToUseExample", serverConfig.commandPrefix],
locale["commands.command.cortesflow.commandExample", serverConfig.commandPrefix]
).joinToString("\n")
)
.setFooter(locale["commands.command.cortesflow.findOutThumbnailSource"], "https://yt3.ggpht.com/a/AATXAJwhhX5JXoYvdDwDI56fQfTDinfs21vzivC-DBW6=s88-c-k-c0x00ffffff-no-rj")
.setColor(Color.BLACK)
for ((_, value) in availableGroupedBy) {
embed.addField(
value.first().jsonObject["participantDisplayName"]!!.jsonPrimitive.content,
value.joinToString {
locale[
"commands.command.cortesflow.thumbnailSelection",
it.jsonObject["path"]!!.jsonPrimitive.content.removePrefix("/api/v1/images/cortes-flow/"),
it.jsonObject["source"]!!.jsonPrimitive.content
]
},
true
)
}
sendMessageEmbeds(
embed.build()
)
return@executesDiscord
}
if (args.size == 1)
fail(locale["commands.command.cortesflow.youNeedToAddText"])
val type = args.getOrNull(0)
val string = args
.drop(1)
.joinToString(" ")
val response = loritta.http.post("https://gabriela.loritta.website/api/v1/images/cortes-flow/$type") {
setBody(
buildJsonObject {
putJsonArray("strings") {
addJsonObject {
put("string", string)
}
}
}.toString()
)
}
if (response.status == HttpStatusCode.NotFound)
fail(locale["commands.command.cortesflow.unknownType", serverConfig.commandPrefix])
sendFile(response.readBytes(), "cortes_flow.jpg")
}
}
} | agpl-3.0 | 75965a86c5ff155adcf0bf9b1cbaf393 | 40.333333 | 190 | 0.586924 | 5.28139 | false | false | false | false |
spookyUnknownUser/PremiereDowngrader | src/main/kotlin/mainview/MainViewStyle.kt | 1 | 1119 | package mainview
import javafx.scene.layout.BorderStrokeStyle
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
/**
* Created on 29/08/2017.
*
* Stylesheet for the [MainView]
*/
class MainViewStyle : Stylesheet() {
init {
button {
fontFamily = "Helvetica"
fontWeight = FontWeight.EXTRA_BOLD
fontSize = 30.px
backgroundColor += c("#3B3B3B")
textFill = Color.WHITE
and(hover) {
backgroundColor += c("#005599")
borderColor += box(
all = c("#2c312e")
)
borderStyle += BorderStrokeStyle.DOTTED
}
and(pressed) {
backgroundColor += c("#2f2f2f")
}
}
label {
textFill = Color.WHITE
fontFamily = "Helvetica"
fontSize = 30.px
fontWeight = FontWeight.BOLD
}
root {
backgroundColor += c("2B2B2B")
padding = box(50.px, 10.px, 10.px, 10.px)
}
}
} | mit | 3036cfd71053419fb03a5442a1714686 | 22.333333 | 55 | 0.497766 | 4.476 | false | false | false | false |
android/app-bundle-samples | DynamicFeatureNavigation/DSL/app/src/main/java/com/example/android/dfn/dsl/MainActivity.kt | 1 | 3351 | /*
* 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 com.example.android.dfn.dsl
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.dynamicfeatures.activity
import androidx.navigation.dynamicfeatures.createGraph
import androidx.navigation.dynamicfeatures.fragment.DynamicNavHostFragment
import androidx.navigation.dynamicfeatures.fragment.fragment
import androidx.navigation.dynamicfeatures.includeDynamic
import com.example.android.dfn.dsl.databinding.ActivityMainBinding
/**
* Main entry point into the Kotlin DSL sample for Dynamic Feature Navigation.
* The navigation graph is declared in this class.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(ActivityMainBinding.inflate(layoutInflater).root)
(supportFragmentManager.findFragmentByTag("nav_host") as DynamicNavHostFragment)
.navController
.apply {
// Create a dynamic navigation graph. Inside this destinations from within dynamic
// feature modules can be navigated to.
graph = createGraph(
id = R.id.graphId,
startDestination = R.id.startDestination
) {
// A fragment destination declared in the "base" feature module.
fragment<StartDestinationFragment>(R.id.startDestination)
// A fragment destination declared in the "ondemand" dynamic feature module.
fragment(R.id.onDemandFragment, "${baseContext.packageName}$ON_DEMAND_FRAGMENT") {
moduleName = MODULE_ON_DEMAND
}
// An activity destination declared in the "ondemand" dynamic feature module.
activity(id = R.id.featureActivity) {
moduleName = MODULE_ON_DEMAND
activityClassName = "${baseContext.packageName}$FEATURE_ACTIVITY"
}
/* A dynamically included graph in the "included" dynamic feature module.
This matches the <include-dynamic> tag in xml. */
includeDynamic(
id = R.id.includedFragment,
moduleName = MODULE_INCLUDED,
graphResourceName = INCLUDED_GRAPH_NAME
)
}
}
}
}
const val INCLUDED_GRAPH_NAME = "included_dynamically"
const val ON_DEMAND_FRAGMENT = ".ondemand.OnDemandFragment"
const val FEATURE_ACTIVITY = ".ondemand.FeatureActivity"
const val MODULE_INCLUDED = "included"
const val MODULE_ON_DEMAND = "ondemand"
| apache-2.0 | daffed03ef8eb355c6b1af81c14a0b8c | 43.092105 | 102 | 0.657714 | 5.260597 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/misc/tileentity/TileTrait.kt | 2 | 548 | package misc.tileentity
import com.cout970.magneticraft.tileentity.TileBase
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by cout970 on 2017/02/21.
*/
abstract class TileTrait(val tile: TileBase) : ITileTrait {
override fun getPos(): BlockPos = tile.pos
override fun getWorld(): World = tile.world
private var firstTick = false
override fun update() {
if (!firstTick){
firstTick = true
onFullyLoad()
}
}
open fun onFullyLoad() = Unit
} | gpl-2.0 | 2ebf159ef21b31840980e85583418f82 | 20.96 | 59 | 0.666058 | 4.029412 | false | false | false | false |
danielrs/botellier | src/main/kotlin/org/botellier/server/Client.kt | 1 | 2691 | package org.botellier.server
import org.botellier.command.CommandParser
import org.botellier.value.Lexer
import org.botellier.value.LexerException
import org.botellier.value.ParserException
import org.botellier.value.toList
import java.net.Socket
import java.net.SocketException
import java.net.SocketTimeoutException
/**
* Container class for client information.
*/
data class Client(val socket: Socket, var dbIndex: Int = 0, var isAuthenticated: Boolean = false)
/**
* Class for handling a new client connection. It reads the input,
* tries to parse a command, and then sends back the constructed
* request using the provided callback.
* @property db the current db the client is connected to.
*/
class ClientHandler(val client: Client, val dispatcher: RequestDispatcher) : Runnable {
var readTimeout: Int = 1000
override fun run() {
println("Handling client ${client.socket.inetAddress.hostAddress}")
loop@while (true) {
try {
val stream = client.socket.waitInput()
client.socket.soTimeout = readTimeout
val tokens = Lexer(stream).lex().toList()
client.socket.soTimeout = 0
val command = CommandParser.parse(tokens)
dispatcher.dispatch(Request(client, command))
}
catch (e: SocketException) {
break@loop
}
catch (e: Throwable) {
println(e.message)
val writer = client.socket.getOutputStream().bufferedWriter()
when (e) {
// Exception for Lexer waiting too much.
is SocketTimeoutException ->
writer.write("-ERR Command read timeout\r\n")
// Exception regarding the serialized data.
is LexerException ->
writer.write("-COMMANDERR Unable to read command\r\n")
// Exception regarding the structure of the data.
is ParserException ->
writer.write("-COMMANDERR Unable to parse command\r\n")
// Exception regarding unknown command.
is CommandParser.UnknownCommandException ->
writer.write("-COMMANDERR ${e.message}\r\n")
// Exception that we don't know how to handle.
else -> {
client.socket.close()
break@loop
}
}
writer.flush()
}
}
println("Dropping client ${client.socket.inetAddress.hostAddress}")
}
}
| mit | 4830a8e165e8acf16015c8145020976c | 35.863014 | 97 | 0.575994 | 5.255859 | false | false | false | false |
robinverduijn/gradle | .teamcity/Gradle_Promotion/buildTypes/PublishGradleDistribution.kt | 1 | 2634 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package Gradle_Promotion.buildTypes
import common.Os
import common.builtInRemoteBuildCacheNode
import common.gradleWrapper
import common.requiresOs
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.vcs.GitVcsRoot
abstract class PublishGradleDistribution(
branch: String,
task: String,
val triggerName: String,
gitUserName: String = "Gradleware Git Bot",
gitUserEmail: String = "[email protected]",
extraParameters: String = "",
vcsRoot: GitVcsRoot = Gradle_Promotion.vcsRoots.Gradle_Promotion__master_
) : BasePromotionBuildType(vcsRoot = vcsRoot) {
init {
artifactRules = """
incoming-build-receipt/build-receipt.properties => incoming-build-receipt
**/build/git-checkout/build/build-receipt.properties
**/build/distributions/*.zip => promote-build-distributions
**/build/website-checkout/data/releases.xml
**/build/git-checkout/build/reports/integTest/** => distribution-tests
**/smoke-tests/build/reports/tests/** => post-smoke-tests
""".trimIndent()
steps {
gradleWrapper {
name = "Promote"
tasks = task
gradleParams = """-PuseBuildReceipt $extraParameters "-PgitUserName=$gitUserName" "-PgitUserEmail=$gitUserEmail" -Igradle/buildScanInit.gradle ${builtInRemoteBuildCacheNode.gradleParameters(Os.linux).joinToString(" ")}"""
}
}
dependencies {
artifacts(AbsoluteId("Gradle_Check_Stage_${[email protected]}_Trigger")) {
buildRule = lastSuccessful(branch)
cleanDestination = true
artifactRules = "build-receipt.properties => incoming-build-receipt/"
}
}
requirements {
requiresOs(Os.linux)
}
}
}
fun String.promoteNightlyTaskName(): String = "promote${if (this == "master") "" else capitalize()}Nightly"
| apache-2.0 | 86396956cb4c15bd0fd1aeeefd2386e0 | 38.313433 | 237 | 0.686029 | 4.564991 | false | true | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/Lexer.kt | 1 | 6479 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.jetbrains.kotlin.lexer.KotlinLexer
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.lexer.KtTokens.COMMENTS
import org.jetbrains.kotlin.lexer.KtTokens.IDENTIFIER
import org.jetbrains.kotlin.lexer.KtTokens.LBRACE
import org.jetbrains.kotlin.lexer.KtTokens.PACKAGE_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.RBRACE
import org.jetbrains.kotlin.lexer.KtTokens.WHITE_SPACE
internal
class UnexpectedBlock(val identifier: String, val location: IntRange) : RuntimeException("Unexpected block found.")
private
enum class State {
SearchingTopLevelBlock,
SearchingBlockStart,
SearchingBlockEnd
}
data class Packaged<T>(
val packageName: String?,
val document: T
) {
fun <U> map(transform: (T) -> U): Packaged<U> = Packaged(
packageName,
document = transform(document)
)
}
internal
data class LexedScript(
val comments: List<IntRange>,
val topLevelBlocks: List<TopLevelBlock>
)
/**
* Returns the comments and [top-level blocks][topLevelBlockIds] found in the given [script].
*/
internal
fun lex(script: String, vararg topLevelBlockIds: String): Packaged<LexedScript> {
var packageName: String? = null
val comments = mutableListOf<IntRange>()
val topLevelBlocks = mutableListOf<TopLevelBlock>()
var state = State.SearchingTopLevelBlock
var inTopLevelBlock: String? = null
var blockIdentifier: IntRange? = null
var blockStart: Int? = null
var depth = 0
fun reset() {
state = State.SearchingTopLevelBlock
inTopLevelBlock = null
blockIdentifier = null
blockStart = null
}
fun KotlinLexer.matchTopLevelIdentifier(): Boolean {
if (depth == 0) {
val identifier = tokenText
for (topLevelBlock in topLevelBlockIds) {
if (topLevelBlock == identifier) {
state = State.SearchingBlockStart
inTopLevelBlock = topLevelBlock
blockIdentifier = tokenStart..(tokenEnd - 1)
return true
}
}
}
return false
}
KotlinLexer().apply {
start(script)
while (tokenType != null) {
when (tokenType) {
WHITE_SPACE -> {
// ignore
}
in COMMENTS -> {
comments.add(
tokenStart..(tokenEnd - 1)
)
}
else -> {
when (state) {
State.SearchingTopLevelBlock -> {
when (tokenType) {
PACKAGE_KEYWORD -> {
advance()
skipWhiteSpaceAndComments()
packageName = parseQualifiedName()
}
IDENTIFIER -> matchTopLevelIdentifier()
LBRACE -> depth += 1
RBRACE -> depth -= 1
}
}
State.SearchingBlockStart -> {
when (tokenType) {
IDENTIFIER -> if (!matchTopLevelIdentifier()) reset()
LBRACE -> {
depth += 1
state = State.SearchingBlockEnd
blockStart = tokenStart
}
else -> reset()
}
}
State.SearchingBlockEnd -> {
when (tokenType) {
LBRACE -> depth += 1
RBRACE -> {
depth -= 1
if (depth == 0) {
topLevelBlocks.add(
topLevelBlock(
inTopLevelBlock!!,
blockIdentifier!!,
blockStart!!..tokenStart
)
)
reset()
}
}
}
}
}
}
}
advance()
}
}
return Packaged(
packageName,
LexedScript(comments, topLevelBlocks)
)
}
private
fun KotlinLexer.parseQualifiedName(): String =
StringBuilder().run {
while (tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.DOT) {
append(tokenText)
advance()
}
toString()
}
private
fun KotlinLexer.skipWhiteSpaceAndComments() {
while (tokenType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) {
advance()
}
}
internal
fun topLevelBlock(identifier: String, identifierRange: IntRange, blockRange: IntRange) =
TopLevelBlock(identifier, ScriptSection(identifierRange, blockRange))
internal
data class TopLevelBlock(val identifier: String, val section: ScriptSection) {
val range: IntRange
get() = section.wholeRange
}
internal
fun List<TopLevelBlock>.singleBlockSectionOrNull(): ScriptSection? =
when (size) {
0 -> null
1 -> get(0).section
else -> {
val unexpectedBlock = get(1)
throw UnexpectedBlock(unexpectedBlock.identifier, unexpectedBlock.range)
}
}
| apache-2.0 | d90a6917de53fbb1e5f2d5f170715097 | 28.720183 | 115 | 0.504553 | 5.70837 | false | false | false | false |
mplatvoet/kovenant | projects/core/src/main/kotlin/bulk-api.kt | 1 | 7094 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* 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,
* THE SOFTWARE.
*/
@file:JvmName("KovenantBulkApi")
package nl.komponents.kovenant
/**
* Creates a promise that is considered done if either all provided promises are successful or one fails.
*
* Creates a promise that is considered done if either all provided promises are successful or one fails. If all provided
* promises are successful this promise resolves with a `List<V>` of all the results. The order if the items in the list
* is the same order as the provided promises.
*
* If one or multiple promises result in failure this promise fails too. The error value of the first promise that fails
* will be the cause of fail of this promise. If [cancelOthersOnError] is `true` it is attempted to cancel the execution of
* the other promises.
*
* If provided no promises are provided an empty successful promise is returned.
*
* @param promises the promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnError whether an error of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> all(vararg promises: Promise<V, Exception>,
context: Context = Kovenant.context,
cancelOthersOnError: Boolean = true): Promise<List<V>, Exception> {
return when (promises.size) {
0 -> Promise.ofSuccess(listOf(), context)
else -> concreteAll(promises = *promises, context = context, cancelOthersOnError = cancelOthersOnError)
}
}
/**
* Creates a promise that is considered done if either all provided promises are successful or one fails.
*
* Creates a promise that is considered done if either all provided promises are successful or one fails. If all provided
* promises are successful this promise resolves with a `List<V>` of all the results. The order if the items in the list
* is the same order as the provided promises.
*
* If one or multiple promises result in failure this promise fails too. The error value of the first promise that fails
* will be the cause of fail of this promise. If [cancelOthersOnError] is `true` it is attempted to cancel the execution of
* the other promises.
*
* If provided no promises are provided an empty successful promise is returned.
*
* @param promises the List of promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnError whether an error of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> all(promises: List<Promise<V, Exception>>,
context: Context = Kovenant.context,
cancelOthersOnError: Boolean = true): Promise<List<V>, Exception> {
return when (promises.size) {
0 -> Promise.ofSuccess(listOf(), context)
else -> concreteAll(promises = promises, context = context, cancelOthersOnError = cancelOthersOnError)
}
}
/**
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
*
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
* If any of the provided promises is successful this promise resolves successful with that result.
* If [cancelOthersOnSuccess] is `true` it is attempted to cancel the execution of the other promises.
*
* If all promises result in failure this promise fails too with a `List` containing all failures. The order if the
* items in the list is the same order as the provided promises.
*
* If provided no promises are provided an empty failed promise is returned.
*
* @param promises the promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnSuccess whether a success of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> any(vararg promises: Promise<V, Exception>,
context: Context = Kovenant.context,
cancelOthersOnSuccess: Boolean = true): Promise<V, List<Exception>> {
return when (promises.size) {
0 -> Promise.ofFail(listOf(), context)
else -> concreteAny(promises = *promises, context = context, cancelOthersOnSuccess = cancelOthersOnSuccess)
}
}
/**
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
*
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
* If any of the provided promises is successful this promise resolves successful with that result.
* If [cancelOthersOnSuccess] is `true` it is attempted to cancel the execution of the other promises.
*
* If all promises result in failure this promise fails too with a `List` containing all failures. The order if the
* items in the list is the same order as the provided promises.
*
* If provided no promises are provided an empty failed promise is returned.
*
* @param promises the List of promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnSuccess whether a success of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> any(promises: List<Promise<V, Exception>>,
context: Context = Kovenant.context,
cancelOthersOnSuccess: Boolean = true): Promise<V, List<Exception>> {
return when (promises.size) {
0 -> Promise.ofFail(listOf(), context)
else -> concreteAny(promises = promises, context = context, cancelOthersOnSuccess = cancelOthersOnSuccess)
}
} | mit | d93bf6987d3a5e11fff844ada71f179f | 55.76 | 134 | 0.734282 | 4.710491 | false | false | false | false |
mcmacker4/PBR-Test | src/main/kotlin/net/upgaming/pbrengine/gameobject/Entity.kt | 1 | 945 | package net.upgaming.pbrengine.gameobject
import net.upgaming.pbrengine.material.Material
import net.upgaming.pbrengine.models.Model
import org.joml.Matrix4f
import org.joml.Vector3f
import org.lwjgl.system.MemoryUtil
import java.nio.FloatBuffer
class Entity(val model: Model, val material: Material = Material.default(), val position: Vector3f = Vector3f(),
val rotation: Vector3f = Vector3f(), var scale: Float = 1f) {
private val mmBuffer = MemoryUtil.memAllocFloat(16)
fun getModelMatrixFB(): FloatBuffer {
mmBuffer.clear()
val matrix = Matrix4f()
.translate(position)
.rotate(rotation.x, 1f, 0f, 0f)
.rotate(rotation.y, 0f, 1f, 0f)
.rotate(rotation.z, 0f, 0f, 1f)
.scale(scale)
matrix.get(mmBuffer)
return mmBuffer
}
fun delete() {
MemoryUtil.memFree(mmBuffer)
}
} | apache-2.0 | 379d245a8c5b919d2f82a86e1ba14585 | 28.5625 | 112 | 0.631746 | 3.795181 | false | false | false | false |
charbgr/CliffHanger | cliffhanger/feature-movie-detail/src/main/kotlin/com/github/charbgr/cliffhanger/features/detail/MovieDetailActivity.kt | 1 | 2517 | package com.github.charbgr.cliffhanger.features.detail
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ProgressBar
import android.widget.TextView
import com.github.charbgr.cliffhanger.features.detail.arch.Presenter
import com.github.charbgr.cliffhanger.features.detail.arch.UiBinder
import com.github.charbgr.cliffhanger.features.detail.arch.View
import com.github.charbgr.cliffhanger.shared.views.imageview.MovieImageView
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
class MovieDetailActivity : AppCompatActivity(), View {
companion object Contract {
const val MOVIE_ID_EXTRA = "movie:detail:id"
}
internal lateinit var uiBinder: UiBinder
internal lateinit var presenter: Presenter
private val disposable: CompositeDisposable = CompositeDisposable()
lateinit var backdrop: MovieImageView
lateinit var title: TextView
lateinit var poster: MovieImageView
lateinit var progressBar: ProgressBar
lateinit var overview: TextView
lateinit var tagline: TextView
lateinit var directedBy: TextView
lateinit var director: TextView
lateinit var chronology: TextView
lateinit var duration: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_movie_detail)
findViews()
uiBinder = UiBinder(this)
setUpPresenter()
uiBinder.onCreateView()
}
override fun onDestroy() {
presenter.destroy()
disposable.clear()
super.onDestroy()
}
private fun setUpPresenter() {
presenter = Presenter()
with(presenter) {
init(this@MovieDetailActivity)
bindIntents()
renders()
.subscribe { uiBinder.render(it) }
.addTo(disposable)
}
}
private fun findViews() {
backdrop = findViewById(R.id.movie_detail_backdrop)
title = findViewById(R.id.movie_detail_title)
poster = findViewById(R.id.movie_detail_poster)
overview = findViewById(R.id.movie_detail_overview)
tagline = findViewById(R.id.movie_detail_tagline)
directedBy = findViewById(R.id.movie_detail_directed_by)
director = findViewById(R.id.movie_detail_director)
chronology = findViewById(R.id.movie_detail_chronology)
duration = findViewById(R.id.movie_detail_duration)
progressBar = findViewById(R.id.movie_detail_progressbar)
}
override fun fetchMovieIntent(): Observable<Int> = uiBinder.fetchMovieIntent()
}
| mit | e2a0867e8c2efdbe35a3ff01bcd80de4 | 31.269231 | 80 | 0.761621 | 4.408056 | false | false | false | false |
robinverduijn/gradle | .teamcity/common/BuildCache.kt | 1 | 1577 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package common
interface BuildCache {
fun gradleParameters(os: Os): List<String>
}
data class RemoteBuildCache(val url: String, val username: String = "%gradle.cache.remote.username%", val password: String = "%gradle.cache.remote.password%") : BuildCache {
override fun gradleParameters(os: Os): List<String> {
return listOf("--build-cache",
os.escapeKeyValuePair("-Dgradle.cache.remote.url", url),
os.escapeKeyValuePair("-Dgradle.cache.remote.username", username),
os.escapeKeyValuePair("-Dgradle.cache.remote.password", password)
)
}
}
val builtInRemoteBuildCacheNode = RemoteBuildCache("%gradle.cache.remote.url%")
object NoBuildCache : BuildCache {
override fun gradleParameters(os: Os): List<String> {
return emptyList()
}
}
private
fun Os.escapeKeyValuePair(key: String, value: String) = if (this == Os.windows) """$key="$value"""" else """"$key=$value""""
| apache-2.0 | 0d7cdabf7eb283578916d8af8f1030ec | 36.547619 | 173 | 0.698161 | 4.139108 | false | false | false | false |
charbgr/CliffHanger | cliffhanger/feature-home/src/main/kotlin/com/github/charbgr/cliffhanger/feature/home/arch/state/HomeStateReducer.kt | 1 | 1818 | package com.github.charbgr.cliffhanger.feature.home.arch.state
import com.github.charbgr.cliffhanger.domain.MovieCategory.NowPlaying
import com.github.charbgr.cliffhanger.domain.MovieCategory.Popular
import com.github.charbgr.cliffhanger.domain.MovieCategory.TopRated
import com.github.charbgr.cliffhanger.domain.MovieCategory.Upcoming
import com.github.charbgr.cliffhanger.feature.home.arch.HomeViewModel
class HomeStateReducer {
private val categoryReducer: CategoryStateReducer = CategoryStateReducer()
val reduce: (previousViewModel: HomeViewModel, partialChange: PartialChange) -> HomeViewModel =
{ previousViewModel, partialChange ->
when (partialChange.movieCategory) {
is TopRated -> {
val prevCategoryVM = previousViewModel.topRated
previousViewModel.copy(topRated = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is NowPlaying -> {
val prevCategoryVM = previousViewModel.nowPlaying
previousViewModel.copy(
nowPlaying = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is Upcoming -> {
val prevCategoryVM = previousViewModel.upcoming
previousViewModel.copy(upcoming = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is Popular -> {
val prevCategoryVM = previousViewModel.popular
previousViewModel.copy(popular = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
else -> {
previousViewModel
}
}
}
}
| mit | 9b1b3626e22819d3cdc2fb20eef234a4 | 41.27907 | 100 | 0.688669 | 5.826923 | false | false | false | false |
maballesteros/vertx3-kotlin-rest-jdbc-tutorial | step02/src/tutorial02.kt | 1 | 3062 | import com.google.gson.Gson
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.json.Json
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.BodyHandler
import java.util.*
import kotlin.reflect.KClass
/**
* Step02 - In memory REST User repository
*/
object Vertx3KotlinRestJdbcTutorial {
val gson = Gson()
@JvmStatic fun main(args: Array<String>) {
val port = 9000
val vertx = Vertx.vertx()
val server = vertx.createHttpServer()
val router = Router.router(vertx)
router.route().handler(BodyHandler.create()) // Required for RoutingContext.bodyAsString
val userService = MemoryUserService()
router.get("/:userId").handler { ctx ->
val userId = ctx.request().getParam("userId")
jsonResponse(ctx, userService.getUser(userId))
}
router.post("/").handler { ctx ->
val user = jsonRequest<User>(ctx, User::class)
jsonResponse(ctx, userService.addUser(user))
}
router.delete("/:userId").handler { ctx ->
val userId = ctx.request().getParam("userId")
jsonResponse(ctx, userService.remUser(userId))
}
server.requestHandler { router.accept(it) }.listen(port) {
if (it.succeeded()) println("Server listening at $port")
else println(it.cause())
}
}
fun jsonRequest<T>(ctx: RoutingContext, clazz: KClass<out Any>): T =
gson.fromJson(ctx.bodyAsString, clazz.java) as T
fun jsonResponse<T>(ctx: RoutingContext, future: Future<T>) {
future.setHandler {
if (it.succeeded()) {
val res = if (it.result() == null) "" else gson.toJson(it.result())
ctx.response().end(res)
} else {
ctx.response().setStatusCode(500).end(it.cause().toString())
}
}
}
}
//-----------------------------------------------------------------------------
// API
data class User(val id:String, val fname: String, val lname: String)
interface UserService {
fun getUser(id: String): Future<User>
fun addUser(user: User): Future<Unit>
fun remUser(id: String): Future<Unit>
}
//-----------------------------------------------------------------------------
// IMPLEMENTATION
class MemoryUserService(): UserService {
val _users = HashMap<String, User>()
init {
addUser(User("1", "user1_fname", "user1_lname"))
}
override fun getUser(id: String): Future<User> {
return if (_users.containsKey(id)) Future.succeededFuture(_users.getOrImplicitDefault(id))
else Future.failedFuture(IllegalArgumentException("Unknown user $id"))
}
override fun addUser(user: User): Future<Unit> {
_users.put(user.id, user)
return Future.succeededFuture()
}
override fun remUser(id: String): Future<Unit> {
_users.remove(id)
return Future.succeededFuture()
}
} | apache-2.0 | 5afc14011553d59a370818386b9a6c6f | 28.171429 | 98 | 0.590137 | 4.270572 | false | false | false | false |
artfable/telegram-api-java | src/main/kotlin/com/artfable/telegram/api/Poll.kt | 1 | 1088 | package com.artfable.telegram.api
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author aveselov
* @since 02/09/2020
*/
@JsonIgnoreProperties(ignoreUnknown = true)
data class Poll(
@JsonProperty("id") val id: String,
@JsonProperty("question") val question: String,
@JsonProperty("options") val options: List<PollOption>,
@JsonProperty("total_voter_count") val totalVoterCount: Int,
@JsonProperty("is_closed") val closed: Boolean,
@JsonProperty("is_anonymous") val anonymous: Boolean,
@JsonProperty("type") val type: PollType,
@JsonProperty("allows_multiple_answers") val allowsMultipleAnswers: Boolean,
@JsonProperty("correct_option_id") val correctOptionId: Int? = null,
@JsonProperty("explanation") val explanation: String? = null,
// TODO: explanation_entities Array of MessageEntity Optional.
@JsonProperty("open_period") val openPeriod: Long? = null,
@JsonProperty("close_date") val closeDate: Long? = null
) | mit | 0a52c754933e36518ca5e2d53e68b3db | 42.56 | 84 | 0.705882 | 4.266667 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/settings/background/load/RotatedImageFixing.kt | 2 | 1956 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings.background.load
import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import java.io.FileDescriptor
/**
* @author toastkidjp
*/
class RotatedImageFixing(
private val exifInterfaceFactory: (FileDescriptor) -> ExifInterface = { ExifInterface(it) }
) {
operator fun invoke(contentResolver: ContentResolver, bitmap: Bitmap?, imageUri: Uri): Bitmap? {
if (bitmap == null) {
return null
}
val openFileDescriptor = contentResolver.openFileDescriptor(imageUri, "r") ?: return bitmap
val exifInterface = exifInterfaceFactory(openFileDescriptor.fileDescriptor)
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotate(bitmap, 90F)
ExifInterface.ORIENTATION_ROTATE_180 -> rotate(bitmap, 180F)
ExifInterface.ORIENTATION_ROTATE_270 -> rotate(bitmap, 270F)
else -> bitmap
}
}
private fun rotate(bitmap: Bitmap, degree: Float): Bitmap? {
val matrix = Matrix()
matrix.postRotate(degree)
val rotatedBitmap = Bitmap.createBitmap(
bitmap,
0,
0,
bitmap.width,
bitmap.height,
matrix,
true
)
bitmap.recycle()
return rotatedBitmap
}
} | epl-1.0 | 7acca56c816e956b789bdd11a0c8927f | 31.616667 | 100 | 0.652863 | 4.964467 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt | 1 | 4415 | package eu.kanade.tachiyomi.ui.setting
import android.graphics.drawable.Drawable
import android.support.v7.preference.PreferenceGroup
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.util.LocaleHelper
import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference
import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog
import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.*
class SettingsSourcesController : SettingsController(),
SourceLoginDialog.Listener {
private val onlineSources by lazy { Injekt.get<SourceManager>().getOnlineSources() }
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.pref_category_sources
// Get the list of active language codes.
val activeLangsCodes = preferences.enabledLanguages().getOrDefault()
// Get a map of sources grouped by language.
val sourcesByLang = onlineSources.groupByTo(TreeMap(), { it.lang })
// Order first by active languages, then inactive ones
val orderedLangs = sourcesByLang.keys.filter { it in activeLangsCodes } +
sourcesByLang.keys.filterNot { it in activeLangsCodes }
orderedLangs.forEach { lang ->
val sources = sourcesByLang[lang].orEmpty().sortedBy { it.name }
// Create a preference group and set initial state and change listener
SwitchPreferenceCategory(context).apply {
preferenceScreen.addPreference(this)
title = LocaleHelper.getDisplayName(lang, context)
isPersistent = false
if (lang in activeLangsCodes) {
setChecked(true)
addLanguageSources(this, sources)
}
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.enabledLanguages().getOrDefault()
if (!checked) {
preferences.enabledLanguages().set(current - lang)
removeAll()
} else {
preferences.enabledLanguages().set(current + lang)
addLanguageSources(this, sources)
}
true
}
}
}
}
override fun setDivider(divider: Drawable?) {
super.setDivider(null)
}
/**
* Adds the source list for the given group (language).
*
* @param group the language category.
*/
private fun addLanguageSources(group: PreferenceGroup, sources: List<HttpSource>) {
val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault()
sources.forEach { source ->
val sourcePreference = LoginCheckBoxPreference(group.context, source).apply {
val id = source.id.toString()
title = source.name
key = getSourceKey(source.id)
isPersistent = false
isChecked = id !in hiddenCatalogues
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.hiddenCatalogues().getOrDefault()
preferences.hiddenCatalogues().set(if (checked)
current - id
else
current + id)
true
}
setOnLoginClickListener {
val dialog = SourceLoginDialog(source)
dialog.targetController = this@SettingsSourcesController
dialog.showDialog(router)
}
}
group.addPreference(sourcePreference)
}
}
override fun loginDialogClosed(source: LoginSource) {
val pref = findPreference(getSourceKey(source.id)) as? LoginCheckBoxPreference
pref?.notifyChanged()
}
private fun getSourceKey(sourceId: Long): String {
return "source_$sourceId"
}
} | apache-2.0 | e034a5a2f1ba422fbbba1e97da4ae203 | 36.423729 | 89 | 0.616082 | 5.491294 | false | false | false | false |
JimSeker/ui | RecyclerViews/RecyclerViewSwipeRefresh_kt/app/src/main/java/edu/cs4730/recyclerviewswiperefresh_kt/MainActivity.kt | 1 | 7584 | package edu.cs4730.recyclerviewswiperefresh_kt
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
class MainActivity : AppCompatActivity() {
lateinit var mRecyclerView: RecyclerView
lateinit var mAdapter: myAdapter
lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
var values = arrayOf(
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
"Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
"Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
"East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
"Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
"French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
"Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
"Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
"Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
"Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
"Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
"Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
"Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
"Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
"The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
"Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//setup the RecyclerView
mRecyclerView = findViewById(R.id.list)
mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.itemAnimator = DefaultItemAnimator()
//setup the adapter, which is myAdapter, see the code.
mAdapter = myAdapter(values, R.layout.my_row, this)
//add the adapter to the recyclerview
mRecyclerView.adapter = mAdapter
//SwipeRefreshlayout setup.
mSwipeRefreshLayout = findViewById(R.id.activity_main_swipe_refresh_layout)
//setup some colors for the refresh circle.
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue)
//now setup the swiperefrestlayout listener where the main work is done.
mSwipeRefreshLayout.setOnRefreshListener {
//where we call the refresher parts. normally some kind of networking async task or web service.
// For demo purpose, the code in the refreshslower method so it will take a couple of seconds
//otherwise, the task or service would just be called here.
refreshslower() //this will be slower, for the demo.
}
//setup left/right swipes on the cardviews
val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback =
object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
//likely allows to for animations? or moving items in the view I think.
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
//called when it has been animated off the screen. So item is no longer showing.
//use ItemtouchHelper.X to find the correct one.
if (direction == ItemTouchHelper.RIGHT) {
//Toast.makeText(getBaseContext(),"Right?", Toast.LENGTH_SHORT).show();
val item =
viewHolder.absoluteAdapterPosition //think this is where in the array it is.
mAdapter.removeitem(item)
}
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(mRecyclerView)
}
/**
* so this is just for demo purposed and will wait a specified time the last numbere there
* listed in milliseconds. so 1.5 seconds is 1500. make it longer to see more colors in
* the refreshing circle.
*/
fun refreshslower() {
Handler().postDelayed({
//update the listview with new values.
mAdapter.randomlist() //normally something better then a random update.
mAdapter.notifyDataSetChanged() //cause the recyclerview to update.
mSwipeRefreshLayout.isRefreshing = false //turn of the refresh.
}, 2500)
}
} | apache-2.0 | 9caca58800914fe2068ce623644bb7eb | 58.257813 | 109 | 0.6399 | 3.706745 | false | false | false | false |
abdodaoud/Merlin | app/src/main/java/com/abdodaoud/merlin/extensions/ExtensionUtils.kt | 1 | 929 | package com.abdodaoud.merlin.extensions
import android.text.format.DateUtils
import java.text.DateFormat
import java.util.*
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
fun Long.maxDate(currentPage: Int = 1): Long {
if (currentPage == 1) return this
return this.minDate(currentPage-1).past()
}
fun Long.minDate(currentPage: Int = 1): Long {
return this.future().past(currentPage * 10)
}
fun Long.zeroedTime(): Long {
return this - (this % DateUtils.DAY_IN_MILLIS)
}
fun Long.past(days: Int = 1): Long {
return this - (days * DateUtils.DAY_IN_MILLIS)
}
fun Long.future(days: Int = 1): Long {
return this + (days * DateUtils.DAY_IN_MILLIS)
}
fun String.parseMessage(): String {
return "\"" + this + "\"" + " - discover more facts through Merlin https://goo.gl/KQJPmJ"
} | mit | c52759021530497179ca05cc8f05c942 | 25.571429 | 93 | 0.692142 | 3.428044 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/data/source/db/ToDoDatabase.kt | 1 | 908 | package com.airbnb.mvrx.todomvrx.data.source.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.airbnb.mvrx.todomvrx.data.Task
/**
* The Room Database that contains the Task table.
*/
@Database(entities = [Task::class], version = 2)
abstract class ToDoDatabase : RoomDatabase() {
abstract fun taskDao(): TasksDao
companion object {
private var INSTANCE: ToDoDatabase? = null
private val lock = Any()
fun getInstance(context: Context): ToDoDatabase {
synchronized(lock) {
if (INSTANCE == null) {
INSTANCE = Room
.databaseBuilder(context.applicationContext, ToDoDatabase::class.java, "Tasks.db")
.build()
}
return INSTANCE!!
}
}
}
}
| apache-2.0 | a3cebc137001e7cc10d38d1cc3b4016a | 25.705882 | 106 | 0.605727 | 4.680412 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/home/bundles/appcoins/EarnAppCoinsViewHolder.kt | 1 | 3351 | package cm.aptoide.pt.home.bundles.appcoins
import android.content.Context.WINDOW_SERVICE
import android.graphics.Rect
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cm.aptoide.aptoideviews.skeleton.Skeleton
import cm.aptoide.aptoideviews.skeleton.applySkeleton
import cm.aptoide.pt.R
import cm.aptoide.pt.dataprovider.model.v7.Type
import cm.aptoide.pt.home.bundles.base.AppBundle
import cm.aptoide.pt.home.bundles.base.AppBundleViewHolder
import cm.aptoide.pt.home.bundles.base.HomeBundle
import cm.aptoide.pt.home.bundles.base.HomeEvent
import cm.aptoide.pt.utils.AptoideUtils
import kotlinx.android.synthetic.main.bundle_earn_appcoins.view.*
import rx.subjects.PublishSubject
import java.text.DecimalFormat
class EarnAppCoinsViewHolder(val view: View,
decimalFormatter: DecimalFormat,
val uiEventsListener: PublishSubject<HomeEvent>) :
AppBundleViewHolder(view) {
private var adapter: EarnAppCoinsListAdapter =
EarnAppCoinsListAdapter(decimalFormatter, uiEventsListener)
private var skeleton: Skeleton? = null
init {
val layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.HORIZONTAL, false)
itemView.apps_list.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State) {
val margin = AptoideUtils.ScreenU.getPixelsForDip(8, view.resources)
val marginBottom = AptoideUtils.ScreenU.getPixelsForDip(4, view.resources)
outRect.set(margin, margin, 0, marginBottom)
}
})
itemView.apps_list.layoutManager = layoutManager
itemView.apps_list.adapter = adapter
itemView.apps_list.isNestedScrollingEnabled = false
itemView.apps_list.setHasFixedSize(true)
val resources = view.context.resources
val windowManager = view.context.getSystemService(WINDOW_SERVICE) as WindowManager
skeleton = itemView.apps_list.applySkeleton(R.layout.earn_appcoins_item_skeleton,
Type.APPCOINS_ADS.getPerLineCount(resources, windowManager) * 3)
}
override fun setBundle(homeBundle: HomeBundle?, position: Int) {
if (homeBundle !is AppBundle) {
throw IllegalStateException(this.javaClass.name + " is getting non AppBundle instance!")
}
if (homeBundle.content == null) {
skeleton?.showSkeleton()
} else {
skeleton?.showOriginal()
adapter.updateBundle(homeBundle, position)
itemView.apps_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dx > 0) {
uiEventsListener.onNext(
HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.SCROLL_RIGHT))
}
}
})
itemView.setOnClickListener {
uiEventsListener.onNext(
HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.APPC_KNOW_MORE))
}
itemView.see_more_btn.setOnClickListener {
uiEventsListener.onNext(HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.MORE))
}
}
}
} | gpl-3.0 | 319945691968ad46ee86052661768c9c | 39.385542 | 96 | 0.729633 | 4.522267 | false | false | false | false |
BoD/android-wear-color-picker | library/src/main/kotlin/org/jraf/android/androidwearcolorpicker/ColorPickActivity.kt | 1 | 8516 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2015-present Benoit 'BoD' Lubek ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jraf.android.androidwearcolorpicker
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewAnimationUtils
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.annotation.ColorInt
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.wear.widget.CurvingLayoutCallback
import androidx.wear.widget.WearableLinearLayoutManager
import org.jraf.android.androidwearcolorpicker.databinding.AwcpColorPickBinding
class ColorPickActivity : Activity() {
companion object {
const val EXTRA_RESULT = "EXTRA_RESULT"
const val EXTRA_OLD_COLOR = "EXTRA_OLD_COLOR"
const val EXTRA_COLORS = "EXTRA_COLORS"
/**
* Extracts the picked color from an onActivityResult data Intent.
*
* @param data The intent passed to onActivityResult.
* @return The resulting picked color, or 0 if the result could not be found in the given Intent.
*/
@Suppress("unused")
fun getPickedColor(data: Intent) = data.getIntExtra(EXTRA_RESULT, 0)
}
private lateinit var binding: AwcpColorPickBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.awcp_color_pick)!!
binding.rclList.setHasFixedSize(true)
binding.rclList.isEdgeItemsCenteringEnabled = true
// Apply an offset + scale on the items depending on their distance from the center (only for Round screens)
if (resources.configuration.isScreenRound) {
binding.rclList.layoutManager =
WearableLinearLayoutManager(this, object : CurvingLayoutCallback(this) {
override fun onLayoutFinished(child: View, parent: RecyclerView) {
super.onLayoutFinished(child, parent)
val childTop = child.y + child.height / 2f
val childOffsetFromCenter = childTop - parent.height / 2f
child.pivotX = 1f
child.rotation = -15f * (childOffsetFromCenter / parent.height)
}
})
// Also snap
LinearSnapHelper().attachToRecyclerView(binding.rclList)
} else {
// Square screen: no scale effect and no snapping
binding.rclList.layoutManager = WearableLinearLayoutManager(this)
}
val adapter = ColorAdapter(this, intent.getIntArrayExtra(EXTRA_COLORS)) { colorArgb, clickedView ->
setResult(RESULT_OK, Intent().putExtra(EXTRA_RESULT, colorArgb))
binding.vieRevealedColor.setBackgroundColor(colorArgb)
val clickedViewRect = Rect()
clickedView.getGlobalVisibleRect(clickedViewRect)
val finalRadius = Math.hypot(
binding.vieRevealedColor.width.toDouble(),
binding.vieRevealedColor.height.toDouble()
).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(
binding.vieRevealedColor,
clickedViewRect.centerX(),
clickedViewRect.centerY(),
clickedViewRect.width() / 2F - 4,
finalRadius
)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
finish()
}
})
binding.vieRevealedColor.visibility = View.VISIBLE
anim.start()
}
binding.rclList.adapter = adapter
val initialPosition = adapter.getMiddlePosition() +
if (intent?.hasExtra(EXTRA_OLD_COLOR) != true) 0
else adapter.colorToPositions(
intent!!.getIntExtra(
EXTRA_OLD_COLOR,
Color.WHITE
)
).first
binding.rclList.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val oldColor = intent!!.getIntExtra(EXTRA_OLD_COLOR, Color.WHITE)
binding.vieRevealedColor.setBackgroundColor(oldColor)
binding.vieRevealedColor.visibility = View.VISIBLE
val selectedViewIdx = adapter.colorToPositions(oldColor).second
val selectedView = (binding.rclList.layoutManager!!.findViewByPosition(0) as ViewGroup).getChildAt(selectedViewIdx)
val selectedViewRect = Rect()
selectedView.getGlobalVisibleRect(selectedViewRect)
ViewAnimationUtils.createCircularReveal(
binding.vieRevealedColor,
selectedViewRect.centerX(),
selectedViewRect.centerY(),
Math.hypot(
binding.vieRevealedColor.width.toDouble(),
binding.vieRevealedColor.height.toDouble()
).toFloat(),
selectedViewRect.width() / 2F - 4
).apply {
startDelay = 300
duration = 500
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.vieRevealedColor.visibility = View.INVISIBLE
}
})
}
.start()
// For some unknown reason, this must be posted - if done right away, it doesn't work
Handler(Looper.getMainLooper()).post {
binding.rclList.scrollToPosition(initialPosition)
binding.rclList.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
@Suppress("unused")
class IntentBuilder {
private var oldColor: Int = Color.WHITE
private var colors: List<Int>? = null
/**
* Sets the initial value for the picked color.
* The default value is white.
*
* @param oldColor The old color to use as an ARGB int (the alpha component is ignored).
* @return This builder.
*/
fun oldColor(@ColorInt oldColor: Int): IntentBuilder {
this.oldColor = oldColor
return this
}
/**
* Sets the colors to display in the picker.
* This is optional - if not specified, all the colors of the rainbow will be used.
*
* @param colors The colors to display as ARGB ints (the alpha component is ignored).
* @return This builder.
*/
fun colors(colors: List<Int>): IntentBuilder {
this.colors = colors
return this
}
/**
* Build the resulting Intent.
*
* @param context The context to use to build the Intent.
* @return The build Intent.
*/
fun build(context: Context): Intent = Intent(context, ColorPickActivity::class.java)
.putExtra(EXTRA_OLD_COLOR, oldColor)
.putExtra(EXTRA_COLORS, colors?.toIntArray())
}
} | apache-2.0 | ce02635d8cc27ebc862a6817cf7658f7 | 38.613953 | 131 | 0.601926 | 5.329161 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/main/kotlin/glimpse/Matrices.kt | 1 | 4473 | package glimpse
/**
* Returns a frustum projection [Matrix].
* The [left] to [right], [top] to [bottom] rectangle is the [near] clipping plane of the frustum.
*/
fun frustumProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Matrix {
val width = right - left
val height = top - bottom
val depth = near - far
return Matrix(listOf(
2f * near / width, 0f, 0f, 0f,
0f, 2f * near / height, 0f, 0f,
(right + left) / width, (top + bottom) / height, (far + near) / depth, -1f,
0f, 0f, 2f * far * near / depth, 0f))
}
/**
* Returns a perspective projection [Matrix].
*
* @param fovY Field of view angle for Y-axis (viewport height axis).
* @param aspect Width aspect ratio against height.
* @param near Near clipping plane distance.
* @param far Far clipping plane distance.
*/
fun perspectiveProjectionMatrix(fovY: Angle, aspect: Float, near: Float, far: Float): Matrix {
val top = tan(fovY / 2f) * near
val right = aspect * top
val depth = near - far
return Matrix(listOf(
1f / right, 0f, 0f, 0f,
0f, 1f / top, 0f, 0f,
0f, 0f, (near + far) / depth, -1f,
0f, 0f, 2 * near * far / depth, 0f))
}
/**
* Returns an orthographic projection [Matrix].
*/
fun orthographicProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Matrix {
val width = right - left
val height = top - bottom
val depth = far - near
return Matrix(listOf(
2f / width, 0f, 0f, 0f,
0f, 2f / height, 0f, 0f,
0f, 0f, -2f / depth, 0f,
-(right + left) / width, -(top + bottom) / height, -(near + far) / depth, 1f))
}
/**
* Returns a look-at view [Matrix].
*/
fun lookAtViewMatrix(eye: Point, center: Point, up: Vector): Matrix {
val f = (eye to center).normalize
val s = (f * up).normalize
val u = s * f
return Matrix(listOf(
s.x, u.x, -f.x, 0f,
s.y, u.y, -f.y, 0f,
s.z, u.z, -f.z, 0f,
0f, 0f, 0f, 1f)) * translationMatrix(-eye.toVector())
}
/**
* Returns a transformation [Matrix] for a translation by an [vector].
*/
fun translationMatrix(vector: Vector): Matrix {
val (x, y, z) = vector
return Matrix(listOf(
1f, 0f, 0f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
x, y, z, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around an [axis].
*/
fun rotationMatrix(axis: Vector, angle: Angle): Matrix {
val (x, y, z) = axis.normalize
val sin = sin(angle)
val cos = cos(angle)
val nCos = 1f - cos(angle)
return Matrix(listOf(
cos + x * x * nCos, x * y * nCos + z * sin, x * z * nCos - y * sin, 0f,
x * y * nCos - z * sin, cos + y * y * nCos, y * z * nCos + x * sin, 0f,
x * z * nCos + y * sin, y * z * nCos - x * sin, cos + z * z * nCos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around X axis.
*/
fun rotationMatrixX(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
1f, 0f, 0f, 0f,
0f, cos, sin, 0f,
0f, -sin, cos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around Y axis.
*/
fun rotationMatrixY(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
cos, 0f, -sin, 0f,
0f, 1f, 0f, 0f,
sin, 0f, cos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around Z axis.
*/
fun rotationMatrixZ(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
cos, sin, 0f, 0f,
-sin, cos, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for uniform scaling.
*/
fun scalingMatrix(scale: Float): Matrix = scalingMatrix(scale, scale, scale)
/**
* Returns a transformation [Matrix] for scaling.
*/
fun scalingMatrix(x: Float = 1f, y: Float = 1f, z: Float = 1f): Matrix =
Matrix(listOf(
x, 0f, 0f, 0f,
0f, y, 0f, 0f,
0f, 0f, z, 0f,
0f, 0f, 0f, 1f))
/**
* Returns a transformation [Matrix] for reflection through a plane,
* defined by a [normal] vector and a [point] on the plane.
*/
fun reflectionMatrix(normal: Vector, point: Point): Matrix {
val (a, b, c) = normal.normalize
val d = -point.toVector() dot (normal.normalize)
return Matrix(listOf(
1f - 2f * a * a, -2f * b * a, -2f * c * a, 0f,
-2f * a * b, 1f - 2f * b * b, -2f * c * b, 0f,
-2f * a * c, -2f * b * c, 1f - 2f * c * c, 0f,
-2f * a * d, -2f * b * d, -2f * c * d, 1f))
}
| apache-2.0 | 4192e5761a4ef17f3afe7343dabc1019 | 26.95625 | 121 | 0.606752 | 2.605125 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/common/MyExoPlayerView.kt | 1 | 13552 | package com.nutrition.express.common
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.widget.*
import androidx.annotation.AttrRes
import androidx.annotation.StyleRes
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.view.SimpleDraweeView
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.video.VideoListener
import com.nutrition.express.R
import com.nutrition.express.application.toast
import com.nutrition.express.databinding.ItemVideoControlBinding
import com.nutrition.express.model.api.bean.BaseVideoBean
import com.nutrition.express.ui.video.VideoPlayerActivity
import com.nutrition.express.util.dp2Pixels
import java.util.*
class MyExoPlayerView : FrameLayout {
private val formatBuilder: StringBuilder = StringBuilder()
private val formatter: Formatter = Formatter(formatBuilder, Locale.getDefault())
private lateinit var uri: Uri
private var player: SimpleExoPlayer? = null
private var dragging = false
private var isConnected = false
private val showTimeoutMs = 3000L
private val progressBarMax = 1000
private var controlBinding: ItemVideoControlBinding =
ItemVideoControlBinding.inflate(LayoutInflater.from(context), this, true)
private var videoView: TextureView
private lateinit var thumbnailView: SimpleDraweeView
private lateinit var loadingBar: ProgressBar
private var playView: ImageView
private var leftTime: TextView
private val videoListener = object : VideoListener {
override fun onRenderedFirstFrame() {
thumbnailView.visibility = View.GONE
}
}
private val eventListener = object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
Player.STATE_BUFFERING -> loadingBar.visibility = View.VISIBLE
Player.STATE_ENDED -> {
show()
loadingBar.visibility = View.GONE
keepScreenOn = false
}
Player.STATE_READY -> {
loadingBar.visibility = View.GONE
keepScreenOn = true
}
Player.STATE_IDLE -> {
loadingBar.visibility = View.GONE
keepScreenOn = false
}
}
updatePlayPauseButton()
updateProgress()
updateLeftTime()
}
override fun onPlayerError(error: ExoPlaybackException) {
disconnect()
context.toast(R.string.video_play_error)
}
}
private val updateProgressAction = Runnable {
updateProgress()
}
private val hideAction = Runnable {
hide()
}
private val updateTimeAction = Runnable {
updateLeftTime()
}
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@TargetApi(21)
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int, @StyleRes defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
init {
controlBinding.videoControllerProgress.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) {
controlBinding.timeCurrent.text = stringForTime(positionValue(progress))
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
removeCallbacks(hideAction)
dragging = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
player?.seekTo(positionValue(seekBar.progress))
hideAfterTimeout()
dragging = false
}
})
controlBinding.videoControllerProgress.max = progressBarMax
controlBinding.videoFullscreen.setOnClickListener {
val playerIntent = Intent(context, VideoPlayerActivity::class.java)
playerIntent.putExtra("uri", uri)
player?.let {
playerIntent.putExtra("position", it.currentPosition)
playerIntent.putExtra("windowIndex", it.currentWindowIndex)
}
playerIntent.putExtra("rotation", width > height)
context.startActivity(playerIntent)
disconnect()
}
videoView = TextureView(context)
val videoParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
videoView.layoutParams = videoParams
videoView.setOnClickListener {
if (isConnected) {
show()
} else {
connect()
}
}
thumbnailView = SimpleDraweeView(context)
val thumbParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
val hierarchy = GenericDraweeHierarchyBuilder(resources)
.setPlaceholderImage(R.color.loading_color)
.build()
thumbnailView.hierarchy = hierarchy
thumbnailView.layoutParams = thumbParams
loadingBar = ProgressBar(context, null, android.R.attr.progressBarStyle)
val loadingParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
loadingParams.gravity = Gravity.CENTER
loadingBar.layoutParams = loadingParams
loadingBar.visibility = View.GONE
playView = ImageView(context)
val playParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
playParams.gravity = Gravity.CENTER
playView.layoutParams = playParams
val padding = dp2Pixels(context, 24)
playView.setPadding(padding, padding, padding, padding)
playView.setOnClickListener {
player?.let {
if (it.playbackState == ExoPlayer.STATE_ENDED) {
it.seekTo(0)
it.playWhenReady = true
} else {
it.playWhenReady = !it.playWhenReady
}
}
}
leftTime = TextView(context)
val leftParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
leftParams.gravity = Gravity.BOTTOM
leftParams.bottomMargin = padding / 2
leftParams.leftMargin = padding / 2
leftTime.layoutParams = leftParams
leftTime.setTextColor(Color.WHITE)
leftTime.visibility = View.GONE
addView(videoView, 0)
addView(thumbnailView, 1)
addView(loadingBar, 2)
addView(playView, 3)
addView(leftTime, 4)
}
fun bindVideo(video: BaseVideoBean) {
uri = video.sourceUri
var params = layoutParams
if (params == null) {
params = LayoutParams(video.getWidth(), video.getHeight())
}
params.width = video.getWidth()
params.height = video.getHeight()
layoutParams = params
thumbnailView.setImageURI(video.getThumbnailUri(), context)
thumbnailView.visibility = View.VISIBLE
hide()
disconnect()
}
fun setPlayerClickable(enable: Boolean) {
videoView.isClickable = enable
}
fun performPlayerClick() {
if (isConnected) {
show()
} else {
connect()
}
}
private fun connect() {
val player = MyExoPlayer.preparePlayer(uri) {
disconnect()
}
player.setVideoTextureView(videoView)
player.addListener(eventListener)
player.addVideoListener(videoListener)
player.playWhenReady = true
this.player = player
isConnected = true
}
private fun disconnect() {
player?.let {
it.removeListener(eventListener)
it.removeVideoListener(videoListener)
it.stop()
player = null
}
thumbnailView.visibility = View.VISIBLE
loadingBar.visibility = View.GONE
isConnected = false
}
/**
* Shows the controller
*/
private fun show() {
if (isControllerVisible()) {
hide()
} else {
controlBinding.videoControlLayout.visibility = View.VISIBLE
playView.visibility = View.VISIBLE
leftTime.visibility = View.GONE
updateAll()
}
// Call hideAfterTimeout even if already visible to reset the timeout.
hideAfterTimeout()
}
private fun hide() {
if (isControllerVisible()) {
controlBinding.videoControlLayout.visibility = View.GONE
playView.visibility = View.GONE
removeCallbacks(updateProgressAction)
removeCallbacks(hideAction)
updateLeftTime()
}
}
private fun updateLeftTime() {
if (!isConnected || !isAttachedToWindow) {
leftTime.visibility = View.GONE
return
}
if (isControllerVisible()) {
return
}
val duration: Long = player?.duration ?: 0L
val position: Long = player?.currentPosition ?: 0L
if (duration == C.TIME_UNSET) {
return
}
leftTime.visibility = View.VISIBLE
leftTime.text = stringForTime(duration - position)
leftTime.postDelayed(updateTimeAction, 1000)
}
private fun hideAfterTimeout() {
removeCallbacks(hideAction)
if (isAttachedToWindow) {
postDelayed(hideAction, showTimeoutMs)
}
}
private fun updateAll() {
updatePlayPauseButton()
updateProgress()
}
private fun updatePlayPauseButton() {
if (!isControllerVisible() || !isAttachedToWindow) {
return
}
val playing: Boolean = player?.playWhenReady == true && player?.playbackState != ExoPlayer.STATE_ENDED
val contentDescription = resources.getString(
if (playing) R.string.exo_controls_pause_description else R.string.exo_controls_play_description)
playView.contentDescription = contentDescription
playView.setImageResource(if (playing) R.drawable.exo_controls_pause else R.drawable.exo_controls_play)
}
private fun updateProgress() {
if (!isControllerVisible() || !isAttachedToWindow) {
return
}
val duration = player?.duration ?: 0
val position = player?.currentPosition ?: 0
controlBinding.time.text = stringForTime(duration)
if (!dragging) {
controlBinding.timeCurrent.text = stringForTime(position)
}
if (!dragging) {
controlBinding.videoControllerProgress.progress = progressBarValue(position)
}
val bufferedPosition = player?.bufferedPosition ?: 0
controlBinding.videoControllerProgress.secondaryProgress = progressBarValue(bufferedPosition)
// Remove scheduled updates.
removeCallbacks(updateProgressAction)
// Schedule an update if necessary.
val playbackState = player?.playbackState ?: Player.STATE_IDLE
if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) {
var delayMs: Long
if (player?.playWhenReady == true && playbackState == Player.STATE_READY) {
delayMs = 1000 - position % 1000
if (delayMs < 200) {
delayMs += 1000
}
} else {
delayMs = 1000
}
postDelayed(updateProgressAction, delayMs)
}
}
private fun isControllerVisible(): Boolean {
return controlBinding.videoControlLayout.visibility == View.VISIBLE
}
private fun stringForTime(timeMs: Long): String? {
var time = timeMs
if (time == C.TIME_UNSET) {
time = 0
}
val totalSeconds = (time + 500) / 1000
val seconds = totalSeconds % 60
val minutes = totalSeconds / 60 % 60
val hours = totalSeconds / 3600
formatBuilder.setLength(0)
return if (hours > 0)
formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
else
formatter.format("%02d:%02d", minutes, seconds).toString()
}
private fun progressBarValue(position: Long): Int {
val duration = player?.duration ?: C.TIME_UNSET
return if (duration == C.TIME_UNSET || duration == 0L) 0 else (position * progressBarMax / duration).toInt()
}
private fun positionValue(progress: Int): Long {
val duration = player?.duration ?: C.TIME_UNSET
return if (duration == C.TIME_UNSET || duration == 0L) 0 else (duration * progress / progressBarMax)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
hide()
disconnect()
}
} | apache-2.0 | 6f0d5e8ecfba0f0f31e0af1b3a9acffd | 34.479058 | 162 | 0.619318 | 5.356522 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/DeckOptionsActivity.kt | 1 | 35075 | /****************************************************************************************
* Copyright (c) 2009 Casey Link <[email protected]> *
* Copyright (c) 2012 Norbert Nagold <[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("DEPRECATION") // Migrate to AndroidX preferences #5019
package com.ichi2.anki
import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.os.Bundle
import android.preference.CheckBoxPreference
import android.preference.ListPreference
import android.preference.Preference
import android.preference.PreferenceScreen
import android.text.TextUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anim.ActivityTransitionAnimation.Direction.FADE
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.exception.ConfirmModSchemaException
import com.ichi2.anki.services.ReminderService
import com.ichi2.annotations.NeedsTest
import com.ichi2.async.TaskListenerWithContext
import com.ichi2.async.changeDeckConfiguration
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts
import com.ichi2.libanki.DeckConfig
import com.ichi2.libanki.utils.Time
import com.ichi2.libanki.utils.TimeManager
import com.ichi2.libanki.utils.set
import com.ichi2.preferences.NumberRangePreference
import com.ichi2.preferences.StepsPreference
import com.ichi2.preferences.TimePreference
import com.ichi2.themes.StyledProgressDialog
import com.ichi2.themes.Themes
import com.ichi2.themes.Themes.themeFollowsSystem
import com.ichi2.themes.Themes.updateCurrentTheme
import com.ichi2.ui.AppCompatPreferenceActivity
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.NamedJSONComparator
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.util.*
@NeedsTest("onCreate - to be done after preference migration (5019)")
@KotlinCleanup("lateinit wherever possible")
@KotlinCleanup("IDE lint")
class DeckOptionsActivity :
AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>() {
private lateinit var mOptions: DeckConfig
inner class DeckPreferenceHack : AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>.AbstractPreferenceHack() {
@Suppress("Deprecation")
lateinit var progressDialog: android.app.ProgressDialog
private val mListeners: MutableList<SharedPreferences.OnSharedPreferenceChangeListener> = LinkedList()
val deckOptionsActivity: DeckOptionsActivity
get() = this@DeckOptionsActivity
override fun cacheValues() {
Timber.i("DeckOptions - CacheValues")
try {
mOptions = col.decks.confForDid(deck.getLong("id"))
mValues.apply {
set("name", deck.getString("name"))
set("desc", deck.getString("desc"))
set("deckConf", deck.getString("conf"))
// general
set("maxAnswerTime", mOptions.getString("maxTaken"))
set("showAnswerTimer", parseTimerValue(mOptions).toString())
set("autoPlayAudio", mOptions.getBoolean("autoplay").toString())
set("replayQuestion", mOptions.optBoolean("replayq", true).toString())
}
// new
val newOptions = mOptions.getJSONObject("new")
mValues.apply {
set("newSteps", StepsPreference.convertFromJSON(newOptions.getJSONArray("delays")))
set("newGradIvl", newOptions.getJSONArray("ints").getString(0))
set("newEasy", newOptions.getJSONArray("ints").getString(1))
set("newFactor", (newOptions.getInt("initialFactor") / 10).toString())
set("newOrder", newOptions.getString("order"))
set("newPerDay", newOptions.getString("perDay"))
set("newBury", newOptions.optBoolean("bury", true).toString())
}
// rev
val revOptions = mOptions.getJSONObject("rev")
mValues.apply {
set("revPerDay", revOptions.getString("perDay"))
set("easyBonus", String.format(Locale.ROOT, "%.0f", revOptions.getDouble("ease4") * 100))
set("hardFactor", String.format(Locale.ROOT, "%.0f", revOptions.optDouble("hardFactor", 1.2) * 100))
set("revIvlFct", String.format(Locale.ROOT, "%.0f", revOptions.getDouble("ivlFct") * 100))
set("revMaxIvl", revOptions.getString("maxIvl"))
set("revBury", revOptions.optBoolean("bury", true).toString())
set("revUseGeneralTimeoutSettings", revOptions.optBoolean("useGeneralTimeoutSettings", true).toString())
set("revTimeoutAnswer", revOptions.optBoolean("timeoutAnswer", false).toString())
set("revTimeoutAnswerSeconds", revOptions.optInt("timeoutAnswerSeconds", 6).toString())
set("revTimeoutQuestionSeconds", revOptions.optInt("timeoutQuestionSeconds", 60).toString())
}
// lapse
val lapOptions = mOptions.getJSONObject("lapse")
mValues.apply {
set("lapSteps", StepsPreference.convertFromJSON(lapOptions.getJSONArray("delays")))
set("lapNewIvl", String.format(Locale.ROOT, "%.0f", lapOptions.getDouble("mult") * 100))
set("lapMinIvl", lapOptions.getString("minInt"))
set("lapLeechThres", lapOptions.getString("leechFails"))
set("lapLeechAct", lapOptions.getString("leechAction"))
// options group management
set("currentConf", col.decks.getConf(deck.getLong("conf"))!!.getString("name"))
}
// reminders
if (mOptions.has("reminder")) {
val reminder = mOptions.getJSONObject("reminder")
val reminderTime = reminder.getJSONArray("time")
mValues["reminderEnabled"] = reminder.getBoolean("enabled").toString()
mValues["reminderTime"] = String.format(
"%1$02d:%2$02d", reminderTime.getLong(0), reminderTime.getLong(1)
)
} else {
mValues["reminderEnabled"] = "false"
mValues["reminderTime"] = TimePreference.DEFAULT_VALUE
}
} catch (e: JSONException) {
Timber.e(e, "DeckOptions - cacheValues")
CrashReportService.sendExceptionReport(e, "DeckOptions: cacheValues")
UIUtils.showThemedToast(this@DeckOptionsActivity, [email protected](R.string.deck_options_corrupt, e.localizedMessage), false)
finish()
}
}
private fun parseTimerValue(options: DeckConfig): Boolean {
return DeckConfig.parseTimerOpt(options, true)
}
fun confChangeHandler(timbering: String, block: Collection.() -> Unit) {
launch(getCoroutineExceptionHandler(this@DeckOptionsActivity)) {
preConfChange()
Timber.d(timbering)
try {
withCol(block)
} finally {
// need to call postConfChange in finally because if withCol{} throws an exception,
// postConfChange would never get called and progress-bar will never get dismissed
postConfChange()
}
}
}
fun preConfChange() {
val res = deckOptionsActivity.resources
progressDialog = StyledProgressDialog.show(
deckOptionsActivity as Context, null,
res?.getString(R.string.reordering_cards), false
)
}
fun postConfChange() {
cacheValues()
deckOptionsActivity.buildLists()
deckOptionsActivity.updateSummaries()
progressDialog.dismiss()
// Restart to reflect the new preference values
deckOptionsActivity.restartActivity()
}
inner class Editor : AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>.AbstractPreferenceHack.Editor() {
override fun commit(): Boolean {
Timber.d("DeckOptions - commit() changes back to database")
try {
for ((key, value) in update.valueSet()) {
Timber.i("Change value for key '%s': %s", key, value)
when (key) {
"maxAnswerTime" -> mOptions.put("maxTaken", value)
"newFactor" -> mOptions.getJSONObject("new").put("initialFactor", value as Int * 10)
"newOrder" -> {
val newOrder: Int = (value as String).toInt()
// Sorting is slow, so only do it if we change order
val oldOrder = mOptions.getJSONObject("new").getInt("order")
if (oldOrder != newOrder) {
mOptions.getJSONObject("new").put("order", newOrder)
confChangeHandler("doInBackground - reorder") {
sched.resortConf(mOptions)
}
}
mOptions.getJSONObject("new").put("order", value.toInt())
}
"newPerDay" -> mOptions.getJSONObject("new").put("perDay", value)
"newGradIvl" -> {
val newInts = JSONArray() // [graduating, easy]
newInts.put(value)
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").getInt(1))
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").optInt(2, 7))
mOptions.getJSONObject("new").put("ints", newInts)
}
"newEasy" -> {
val newInts = JSONArray() // [graduating, easy]
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").getInt(0))
newInts.put(value)
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").optInt(2, 7))
mOptions.getJSONObject("new").put("ints", newInts)
}
"newBury" -> mOptions.getJSONObject("new").put("bury", value)
"revPerDay" -> mOptions.getJSONObject("rev").put("perDay", value)
"easyBonus" -> mOptions.getJSONObject("rev").put("ease4", (value as Int / 100.0f).toDouble())
"hardFactor" -> mOptions.getJSONObject("rev").put("hardFactor", (value as Int / 100.0f).toDouble())
"revIvlFct" -> mOptions.getJSONObject("rev").put("ivlFct", (value as Int / 100.0f).toDouble())
"revMaxIvl" -> mOptions.getJSONObject("rev").put("maxIvl", value)
"revBury" -> mOptions.getJSONObject("rev").put("bury", value)
"revUseGeneralTimeoutSettings" -> mOptions.getJSONObject("rev").put("useGeneralTimeoutSettings", value)
"revTimeoutAnswer" -> mOptions.getJSONObject("rev").put("timeoutAnswer", value)
"revTimeoutAnswerSeconds" -> mOptions.getJSONObject("rev").put("timeoutAnswerSeconds", value)
"revTimeoutQuestionSeconds" -> mOptions.getJSONObject("rev").put("timeoutQuestionSeconds", value)
"lapMinIvl" -> mOptions.getJSONObject("lapse").put("minInt", value)
"lapLeechThres" -> mOptions.getJSONObject("lapse").put("leechFails", value)
"lapLeechAct" -> mOptions.getJSONObject("lapse").put("leechAction", (value as String).toInt())
"lapNewIvl" -> mOptions.getJSONObject("lapse").put("mult", (value as Int / 100.0f).toDouble())
"showAnswerTimer" -> mOptions.put("timer", if (value as Boolean) 1 else 0)
"autoPlayAudio" -> mOptions.put("autoplay", value)
"replayQuestion" -> mOptions.put("replayq", value)
"desc" -> {
deck.put("desc", value)
col.decks.save(deck)
}
"newSteps" -> mOptions.getJSONObject("new").put("delays", StepsPreference.convertToJSON((value as String)))
"lapSteps" -> mOptions.getJSONObject("lapse").put("delays", StepsPreference.convertToJSON((value as String)))
// TODO: Extract out deckConf, confReset, remConf and confSetSubdecks to a function. They are overall similar.
"deckConf" -> {
val newConfId: Long = (value as String).toLong()
confChangeHandler("change Deck configuration") {
mOptions = decks.getConf(newConfId)!!
changeDeckConfiguration(deck, mOptions, this)
}
}
"confRename" -> {
val newName = value as String
if (!TextUtils.isEmpty(newName)) {
mOptions.put("name", newName)
}
}
"confReset" -> if (value as Boolean) {
// reset configuration
confChangeHandler("doInBackgroundConfReset") {
decks.restoreToDefault(mOptions)
save()
}
}
"confAdd" -> {
val newName = value as String
if (!TextUtils.isEmpty(newName)) {
// New config clones current config
val id = col.decks.confId(newName, mOptions.toString())
deck.put("conf", id)
col.decks.save(deck)
}
}
"confRemove" -> if (mOptions.getLong("id") == 1L) {
// Don't remove the options group if it's the default group
UIUtils.showThemedToast(
this@DeckOptionsActivity,
resources.getString(R.string.default_conf_delete_error), false
)
} else {
// Remove options group, handling the case where the user needs to confirm full sync
try {
remConf()
} catch (e: ConfirmModSchemaException) {
e.log()
// Libanki determined that a full sync will be required, so confirm with the user before proceeding
// TODO : Use ConfirmationDialog DialogFragment -- not compatible with PreferenceActivity
MaterialDialog(this@DeckOptionsActivity).show {
message(R.string.full_sync_confirmation)
positiveButton(R.string.dialog_ok) {
col.modSchemaNoCheck()
try {
remConf()
} catch (cmse: ConfirmModSchemaException) {
// This should never be reached as we just forced modSchema
throw RuntimeException(cmse)
}
}
negativeButton(R.string.dialog_cancel)
}
}
}
"confSetSubdecks" -> if (value as Boolean) {
launch(getCoroutineExceptionHandler(this@DeckOptionsActivity)) {
preConfChange()
try {
withCol {
Timber.d("confSetSubdecks")
val children = col.decks.children(deck.getLong("id"))
for (childDid in children.values) {
val child = col.decks.get(childDid)
if (child.isDyn) continue
changeDeckConfiguration(deck, mOptions, col)
}
}
} finally {
postConfChange()
}
}
}
"reminderEnabled" -> {
val reminder = JSONObject()
reminder.put("enabled", value)
if (mOptions.has("reminder")) {
reminder.put("time", mOptions.getJSONObject("reminder").getJSONArray("time"))
} else {
reminder.put(
"time",
JSONArray()
.put(TimePreference.parseHours(TimePreference.DEFAULT_VALUE))
.put(TimePreference.parseMinutes(TimePreference.DEFAULT_VALUE))
)
}
mOptions.put("reminder", reminder)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val reminderIntent = CompatHelper.compat.getImmutableBroadcastIntent(
applicationContext,
mOptions.getLong("id").toInt(),
Intent(applicationContext, ReminderService::class.java).putExtra(
ReminderService.EXTRA_DECK_OPTION_ID, mOptions.getLong("id")
),
0
)
alarmManager.cancel(reminderIntent)
if (value as Boolean) {
val calendar = reminderToCalendar(TimeManager.time, reminder)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
reminderIntent
)
}
}
"reminderTime" -> {
val reminder = JSONObject()
reminder.put("enabled", true)
reminder.put(
"time",
JSONArray().put(TimePreference.parseHours((value as String)))
.put(TimePreference.parseMinutes(value))
)
mOptions.put("reminder", reminder)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val reminderIntent = CompatHelper.compat.getImmutableBroadcastIntent(
applicationContext,
mOptions.getLong("id").toInt(),
Intent(
applicationContext,
ReminderService::class.java
).putExtra(
ReminderService.EXTRA_DECK_OPTION_ID,
mOptions.getLong("id")
),
0
)
alarmManager.cancel(reminderIntent)
val calendar = reminderToCalendar(TimeManager.time, reminder)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
reminderIntent
)
}
else -> Timber.w("Unknown key type: %s", key)
}
}
} catch (e: JSONException) {
throw RuntimeException(e)
}
// save conf
try {
col.decks.save(mOptions)
} catch (e: RuntimeException) {
Timber.e(e, "DeckOptions - RuntimeException on saving conf")
CrashReportService.sendExceptionReport(e, "DeckOptionsSaveConf")
setResult(DeckPicker.RESULT_DB_ERROR)
finish()
}
// make sure we refresh the parent cached values
cacheValues()
buildLists()
updateSummaries()
// and update any listeners
for (listener in mListeners) {
listener.onSharedPreferenceChanged(this@DeckPreferenceHack, null)
}
return true
}
/**
* Remove the currently selected options group
*/
@Throws(ConfirmModSchemaException::class)
private fun remConf() {
// Remove options group, asking user to confirm full sync if necessary
col.decks.remConf(mOptions.getLong("id"))
// Run the CPU intensive re-sort operation in a background thread
val conf = mOptions
confChangeHandler("Remove configuration") {
// Note: We do the actual removing of the options group in the main thread so that we
// can ask the user to confirm if they're happy to do a full sync, and just do the resorting here
// When a conf is deleted, all decks using it revert to the default conf.
// Cards must be reordered according to the default conf.
val order = conf.getJSONObject("new").getInt("order")
val defaultOrder =
col.decks.getConf(1)!!.getJSONObject("new").getInt("order")
if (order != defaultOrder) {
conf.getJSONObject("new").put("order", defaultOrder)
col.sched.resortConf(conf)
}
col.save()
}
deck.put("conf", 1)
}
private fun confChangeHandler(): ConfChangeHandler {
return ConfChangeHandler(this@DeckPreferenceHack)
}
}
override fun edit(): Editor {
return Editor()
}
}
class ConfChangeHandler(deckPreferenceHack: DeckPreferenceHack) :
TaskListenerWithContext<DeckPreferenceHack, Void?, Boolean?>(deckPreferenceHack) {
override fun actualOnPreExecute(context: DeckPreferenceHack) = context.preConfChange()
override fun actualOnPostExecute(context: DeckPreferenceHack, result: Boolean?) = context.postConfChange()
}
@KotlinCleanup("Remove this once DeckOptions is an AnkiActivity")
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
val newNightModeStatus = newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
// Check if theme should change
if (Themes.systemIsInNightMode != newNightModeStatus) {
Themes.systemIsInNightMode = newNightModeStatus
if (themeFollowsSystem()) {
updateCurrentTheme()
recreate()
}
}
}
// conversion to fragments tracked as #5019 in github
@Deprecated("Deprecated in Java")
override fun onCreate(savedInstanceState: Bundle?) {
Themes.setThemeLegacy(this)
super.onCreate(savedInstanceState)
if (!isColInitialized()) {
return
}
val extras = intent.extras
deck = if (extras != null && extras.containsKey("did")) {
col.decks.get(extras.getLong("did"))
} else {
col.decks.current()
}
registerExternalStorageListener()
pref = DeckPreferenceHack()
// #6068 - constructor can call finish()
if (this.isFinishing) {
return
}
pref.registerOnSharedPreferenceChangeListener(this)
addPreferencesFromResource(R.xml.deck_options)
if (isSchedV2) {
enableSchedV2Preferences()
}
buildLists()
updateSummaries()
// Set the activity title to include the name of the deck
var title = resources.getString(R.string.deckpreferences_title)
if (title.contains("XXX")) {
title = try {
title.replace("XXX", deck.getString("name"))
} catch (e: JSONException) {
Timber.w(e)
title.replace("XXX", "???")
}
}
setTitle(title)
// Add a home button to the actionbar
supportActionBar!!.setHomeButtonEnabled(true)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
// Workaround for bug 4611: http://code.google.com/p/android/issues/detail?id=4611
@Deprecated("Deprecated in Java") // TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
override fun onPreferenceTreeClick(preferenceScreen: PreferenceScreen, preference: Preference): Boolean {
super.onPreferenceTreeClick(preferenceScreen, preference)
if (preference is PreferenceScreen && preference.dialog != null) {
preference.dialog.window!!.decorView.setBackgroundDrawable(
this.window.decorView.background.constantState!!.newDrawable()
)
}
return false
}
override fun closeWithResult() {
if (prefChanged) {
setResult(RESULT_OK)
} else {
setResult(RESULT_CANCELED)
}
finish()
ActivityTransitionAnimation.slide(this, FADE)
}
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
@KotlinCleanup("remove reduntant val res = resources")
override fun updateSummaries() {
val res = resources
// for all text preferences, set summary as current database value
for (key in pref.mValues.keys) {
val pref = findPreference(key)
if ("deckConf" == key) {
var groupName = optionsGroupName
val count = optionsGroupCount
// Escape "%" in groupName as it's treated as a token
groupName = groupName.replace("%".toRegex(), "%%")
pref!!.summary = res.getQuantityString(R.plurals.deck_conf_group_summ, count, groupName, count)
continue
}
val value: String? = if (pref == null) {
continue
} else if (pref is CheckBoxPreference) {
continue
} else if (pref is ListPreference) {
val lp = pref
if (lp.entry != null) lp.entry.toString() else ""
} else {
this.pref.getString(key, "")
}
// update summary
if (!this.pref.mSummaries.containsKey(key)) {
this.pref.mSummaries[key] = pref.summary?.toString()
}
val summ = this.pref.mSummaries[key]
pref.summary = if (summ != null && summ.contains("XXX")) {
summ.replace("XXX", value!!)
} else {
value
}
}
// Update summaries of preference items that don't have values (aren't in mValues)
val subDeckCount = subdeckCount
findPreference("confSetSubdecks").summary = res.getQuantityString(R.plurals.deck_conf_set_subdecks_summ, subDeckCount, subDeckCount)
}
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
protected fun buildLists() {
val deckConfPref = findPreference("deckConf") as ListPreference
val confs = col.decks.allConf()
Collections.sort(confs, NamedJSONComparator.INSTANCE)
val confValues = arrayOfNulls<String>(confs.size)
val confLabels = arrayOfNulls<String>(confs.size)
confs.forEachIndexed { index, deckConfig ->
confValues[index] = deckConfig.getString("id")
confLabels[index] = deckConfig.getString("name")
}
deckConfPref.apply {
entries = confLabels
entryValues = confValues
value = pref.getString("deckConf", "0")
}
val newOrderPref = findPreference("newOrder") as ListPreference
newOrderPref.apply {
setEntries(R.array.new_order_labels)
setEntryValues(R.array.new_order_values)
value = pref.getString("newOrder", "0")
}
val leechActPref = findPreference("lapLeechAct") as ListPreference
leechActPref.apply {
setEntries(R.array.leech_action_labels)
setEntryValues(R.array.leech_action_values)
value = pref.getString(
"lapLeechAct",
Consts.LEECH_SUSPEND.toString()
)
}
}
private val isSchedV2: Boolean
get() = col.schedVer() == 2
/**
* Enable deck preferences that are only available with Scheduler V2.
*/
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
private fun enableSchedV2Preferences() {
val hardFactorPreference = findPreference("hardFactor") as NumberRangePreference
hardFactorPreference.isEnabled = true
}
/**
* Returns the number of decks using the options group of the current deck.
*/
private val optionsGroupCount: Int
get() {
var count = 0
val conf = deck.getLong("conf")
@KotlinCleanup("Join both if blocks")
for (deck in col.decks.all()) {
if (deck.isDyn) {
continue
}
if (deck.getLong("conf") == conf) {
count++
}
}
return count
}
/**
* Get the name of the currently set options group
*/
private val optionsGroupName: String
get() {
val confId = pref.getLong("deckConf", 0)
return col.decks.getConf(confId)!!.getString("name")
}
/**
* Get the number of (non-dynamic) subdecks for the current deck
*/
@KotlinCleanup("Use .count{}")
private val subdeckCount: Int
get() {
var count = 0
val did = deck.getLong("id")
val children = col.decks.children(did)
for (childDid in children.values) {
val child = col.decks.get(childDid)
if (child.isDyn) {
continue
}
count++
}
return count
}
private fun restartActivity() {
recreate()
}
companion object {
fun reminderToCalendar(time: Time, reminder: JSONObject): Calendar {
val calendar = time.calendar()
calendar[Calendar.HOUR_OF_DAY] = reminder.getJSONArray("time").getInt(0)
calendar[Calendar.MINUTE] = reminder.getJSONArray("time").getInt(1)
calendar[Calendar.SECOND] = 0
return calendar
}
}
}
| gpl-3.0 | 59c6a0d0011c1a68fd4ac5db790bc0e8 | 48.26264 | 169 | 0.503578 | 5.915837 | false | false | false | false |
rock3r/detekt | detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/DetektReport.kt | 1 | 1227 | package io.gitlab.arturbosch.detekt.extensions
import org.gradle.api.Project
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.Provider
import java.io.File
class DetektReport(val type: DetektReportType, private val project: Project) {
var enabled: Boolean? = null
var destination: File? = null
override fun toString(): String {
return "DetektReport(type='$type', enabled=$enabled, destination=$destination)"
}
fun getTargetFileProvider(reportsDir: Provider<File>): Provider<RegularFile> {
return project.provider {
if (enabled ?: DetektExtension.DEFAULT_REPORT_ENABLED_VALUE) {
getTargetFile(reportsDir.get())
} else {
null
}
}
}
private fun getTargetFile(reportsDir: File): RegularFile {
val prop = project.objects.fileProperty()
val customDestination = destination
if (customDestination != null) {
prop.set(customDestination)
} else {
prop.set(File(reportsDir, "$DEFAULT_FILENAME.${type.extension}"))
}
return prop.get()
}
companion object {
const val DEFAULT_FILENAME = "detekt"
}
}
| apache-2.0 | aa94b4f95142012edafa1acb6b9928b4 | 27.534884 | 87 | 0.636512 | 4.612782 | false | false | false | false |
JetBrains/anko | anko/library/generated/sdk27-listeners/src/main/java/Listeners.kt | 2 | 20576 | @file:JvmName("Sdk27ListenersListenersKt")
package org.jetbrains.anko.sdk27.listeners
inline fun android.view.View.onLayoutChange(noinline l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit) {
addOnLayoutChangeListener(l)
}
fun android.view.View.onAttachStateChangeListener(init: __View_OnAttachStateChangeListener.() -> Unit) {
val listener = __View_OnAttachStateChangeListener()
listener.init()
addOnAttachStateChangeListener(listener)
}
class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
_onViewAttachedToWindow?.invoke(v)
}
fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) {
_onViewAttachedToWindow = listener
}
private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null
override fun onViewDetachedFromWindow(v: android.view.View) {
_onViewDetachedFromWindow?.invoke(v)
}
fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) {
_onViewDetachedFromWindow = listener
}
}
fun android.widget.TextView.textChangedListener(init: __TextWatcher.() -> Unit) {
val listener = __TextWatcher()
listener.init()
addTextChangedListener(listener)
}
class __TextWatcher : android.text.TextWatcher {
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
_beforeTextChanged?.invoke(s, start, count, after)
}
fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
_onTextChanged?.invoke(s, start, before, count)
}
fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null
override fun afterTextChanged(s: android.text.Editable?) {
_afterTextChanged?.invoke(s)
}
fun afterTextChanged(listener: (android.text.Editable?) -> Unit) {
_afterTextChanged = listener
}
}
fun android.gesture.GestureOverlayView.onGestureListener(init: __GestureOverlayView_OnGestureListener.() -> Unit) {
val listener = __GestureOverlayView_OnGestureListener()
listener.init()
addOnGestureListener(listener)
}
class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureStarted?.invoke(overlay, event)
}
fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureStarted = listener
}
private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGesture?.invoke(overlay, event)
}
fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGesture = listener
}
private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureEnded?.invoke(overlay, event)
}
fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureEnded = listener
}
private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureCancelled?.invoke(overlay, event)
}
fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureCancelled = listener
}
}
inline fun android.gesture.GestureOverlayView.onGesturePerformed(noinline l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit) {
addOnGesturePerformedListener(l)
}
fun android.gesture.GestureOverlayView.onGesturingListener(init: __GestureOverlayView_OnGesturingListener.() -> Unit) {
val listener = __GestureOverlayView_OnGesturingListener()
listener.init()
addOnGesturingListener(listener)
}
class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
_onGesturingStarted?.invoke(overlay)
}
fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingStarted = listener
}
private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
_onGesturingEnded?.invoke(overlay)
}
fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingEnded = listener
}
}
inline fun android.media.tv.TvView.onUnhandledInputEvent(noinline l: (event: android.view.InputEvent?) -> Boolean) {
setOnUnhandledInputEventListener(l)
}
inline fun android.view.View.onApplyWindowInsets(noinline l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?) {
setOnApplyWindowInsetsListener(l)
}
inline fun android.view.View.onCapturedPointer(noinline l: (view: android.view.View?, event: android.view.MotionEvent?) -> Boolean) {
setOnCapturedPointerListener(l)
}
inline fun android.view.View.onClick(noinline l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
inline fun android.view.View.onContextClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnContextClickListener(l)
}
inline fun android.view.View.onCreateContextMenu(noinline l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit) {
setOnCreateContextMenuListener(l)
}
inline fun android.view.View.onDrag(noinline l: (v: android.view.View, event: android.view.DragEvent) -> Boolean) {
setOnDragListener(l)
}
inline fun android.view.View.onFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnFocusChangeListener(l)
}
inline fun android.view.View.onGenericMotion(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnGenericMotionListener(l)
}
inline fun android.view.View.onHover(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnHoverListener(l)
}
inline fun android.view.View.onKey(noinline l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
inline fun android.view.View.onLongClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnLongClickListener(l)
}
inline fun android.view.View.onScrollChange(noinline l: (v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit) {
setOnScrollChangeListener(l)
}
inline fun android.view.View.onSystemUiVisibilityChange(noinline l: (visibility: Int) -> Unit) {
setOnSystemUiVisibilityChangeListener(l)
}
inline fun android.view.View.onTouch(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnTouchListener(l)
}
fun android.view.ViewGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) {
val listener = __ViewGroup_OnHierarchyChangeListener()
listener.init()
setOnHierarchyChangeListener(listener)
}
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
_onChildViewAdded?.invoke(parent, child)
}
fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
_onChildViewRemoved?.invoke(parent, child)
}
fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
inline fun android.view.ViewStub.onInflate(noinline l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit) {
setOnInflateListener(l)
}
fun android.widget.AbsListView.onScrollListener(init: __AbsListView_OnScrollListener.() -> Unit) {
val listener = __AbsListView_OnScrollListener()
listener.init()
setOnScrollListener(listener)
}
class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
_onScrollStateChanged?.invoke(view, scrollState)
}
fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) {
_onScrollStateChanged = listener
}
private var _onScroll: ((android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
_onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
fun onScroll(listener: (android.widget.AbsListView?, Int, Int, Int) -> Unit) {
_onScroll = listener
}
}
inline fun android.widget.ActionMenuView.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean) {
setOnItemLongClickListener(l)
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) {
val listener = __AdapterView_OnItemSelectedListener()
listener.init()
setOnItemSelectedListener(listener)
}
class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
_onItemSelected?.invoke(p0, p1, p2, p3)
}
fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
_onItemSelected = listener
}
private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
_onNothingSelected?.invoke(p0)
}
fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) {
_onNothingSelected = listener
}
}
inline fun android.widget.AutoCompleteTextView.onDismiss(noinline l: () -> Unit) {
setOnDismissListener(l)
}
inline fun android.widget.CalendarView.onDateChange(noinline l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangeListener(l)
}
inline fun android.widget.Chronometer.onChronometerTick(noinline l: (chronometer: android.widget.Chronometer?) -> Unit) {
setOnChronometerTickListener(l)
}
inline fun android.widget.CompoundButton.onCheckedChange(noinline l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.DatePicker.onDateChanged(noinline l: (view: android.widget.DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangedListener(l)
}
inline fun android.widget.ExpandableListView.onChildClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean) {
setOnChildClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean) {
setOnGroupClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupCollapse(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupCollapseListener(l)
}
inline fun android.widget.ExpandableListView.onGroupExpand(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupExpandListener(l)
}
inline fun android.widget.NumberPicker.onScroll(noinline l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit) {
setOnScrollListener(l)
}
inline fun android.widget.NumberPicker.onValueChanged(noinline l: (picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit) {
setOnValueChangedListener(l)
}
inline fun android.widget.RadioGroup.onCheckedChange(noinline l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.RatingBar.onRatingBarChange(noinline l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit) {
setOnRatingBarChangeListener(l)
}
inline fun android.widget.SearchView.onClose(noinline l: () -> Boolean) {
setOnCloseListener(l)
}
inline fun android.widget.SearchView.onQueryTextFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnQueryTextFocusChangeListener(l)
}
fun android.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) {
val listener = __SearchView_OnQueryTextListener()
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
inline fun android.widget.SearchView.onSearchClick(noinline l: (v: android.view.View?) -> Unit) {
setOnSearchClickListener(l)
}
fun android.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) {
val listener = __SearchView_OnSuggestionListener()
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
fun android.widget.SeekBar.onSeekBarChangeListener(init: __SeekBar_OnSeekBarChangeListener.() -> Unit) {
val listener = __SeekBar_OnSeekBarChangeListener()
listener.init()
setOnSeekBarChangeListener(listener)
}
class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: ((android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
_onProgressChanged?.invoke(seekBar, progress, fromUser)
}
fun onProgressChanged(listener: (android.widget.SeekBar?, Int, Boolean) -> Unit) {
_onProgressChanged = listener
}
private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStartTrackingTouch?.invoke(seekBar)
}
fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStartTrackingTouch = listener
}
private var _onStopTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStopTrackingTouch?.invoke(seekBar)
}
fun onStopTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStopTrackingTouch = listener
}
}
inline fun android.widget.SlidingDrawer.onDrawerClose(noinline l: () -> Unit) {
setOnDrawerCloseListener(l)
}
inline fun android.widget.SlidingDrawer.onDrawerOpen(noinline l: () -> Unit) {
setOnDrawerOpenListener(l)
}
fun android.widget.SlidingDrawer.onDrawerScrollListener(init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit) {
val listener = __SlidingDrawer_OnDrawerScrollListener()
listener.init()
setOnDrawerScrollListener(listener)
}
class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (() -> Unit)? = null
override fun onScrollStarted() {
_onScrollStarted?.invoke()
}
fun onScrollStarted(listener: () -> Unit) {
_onScrollStarted = listener
}
private var _onScrollEnded: (() -> Unit)? = null
override fun onScrollEnded() {
_onScrollEnded?.invoke()
}
fun onScrollEnded(listener: () -> Unit) {
_onScrollEnded = listener
}
}
inline fun android.widget.TabHost.onTabChanged(noinline l: (tabId: String?) -> Unit) {
setOnTabChangedListener(l)
}
inline fun android.widget.TextView.onEditorAction(noinline l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnEditorActionListener(l)
}
inline fun android.widget.TimePicker.onTimeChanged(noinline l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit) {
setOnTimeChangedListener(l)
}
inline fun android.widget.Toolbar.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.VideoView.onCompletion(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
inline fun android.widget.VideoView.onError(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnErrorListener(l)
}
inline fun android.widget.VideoView.onInfo(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnInfoListener(l)
}
inline fun android.widget.VideoView.onPrepared(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
inline fun android.widget.ZoomControls.onZoomInClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomInClickListener(l)
}
inline fun android.widget.ZoomControls.onZoomOutClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomOutClickListener(l)
}
| apache-2.0 | dfcd06f4de6f86bb680a2161307c405e | 35.6121 | 201 | 0.727644 | 4.358399 | false | false | false | false |
pdvrieze/ProcessManager | multiplatform/src/javaShared/kotlin/nl/adaptivity/util/multiplatform/javaMultiplatform.kt | 1 | 2158 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.multiplatform
import java.util.UUID
import kotlin.reflect.KClass
actual typealias Class<T> = java.lang.Class<T>
actual val KClass<*>.name get() = java.name
actual typealias Throws = kotlin.jvm.Throws
actual typealias UUID = java.util.UUID
actual fun randomUUID(): UUID = UUID.randomUUID()
actual typealias JvmStatic = kotlin.jvm.JvmStatic
actual typealias JvmWildcard = kotlin.jvm.JvmWildcard
actual typealias JvmField = kotlin.jvm.JvmField
actual typealias JvmName = kotlin.jvm.JvmName
actual typealias JvmOverloads = kotlin.jvm.JvmOverloads
actual typealias JvmMultifileClass = kotlin.jvm.JvmMultifileClass
actual typealias URI = java.net.URI
@Suppress("NOTHING_TO_INLINE")
actual inline fun createUri(s: String): URI = URI.create(s)
actual fun String.toUUID(): UUID = UUID.fromString(this)
@Suppress("NOTHING_TO_INLINE")
actual fun <T> fill(array: Array<T>, element: T, fromIndex: Int, toIndex: Int) {
java.util.Arrays.fill(array, fromIndex, toIndex, element)
}
@Suppress("NOTHING_TO_INLINE")
actual fun arraycopy(src: Any, srcPos:Int, dest:Any, destPos:Int, length:Int) =
java.lang.System.arraycopy(src, srcPos, dest, destPos, length)
actual inline fun <reified T:Any> isTypeOf(value: Any):Boolean = value::class.java == T::class.java
actual fun Throwable.addSuppressedCompat(suppressed: Throwable): Unit = addSuppressed(suppressed)
actual fun Throwable.initCauseCompat(cause: Throwable): Throwable = initCause(cause)
| lgpl-3.0 | 5be9286dada2321bb2103bd02373cd22 | 33.253968 | 112 | 0.76506 | 3.881295 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/settings/SettingsViewModel.kt | 1 | 2842 | package org.fossasia.openevent.general.settings
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.BuildConfig
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthService
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
const val API_URL = "apiUrl"
class SettingsViewModel(
private val authService: AuthService,
private val preference: Preference,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableSnackBar = SingleLiveEvent<String>()
val snackBar: SingleLiveEvent<String> = mutableSnackBar
private val mutableUpdatedPassword = MutableLiveData<String>()
val updatedPassword: LiveData<String> = mutableUpdatedPassword
fun isLoggedIn() = authService.isLoggedIn()
fun logout() {
compositeDisposable += authService.logout()
.withDefaultSchedulers()
.subscribe({
Timber.d("Logged out!")
}) {
Timber.e(it, "Failure Logging out!")
}
}
fun getMarketAppLink(packageName: String): String {
return "market://details?id=" + packageName
}
fun getMarketWebLink(packageName: String): String {
return "https://play.google.com/store/apps/details?id=" + packageName
}
fun changePassword(oldPassword: String, newPassword: String) {
compositeDisposable += authService.changePassword(oldPassword, newPassword)
.withDefaultSchedulers()
.subscribe({
if (it.passwordChanged) {
mutableSnackBar.value = resource.getString(R.string.change_password_success_message)
mutableUpdatedPassword.value = newPassword
}
}, {
if (it.message.toString() == "HTTP 400 BAD REQUEST")
mutableSnackBar.value = resource.getString(R.string.incorrect_old_password_message)
else mutableSnackBar.value = resource.getString(R.string.change_password_fail_message)
})
}
fun getApiUrl(): String {
return preference.getString(API_URL) ?: BuildConfig.DEFAULT_BASE_URL
}
fun changeApiUrl(url: String) {
preference.putString(API_URL, url)
logout()
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 720b369b309040f4fbc9299d4b512da4 | 34.974684 | 104 | 0.682618 | 5.012346 | false | false | false | false |
andersonlucasg3/SpriteKit-Android | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/opengl/model/GLColor.kt | 1 | 1550 | package br.com.insanitech.spritekit.opengl.model
import br.com.insanitech.spritekit.core.ValueAssign
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Created by anderson on 6/30/15.
*/
internal class GLColor() : ValueAssign<GLColor> {
internal val buffer by lazy {
val bb = ByteBuffer.allocateDirect(16 * 4)
bb.order(ByteOrder.nativeOrder())
bb.asFloatBuffer()
}
var r: Float
get() = this.get(0)
set(value) { this.set(0, value) }
var g: Float
get() = this.get(1)
set(value) { this.set(1, value) }
var b: Float
get() = this.get(2)
set(value) { this.set(2, value) }
var a: Float
get() = this.get(3)
set(value) { this.set(3, value) }
constructor(r: Float, g: Float, b: Float, a: Float) : this() {
this.r = r
this.g = g
this.b = b
this.a = a
}
private fun get(index: Int) : Float = this.buffer.get(index)
private fun set(index: Int, value: Float) {
this.buffer.put(index, value)
this.buffer.put(index + 4, value)
this.buffer.put(index + 8, value)
this.buffer.put(index + 12, value)
}
override fun assignByValue(other: GLColor) {
this.r = other.r
this.g = other.g
this.b = other.b
this.a = other.a
}
companion object {
fun rgb(r: Float, g: Float, b: Float): GLColor = rgba(r, g, b, 1.0f)
fun rgba(r: Float, g: Float, b: Float, a: Float): GLColor = GLColor(r, g, b, a)
}
}
| bsd-3-clause | a27767b04e07ef7c399952b514489296 | 24.833333 | 87 | 0.563871 | 3.229167 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/logback/LogDocumentBuilder.kt | 1 | 3650 | /*
* Copyright (c) 2016. KESTI co, ltd
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.core.logback
import org.joda.time.DateTime
/**
* Kotlin 에서는 이런 Builder 패턴을 apply { } 메소드로 사용하는 것이 가장 좋다
*
* @author [email protected]
*/
class LogDocumentBuilder {
private var _serverName: String = "localhost"
private var _applicationName: String = ""
private var _logger: String = ""
private var _levelInt: Int = 0
private var _levelStr: String = ""
private var _threadName: String = ""
private var _message: String = ""
private var _timestamp: DateTime = DateTime.now()
private var _marker: String? = null
private var _exception: String? = null
private var _stackTrace: List<String> = emptyList()
/**
* Server name 설정
* @param serverName 설정할 server name
* *
* @return LogDocumentBuilder 인스턴스
*/
fun serverName(serverName: String): LogDocumentBuilder {
this._serverName = serverName
return this
}
/**
* Application name 설정
* @param applicationName 설정할 application name
* *
* @return LogDocumentBuilder 인스턴스
*/
fun applicationName(applicationName: String): LogDocumentBuilder {
this._applicationName = applicationName
return this
}
/**
* Logger 명 설정
* @param logger 설정할 logger 명
* *
* @return LogDocumentBuilder 인스턴스
*/
fun logger(logger: String): LogDocumentBuilder {
this._logger = logger
return this
}
/**
* Level 값 설정
* @param levelInt 설정할 레벨 값 (참고 : [ch.qos.logback.classic.Level] )
* *
* @return LogDocumentBuilder 인스턴스
*/
fun levelInt(levelInt: Int): LogDocumentBuilder {
this._levelInt = levelInt
return this
}
/**
* Level 설정
* @param levelStr 설정할 레벨 값 (참고 : [ch.qos.logback.classic.Level] )
* *
* @return LogDocumentBuilder 인스턴스
*/
fun levelStr(levelStr: String): LogDocumentBuilder {
this._levelStr = levelStr
return this
}
fun threadName(threadName: String): LogDocumentBuilder {
this._threadName = threadName
return this
}
fun message(message: String): LogDocumentBuilder {
this._message = message
return this
}
fun timestamp(timestamp: DateTime): LogDocumentBuilder {
this._timestamp = timestamp
return this
}
fun marker(marker: String): LogDocumentBuilder {
this._marker = marker
return this
}
fun exception(exception: String): LogDocumentBuilder {
this._exception = exception
return this
}
fun stackTrace(stackTrace: List<String>): LogDocumentBuilder {
this._stackTrace = stackTrace
return this
}
fun build(): LogDocument {
return LogDocument().apply {
serverName = _serverName
applicationName = _applicationName
logger = _logger
levelInt = _levelInt
levelStr = _levelStr
threadName = _threadName
message = _message
timestamp = _timestamp
marker = _marker
exception = _exception
stackTrace = _stackTrace
}
}
} | apache-2.0 | 5c85556bc16de494e3d8cbdca8067a9f | 22.910959 | 75 | 0.672493 | 4.235437 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/TrendingShowsFragment.kt | 1 | 5279 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.suggestions.shows
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.fragment.SwipeRefreshRecyclerFragment
import net.simonvt.cathode.entity.Show
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import net.simonvt.cathode.ui.ShowsNavigationListener
import net.simonvt.cathode.ui.lists.ListDialog
import net.simonvt.cathode.ui.shows.ShowDescriptionAdapter
import javax.inject.Inject
class TrendingShowsFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val showScheduler: ShowTaskScheduler
) : SwipeRefreshRecyclerFragment<ShowDescriptionAdapter.ViewHolder>(), ListDialog.Callback,
ShowDescriptionAdapter.ShowCallbacks {
private lateinit var viewModel: TrendingShowsViewModel
private var showsAdapter: ShowDescriptionAdapter? = null
private lateinit var navigationListener: ShowsNavigationListener
private lateinit var sortBy: SortBy
private var columnCount: Int = 0
private var scrollToTop: Boolean = false
enum class SortBy(val key: String, val sortOrder: String) {
VIEWERS("viewers", Shows.SORT_VIEWERS), RATING("rating", Shows.SORT_RATING);
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: VIEWERS
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
sortBy = SortBy.fromValue(
Settings.get(requireContext()).getString(Settings.Sort.SHOW_TRENDING, SortBy.VIEWERS.key)!!
)
columnCount = resources.getInteger(R.integer.showsColumns)
setTitle(R.string.title_shows_trending)
setEmptyText(R.string.shows_loading_trending)
viewModel =
ViewModelProviders.of(this, viewModelFactory).get(TrendingShowsViewModel::class.java)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.trending.observe(this, Observer { shows -> setShows(shows) })
}
override fun getColumnCount(): Int {
return columnCount
}
override fun onRefresh() {
viewModel.refresh()
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort_by -> {
val items = arrayListOf<ListDialog.Item>()
items.add(ListDialog.Item(R.id.sort_viewers, R.string.sort_viewers))
items.add(ListDialog.Item(R.id.sort_rating, R.string.sort_rating))
ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this)
.show(requireFragmentManager(), DIALOG_SORT)
return true
}
else -> return super.onMenuItemClick(item)
}
}
override fun onItemSelected(id: Int) {
when (id) {
R.id.sort_viewers -> if (sortBy != SortBy.VIEWERS) {
sortBy = SortBy.VIEWERS
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_TRENDING, SortBy.VIEWERS.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
R.id.sort_rating -> if (sortBy != SortBy.RATING) {
sortBy = SortBy.RATING
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_TRENDING, SortBy.RATING.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
}
}
override fun onShowClick(showId: Long, title: String?, overview: String?) {
navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED)
}
override fun setIsInWatchlist(showId: Long, inWatchlist: Boolean) {
showScheduler.setIsInWatchlist(showId, inWatchlist)
}
private fun setShows(shows: List<Show>) {
if (showsAdapter == null) {
showsAdapter = ShowDescriptionAdapter(requireContext(), this)
adapter = showsAdapter
}
showsAdapter!!.setList(shows)
if (scrollToTop) {
recyclerView.scrollToPosition(0)
scrollToTop = false
}
}
companion object {
private const val DIALOG_SORT =
"net.simonvt.cathode.ui.suggestions.shows.TrendingShowsFragment.sortDialog"
}
}
| apache-2.0 | e9ae146810d1f180fb7e8d2474f8a1ca | 31.386503 | 97 | 0.72419 | 4.410192 | false | false | false | false |
FHannes/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/grAnnotationUtil.kt | 12 | 1357 | /*
* 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.plugins.groovy.lang.psi.impl
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
fun PsiAnnotation.findDeclaredDetachedValue(attributeName: String?): PsiAnnotationMemberValue? {
return AnnotationUtil.findDeclaredAttribute(this, attributeName)?.detachedValue
}
fun PsiAnnotationMemberValue?.booleanValue() = (this as? PsiLiteral)?.value as? Boolean
fun PsiAnnotationMemberValue?.stringValue() = (this as? PsiLiteral)?.value as? String
fun GrModifierList.hasAnnotation(fqn: String) = annotations.any { it.qualifiedName == fqn }
| apache-2.0 | 5d1f07fc57ce40ac2ca0ffae5656e562 | 41.40625 | 96 | 0.789978 | 4.391586 | false | false | false | false |
hea3ven/DulceDeLeche | src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/dispenser/DispenserPlantBehavior.kt | 1 | 1170 | package com.hea3ven.dulcedeleche.modules.redstone.dispenser
import com.hea3ven.dulcedeleche.DulceDeLecheMod
import com.hea3ven.tools.commonutils.util.ItemStackUtil
import net.minecraft.block.DispenserBlock
import net.minecraft.block.dispenser.DispenserBehavior
import net.minecraft.entity.EquipmentSlot
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPointer
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
class DispenserPlantBehavior : DispenserBehavior {
override fun dispense(source: BlockPointer, stack: ItemStack): ItemStack {
val direction: Direction = source.blockState.get(DispenserBlock.FACING)
val position = source.blockPos.offset(direction)
val offset = if (source.world.isAir(position)) 1 else 0
val pos = BlockPos(position.x, position.y - offset, position.z)
val player = DulceDeLecheMod.mod.getFakePlayer(source.world)
player.setEquippedStack(EquipmentSlot.HAND_MAIN, stack)
ItemStackUtil.useItem(player, stack, pos, Direction.UP)
player.setEquippedStack(EquipmentSlot.HAND_MAIN, ItemStack.EMPTY)
return stack
}
} | mit | 607d7688deb20a2bb8f598b668874e5f | 42.37037 | 79 | 0.777778 | 4.048443 | false | false | false | false |
FHannes/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/client/JUnitClientImpl.kt | 2 | 4380 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.client
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import java.io.EOFException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.Socket
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
/**
* @author Sergey Karashevich
*/
class JUnitClientImpl(val host: String, val port: Int, initHandlers: Array<ClientHandler>? = null) : JUnitClient {
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.remote.client.JUnitClientImpl")
private val RECEIVE_THREAD = "JUnit Client Receive Thread"
private val SEND_THREAD = "JUnit Client Send Thread"
private val connection: Socket
private val clientReceiveThread: ClientReceiveThread
private val clientSendThread: ClientSendThread
private val poolOfMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val objectInputStream: ObjectInputStream
private val objectOutputStream: ObjectOutputStream
private val handlers: ArrayList<ClientHandler> = ArrayList()
init {
if (initHandlers != null) handlers.addAll(initHandlers)
LOG.info("Client connecting to Server($host, $port) ...")
connection = Socket(host, port)
LOG.info("Client connected to Server($host, $port) successfully")
objectOutputStream = ObjectOutputStream(connection.getOutputStream())
clientSendThread = ClientSendThread(connection, objectOutputStream)
clientSendThread.start()
objectInputStream = ObjectInputStream(connection.getInputStream())
clientReceiveThread = ClientReceiveThread(connection, objectInputStream)
clientReceiveThread.start()
}
override fun addHandler(handler: ClientHandler) {
handlers.add(handler)
}
override fun removeHandler(handler: ClientHandler) {
handlers.remove(handler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun send(message: TransportMessage) {
poolOfMessages.add(message)
}
override fun stopClient() {
val clientPort = connection.port
LOG.info("Stopping client on port: $clientPort ...")
poolOfMessages.clear()
handlers.clear()
clientReceiveThread.objectInputStream.close()
clientReceiveThread.join()
clientSendThread.objectOutputStream.close()
clientSendThread.join()
connection.close()
LOG.info("Stopped client on port: $clientPort")
}
inner class ClientReceiveThread(val connection: Socket, val objectInputStream: ObjectInputStream) : Thread(RECEIVE_THREAD) {
override fun run() {
LOG.info("Starting Client Receive Thread")
try{
while (connection.isConnected) {
val obj = objectInputStream.readObject()
LOG.info("Received message: $obj")
obj as TransportMessage
handlers
.filter { it.accept(obj) }
.forEach { it.handle(obj) }
}
} catch (e: Exception) {
LOG.info("Transport receiving message exception: $e")
e.printStackTrace()
} finally {
objectInputStream.close()
}
}
}
inner class ClientSendThread(val connection: Socket, val objectOutputStream: ObjectOutputStream) : Thread(SEND_THREAD) {
override fun run() {
try {
LOG.info("Starting Client Send Thread")
while (connection.isConnected) {
val transportMessage = poolOfMessages.take()
LOG.info("Sending message: $transportMessage")
objectOutputStream.writeObject(transportMessage)
}
}
catch(e: InterruptedException) {
Thread.currentThread().interrupt()
}
finally {
objectOutputStream.close()
}
}
}
}
| apache-2.0 | fc1a204349a6b3fe684c11266e1a52eb | 31.932331 | 126 | 0.719406 | 4.76605 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/streaming/db/OfflineDb.kt | 1 | 4031 | package io.casey.musikcube.remote.service.playback.impl.streaming.db
import androidx.room.Database
import androidx.room.RoomDatabase
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.injection.DaggerDataComponent
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy
import io.casey.musikcube.remote.service.websocket.Messages
import io.casey.musikcube.remote.service.websocket.SocketMessage
import io.casey.musikcube.remote.service.websocket.WebSocketService
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import org.json.JSONObject
import javax.inject.Inject
@Database(entities = [OfflineTrack::class], version = 1)
abstract class OfflineDb : RoomDatabase() {
@Inject lateinit var wss: WebSocketService
@Inject lateinit var streamProxy: StreamProxy
init {
DaggerDataComponent.builder()
.appComponent(Application.appComponent)
.build().inject(this)
wss.addInterceptor{ message, responder ->
var result = false
if (Messages.Request.QueryTracksByCategory.matches(message.name)) {
val category = message.getStringOption(Messages.Key.CATEGORY)
if (Metadata.Category.OFFLINE == category) {
queryTracks(message, responder)
result = true
}
}
result
}
prune()
}
abstract fun trackDao(): OfflineTrackDao
fun prune() {
@Suppress("unused")
Single.fromCallable {
val uris = trackDao().queryUris()
val toDelete = ArrayList<String>()
uris.forEach {
if (!streamProxy.isCached(it)) {
toDelete.add(it)
}
}
if (toDelete.size > 0) {
trackDao().deleteByUri(toDelete)
}
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ }, { })
}
private fun queryTracks(message: SocketMessage, responder: WebSocketService.Responder) {
Single.fromCallable {
val dao = trackDao()
val countOnly = message.getBooleanOption(Messages.Key.COUNT_ONLY, false)
val filter = message.getStringOption(Messages.Key.FILTER, "")
val tracks = JSONArray()
val options = JSONObject()
if (countOnly) {
val count = if (filter.isEmpty()) dao.countTracks() else dao.countTracks(filter)
options.put(Messages.Key.COUNT, count)
}
else {
val offset = message.getIntOption(Messages.Key.OFFSET, -1)
val limit = message.getIntOption(Messages.Key.LIMIT, -1)
val offlineTracks: List<OfflineTrack> =
if (filter.isEmpty()) {
if (offset == -1 || limit == -1)
dao.queryTracks() else dao.queryTracks(limit, offset)
}
else {
if (offset == -1 || limit == -1)
dao.queryTracks(filter) else dao.queryTracks(filter, limit, offset)
}
for (track in offlineTracks) {
tracks.put(track.toJSONObject())
}
options.put(Messages.Key.OFFSET, offset)
options.put(Messages.Key.LIMIT, limit)
}
options.put(Messages.Key.DATA, tracks)
val response = SocketMessage.Builder
.respondTo(message).withOptions(options).build()
responder.respond(response)
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
}
| bsd-3-clause | e17d5caa502bf883a69e33c28b65f679 | 33.161017 | 96 | 0.589432 | 4.862485 | false | false | false | false |
arturbosch/detekt | detekt-rules-complexity/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LargeClass.kt | 1 | 3559 | package io.gitlab.arturbosch.detekt.rules.complexity
import io.github.detekt.metrics.linesOfCode
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.util.IdentityHashMap
/**
* This rule reports large classes. Classes should generally have one responsibility. Large classes can indicate that
* the class does instead handle multiple responsibilities. Instead of doing many things at once prefer to
* split up large classes into smaller classes. These smaller classes are then easier to understand and handle less
* things.
*/
@ActiveByDefault(since = "1.0.0")
class LargeClass(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
"LargeClass",
Severity.Maintainability,
"One class should have one responsibility. Large classes tend to handle many things at once. " +
"Split up large classes into smaller classes that are easier to understand.",
Debt.TWENTY_MINS
)
@Configuration("the size of class required to trigger the rule")
private val threshold: Int by config(defaultValue = 600)
private val classToLinesCache = IdentityHashMap<KtClassOrObject, Int>()
private val nestedClassTracking = IdentityHashMap<KtClassOrObject, HashSet<KtClassOrObject>>()
override fun preVisit(root: KtFile) {
classToLinesCache.clear()
nestedClassTracking.clear()
}
override fun postVisit(root: KtFile) {
for ((clazz, lines) in classToLinesCache) {
if (lines >= threshold) {
report(
ThresholdedCodeSmell(
issue,
Entity.atName(clazz),
Metric("SIZE", lines, threshold),
"Class ${clazz.name} is too large. Consider splitting it into smaller pieces."
)
)
}
}
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
val lines = classOrObject.linesOfCode()
classToLinesCache[classOrObject] = lines
classOrObject.getStrictParentOfType<KtClassOrObject>()
?.let { nestedClassTracking.getOrPut(it) { HashSet() }.add(classOrObject) }
super.visitClassOrObject(classOrObject)
findAllNestedClasses(classOrObject)
.fold(0) { acc, next -> acc + (classToLinesCache[next] ?: 0) }
.takeIf { it > 0 }
?.let { classToLinesCache[classOrObject] = lines - it }
}
private fun findAllNestedClasses(startClass: KtClassOrObject): Sequence<KtClassOrObject> = sequence {
var nestedClasses = nestedClassTracking[startClass]
while (!nestedClasses.isNullOrEmpty()) {
yieldAll(nestedClasses)
nestedClasses = nestedClasses.mapNotNull { nestedClassTracking[it] }.flattenTo(HashSet())
}
}
}
| apache-2.0 | 0075106c84ae77aba21fdb2ae69de0e7 | 41.879518 | 117 | 0.69823 | 4.862022 | false | true | false | false |
googlecodelabs/kotlin-coroutines | coroutines-codelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainDatabase.kt | 1 | 2223 | /*
* Copyright (C) 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.kotlincoroutines.main
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Title represents the title fetched from the network
*/
@Entity
data class Title constructor(val title: String, @PrimaryKey val id: Int = 0)
/***
* Very small database that will hold one title
*/
@Dao
interface TitleDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertTitle(title: Title)
@get:Query("select * from Title where id = 0")
val titleLiveData: LiveData<Title?>
}
/**
* TitleDatabase provides a reference to the dao to repositories
*/
@Database(entities = [Title::class], version = 1, exportSchema = false)
abstract class TitleDatabase : RoomDatabase() {
abstract val titleDao: TitleDao
}
private lateinit var INSTANCE: TitleDatabase
/**
* Instantiate a database from a context.
*/
fun getDatabase(context: Context): TitleDatabase {
synchronized(TitleDatabase::class) {
if (!::INSTANCE.isInitialized) {
INSTANCE = Room
.databaseBuilder(
context.applicationContext,
TitleDatabase::class.java,
"titles_db"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}
| apache-2.0 | 55b879e95520daa0a768bf03467e5422 | 28.25 | 76 | 0.688259 | 4.583505 | false | false | false | false |
lambdasoup/watchlater | app/src/main/java/com/lambdasoup/watchlater/ui/add/VideoSnippet.kt | 1 | 8023 | /*
* Copyright (c) 2015 - 2022
*
* Maximilian Hille <[email protected]>
* Juliane Lehmann <[email protected]>
*
* This file is part of Watch Later.
*
* Watch Later 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.
*
* Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambdasoup.watchlater.ui.add
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.ContentAlpha
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer
import com.lambdasoup.watchlater.R
import com.lambdasoup.watchlater.data.YoutubeRepository
import com.lambdasoup.watchlater.util.formatDuration
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo
@Composable
fun VideoSnippet(
videoInfo: VideoInfo,
modifier: Modifier = Modifier,
) {
val loading = videoInfo is VideoInfo.Progress
val painter: Painter
val imageLoaded: Boolean
if (LocalInspectionMode.current) {
painter = painterResource(id = R.drawable.thumbnail)
imageLoaded = true
} else {
painter = when (videoInfo) {
is VideoInfo.Loaded -> rememberAsyncImagePainter(model = videoInfo.data.snippet.thumbnails.medium.url)
else -> remember { ColorPainter(Color.Transparent) }
}
imageLoaded = videoInfo is VideoInfo.Loaded &&
(painter as AsyncImagePainter).state is AsyncImagePainter.State.Success
}
val headerText = when (videoInfo) {
is VideoInfo.Loaded -> videoInfo.data.snippet.title
is VideoInfo.Error -> stringResource(id = R.string.video_error_title)
is VideoInfo.Progress -> "Lorem Ipsum"
}
val subheaderText = when (videoInfo) {
is VideoInfo.Loaded -> formatDuration(videoInfo.data.contentDetails.duration)
is VideoInfo.Progress -> "12:34"
is VideoInfo.Error -> ""
}
val bodyText = when (videoInfo) {
is VideoInfo.Loaded -> videoInfo.data.snippet.description
is VideoInfo.Error -> errorText(errorType = videoInfo.error)
is VideoInfo.Progress -> "Lorem ipsum dolor sit amet yadda yadda this is loading still"
}
Row(
modifier = modifier,
) {
AnimatedVisibility(
visible = videoInfo !is VideoInfo.Error,
) {
Image(
modifier = Modifier
.width(160.dp)
.height(90.dp)
.padding(end = 16.dp)
.placeholder(
visible = loading || !imageLoaded,
highlight = PlaceholderHighlight.shimmer()
),
painter = painter,
contentDescription = stringResource(id = R.string.thumbnail_cd)
)
}
Column(
modifier = Modifier.weight(1f),
) {
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = headerText,
style = MaterialTheme.typography.subtitle2,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
CompositionLocalProvider(LocalContentAlpha.provides(ContentAlpha.medium)) {
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = subheaderText,
maxLines = 1,
style = MaterialTheme.typography.body2,
fontStyle = FontStyle.Italic,
overflow = TextOverflow.Ellipsis,
)
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = bodyText,
style = MaterialTheme.typography.caption,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@Composable
private fun errorText(
errorType: VideoInfo.ErrorType,
): String =
when (errorType) {
is VideoInfo.ErrorType.Youtube -> when (errorType.error) {
YoutubeRepository.ErrorType.Network -> stringResource(id = R.string.error_network)
YoutubeRepository.ErrorType.VideoNotFound -> stringResource(id = R.string.error_video_not_found)
else -> stringResource(
id = R.string.could_not_load,
errorType.toString()
)
}
is VideoInfo.ErrorType.InvalidVideoId -> stringResource(id = R.string.error_invalid_video_id)
is VideoInfo.ErrorType.NoAccount -> stringResource(id = R.string.error_video_info_no_account)
is VideoInfo.ErrorType.Network -> stringResource(id = R.string.error_network)
is VideoInfo.ErrorType.Other -> stringResource(id = R.string.error_general, errorType.msg)
}
@Preview(name = "Progress")
@Composable
fun VideoSnippetPreviewProgress() = VideoSnippet(
videoInfo = VideoInfo.Progress
)
@Preview(name = "Error")
@Composable
fun VideoSnippetPreviewError() = VideoSnippet(
videoInfo = VideoInfo.Error(error = VideoInfo.ErrorType.NoAccount)
)
@Preview(name = "Loaded")
@Composable
fun VideoSnippetPreviewLoaded() = VideoSnippet(
videoInfo = VideoInfo.Loaded(
data = YoutubeRepository.Videos.Item(
id = "video-id",
snippet = YoutubeRepository.Videos.Item.Snippet(
title = "Video Title",
description = "Video description",
thumbnails = YoutubeRepository.Videos.Item.Snippet.Thumbnails(
medium = YoutubeRepository.Videos.Item.Snippet.Thumbnails.Thumbnail("dummy-url ignore in preview"),
)
),
contentDetails = YoutubeRepository.Videos.Item.ContentDetails(duration = "time string"),
)
)
)
| gpl-3.0 | 95fb2059f452620e5c1c96c544089aaf | 37.023697 | 119 | 0.644023 | 4.973962 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/model/GitHubAppTokenServiceExtensions.kt | 1 | 1665 | package net.nemerosa.ontrack.extension.github.model
import net.nemerosa.ontrack.extension.github.app.GitHubAppToken
import net.nemerosa.ontrack.extension.github.app.GitHubAppTokenService
import net.nemerosa.ontrack.extension.github.app.client.GitHubAppAccount
fun GitHubAppTokenService.getAppInstallationToken(configuration: GitHubEngineConfiguration): String? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationToken(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
error("This configuration is not using a GitHub App.")
}
fun GitHubAppTokenService.getAppInstallationTokenInformation(configuration: GitHubEngineConfiguration): GitHubAppToken? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationTokenInformation(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
null
}
fun GitHubAppTokenService.getAppInstallationAccount(configuration: GitHubEngineConfiguration): GitHubAppAccount? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationAccount(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
error("This configuration is not using a GitHub App.")
}
| mit | ddd61dddc03ef7eae69dd0d8aa570ee0 | 39.609756 | 121 | 0.717117 | 5.644068 | false | true | false | false |
wiltonlazary/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/ExecClang.kt | 1 | 3982 | /*
* 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
import org.gradle.api.Action
import groovy.lang.Closure
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.process.ExecResult
import org.gradle.process.ExecSpec
import org.gradle.util.ConfigureUtil
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.konan.file.*
class ExecClang(private val project: Project) {
private val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager
private fun konanArgs(target: KonanTarget): List<String> {
return platformManager.platform(target).clang.clangArgsForKonanSources.asList()
}
fun konanArgs(targetName: String?): List<String> {
val target = platformManager.targetManager(targetName).target
return konanArgs(target)
}
fun resolveExecutable(executable: String?): String {
val executable = executable ?: "clang"
if (listOf("clang", "clang++").contains(executable)) {
val llvmDir = project.findProperty("llvmDir")
return "${llvmDir}/bin/$executable"
} else {
throw GradleException("unsupported clang executable: $executable")
}
}
// The bare ones invoke clang with system default sysroot.
fun execBareClang(action: Action<in ExecSpec>): ExecResult {
return this.execClang(emptyList<String>(), action)
}
fun execBareClang(closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(emptyList<String>(), closure)
}
// The konan ones invoke clang with konan provided sysroots.
// So they require a target or assume it to be the host.
// The target can be specified as KonanTarget or as a
// (nullable, which means host) target name.
fun execKonanClang(target: String?, action: Action<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), action)
}
fun execKonanClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), action)
}
fun execKonanClang(target: String?, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), closure)
}
fun execKonanClang(target: KonanTarget, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), closure)
}
// These ones are private, so one has to choose either Bare or Konan.
private fun execClang(defaultArgs: List<String>, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(defaultArgs, ConfigureUtil.configureUsing(closure))
}
private fun execClang(defaultArgs: List<String>, action: Action<in ExecSpec>): ExecResult {
val extendedAction = object : Action<ExecSpec> {
override fun execute(execSpec: ExecSpec) {
action.execute(execSpec)
execSpec.apply {
executable = resolveExecutable(executable)
val hostPlatform = project.findProperty("hostPlatform") as Platform
environment["PATH"] = project.files(hostPlatform.clang.clangPaths).asPath +
java.io.File.pathSeparator + environment["PATH"]
args(defaultArgs)
}
}
}
return project.exec(extendedAction)
}
}
| apache-2.0 | 167328d2e288593146e9d5e28b5370f9 | 36.214953 | 104 | 0.685334 | 4.592849 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/utils/ShortcutUtil.kt | 1 | 5156 | /*
* Nextcloud Android client application
*
* @author Felix Nüsse
*
* Copyright (C) 2022 Felix Nüsse
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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.nextcloud.utils
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.graphics.drawable.toBitmap
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.ThumbnailsCacheManager
import com.owncloud.android.ui.activity.FileActivity
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.utils.MimeTypeUtil
import com.owncloud.android.utils.theme.ViewThemeUtils
import javax.inject.Inject
class ShortcutUtil @Inject constructor(private val mContext: Context) {
/**
* Adds a pinned shortcut to the home screen that points to the passed file/folder.
*
* @param file The file/folder to which a pinned shortcut should be added to the home screen.
*/
fun addShortcutToHomescreen(file: OCFile, viewThemeUtils: ViewThemeUtils) {
if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
val intent = Intent(mContext, FileDisplayActivity::class.java)
intent.action = FileDisplayActivity.OPEN_FILE
intent.putExtra(FileActivity.EXTRA_FILE, file.remotePath)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val shortcutId = "nextcloud_shortcut_" + file.remoteId
val icon: IconCompat
var thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.remoteId
)
if (thumbnail != null) {
thumbnail = bitmapToAdaptiveBitmap(thumbnail)
icon = IconCompat.createWithAdaptiveBitmap(thumbnail)
} else if (file.isFolder) {
val bitmapIcon = MimeTypeUtil.getFolderTypeIcon(
file.isSharedWithMe || file.isSharedWithSharee,
file.isSharedViaLink,
file.isEncrypted,
file.isGroupFolder,
file.mountType,
mContext,
viewThemeUtils
).toBitmap()
icon = IconCompat.createWithBitmap(bitmapIcon)
} else {
icon = IconCompat.createWithResource(
mContext,
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
)
}
val longLabel = mContext.getString(R.string.pin_shortcut_label, file.fileName)
val pinShortcutInfo = ShortcutInfoCompat.Builder(mContext, shortcutId)
.setShortLabel(file.fileName)
.setLongLabel(longLabel)
.setIcon(icon)
.setIntent(intent)
.build()
val pinnedShortcutCallbackIntent =
ShortcutManagerCompat.createShortcutResultIntent(mContext, pinShortcutInfo)
val successCallback = PendingIntent.getBroadcast(
mContext,
0,
pinnedShortcutCallbackIntent,
FLAG_IMMUTABLE
)
ShortcutManagerCompat.requestPinShortcut(
mContext,
pinShortcutInfo,
successCallback.intentSender
)
}
}
private fun bitmapToAdaptiveBitmap(orig: Bitmap): Bitmap {
val adaptiveIconSize = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_size)
val adaptiveIconOuterSides = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_padding)
val drawable: Drawable = BitmapDrawable(mContext.resources, orig)
val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(
adaptiveIconOuterSides,
adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides
)
drawable.draw(canvas)
return bitmap
}
}
| gpl-2.0 | cf1cf24d14820a707758b9533e1553ab | 41.595041 | 108 | 0.675204 | 5.200807 | false | false | false | false |
vindkaldr/libreplicator | libreplicator-core/src/main/kotlin/org/libreplicator/core/model/TimeTable.kt | 2 | 2506 | /*
* Copyright (C) 2016 Mihály Szabó
*
* 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 org.libreplicator.core.model
import java.lang.Math.max
data class TimeTable(private val table: MutableMap<String, MutableMap<String, Long>> = mutableMapOf()) {
operator fun get(sourceNodeId: String, targetNodeId: String): Long {
return table.getOrElse(sourceNodeId, { mapOf<String, Long>() })
.getOrElse(targetNodeId, { 0 })
}
operator fun set(sourceNodeId: String, targetNodeId: String, time: Long) {
if (time > 0) {
table.getOrPut(sourceNodeId, { mutableMapOf() })[targetNodeId] = time
}
}
fun merge(sourceNodeId: String, payload: ReplicatorPayload) {
mergeRow(sourceNodeId, payload)
merge(payload)
}
private fun mergeRow(sourceNodeId: String, payload: ReplicatorPayload) {
val sourceRow = table.getOrPut(sourceNodeId, { mutableMapOf() })
val targetRow = payload.timeTable.table.getOrPut(payload.nodeId, { mutableMapOf() })
sourceRow.keys + targetRow.keys.forEach {
val maxValue = max(sourceRow.getOrElse(it, { 0 }), targetRow.getOrElse(it, { 0 }))
sourceRow[it] = maxValue
}
}
private fun merge(payload: ReplicatorPayload) {
val rowKeys2 = table.keys + payload.timeTable.table.keys
val columnKeys2 = (table.values.map { it.keys } + payload.timeTable.table.values.map { it.keys }).flatten()
rowKeys2.forEach { rowKey ->
columnKeys2.forEach { columnKey ->
val maxValue = max(get(rowKey, columnKey), payload.timeTable[rowKey, columnKey])
set(rowKey, columnKey, maxValue)
}
}
}
// Do not change or call. It's here for serialization/deserialization purposes.
private fun getTable() = table
}
| gpl-3.0 | 97688dbf1c7e78b88cbbb24cfb5e56fb | 38.746032 | 115 | 0.655751 | 4.187291 | false | false | false | false |
Setekh/Gleipnir-Graphics | src/main/kotlin/eu/corvus/corax/scene/assets/AssetManagerImpl.kt | 1 | 2919 | package eu.corvus.corax.scene.assets
import eu.corvus.corax.app.storage.StorageAccess
import eu.corvus.corax.graphics.material.textures.Texture
import eu.corvus.corax.graphics.material.textures.Texture2D_PC
import eu.corvus.corax.platforms.desktop.assets.loaders.AssimpLoader
import eu.corvus.corax.platforms.desktop.assets.loaders.TextureLoader
import eu.corvus.corax.scene.Object
import eu.corvus.corax.scene.Spatial
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey
import kotlin.properties.Delegates
class AssetManagerImpl(
private val storageAccess: StorageAccess
) : Object(), AssetManager {
private val loaders = mutableMapOf<String, AssetManager.AssetLoader>()
init {
addLoader("png", TextureLoader())
addLoader("jpg", TextureLoader())
addLoader("*", AssimpLoader())
}
override fun addLoader(suffix: String, assetLoader: AssetManager.AssetLoader) {
loaders[suffix] = assetLoader
}
override fun removeLoader(suffix: String) {
loaders.remove(suffix)
}
override suspend fun loadSpatial(assetName: String): Spatial = withContext(Dispatchers.IO) {
val suffix = assetName.substringAfterLast('.')
val assetLoader = loaders[suffix] ?: loaders["*"]!!
assetLoader.load(this@AssetManagerImpl, storageAccess, assetName) as Spatial
}
override suspend fun loadTexture(assetName: String): Texture = withContext(Dispatchers.IO) {
val suffix = assetName.substringAfterLast('.')
val assetLoader = loaders[suffix] ?: throw RuntimeException("Cannot find asset loader for $assetName")
assetLoader.load(this@AssetManagerImpl, storageAccess, assetName) as Texture2D_PC
}
override suspend fun loadRaw(assetPath: String): ByteArray = withContext(Dispatchers.IO) { // this is not cache-able
var data: ByteArray by Delegates.notNull()
storageAccess.readFrom(assetPath) {
data = it.readBytes()
}
data
}
override fun watch(assetPath: File, callback: () -> Unit): WatchKey {
val watchService = FileSystems.getDefault().newWatchService()
val pathToWatch = assetPath.toPath()
val pathKey = pathToWatch.register(watchService,
StandardWatchEventKinds.ENTRY_MODIFY)
while (true) {
val watchKey = watchService.take()
for (event in watchKey.pollEvents()) {
callback()
}
if (!watchKey.reset()) {
watchKey.cancel()
watchService.close()
break
}
}
return pathKey
}
override fun unload(assetName: String) {
}
override fun free() {
super.free()
loaders.clear()
}
}
| bsd-3-clause | 0766f8256d1c980cc07aac4016b7b6af | 30.053191 | 120 | 0.676259 | 4.761827 | false | false | false | false |
apixandru/intellij-community | plugins/copyright/testSrc/com/intellij/copyright/CopyrightManagerTest.kt | 2 | 2460 | // Copyright 2000-2017 JetBrains s.r.o.
// Use of this source code is governed by the Apache 2.0 license that can be
// found in the LICENSE file.
package com.intellij.copyright
import com.intellij.configurationStore.SchemeManagerFactoryBase
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.write
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class CopyrightManagerTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
@Test
fun loadSchemes() {
val schemeFile = fsRule.fs.getPath("copyright/openapi.xml")
val schemeData = """
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright 2000-&#36;today.year 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." />
<option name="keyword" value="Copyright" />
<option name="allowReplaceKeyword" value="JetBrains" />
<option name="myName" value="openapi" />
<option name="myLocal" value="true" />
</copyright>
</component>""".trimIndent()
schemeFile.write(schemeData)
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val profileManager = CopyrightManager(projectRule.project, schemeManagerFactory,
isSupportIprProjects = false /* otherwise scheme will be not loaded from our memory fs */)
profileManager.loadSchemes()
val copyrights = profileManager.getCopyrights()
assertThat(copyrights).hasSize(1)
val scheme = copyrights.first()
assertThat(scheme.schemeState).isEqualTo(null)
assertThat(scheme.name).isEqualTo("openapi")
}
} | apache-2.0 | 37ad679ec490a29672b725e373296bc1 | 47.254902 | 683 | 0.727236 | 4.581006 | false | true | false | false |
permissions-dispatcher/PermissionsDispatcher | ktx/src/test/java/permissions/dispatcher/test/PermissionRequestViewModelTest.kt | 1 | 3230 | package permissions.dispatcher.test
import android.Manifest
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import permissions.dispatcher.ktx.Fun
import permissions.dispatcher.ktx.PermissionRequestViewModel
import permissions.dispatcher.ktx.PermissionResult
import java.lang.ref.WeakReference
class PermissionRequestViewModelTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val permission = arrayOf(Manifest.permission.CAMERA).contentToString()
private lateinit var viewModel: PermissionRequestViewModel
private lateinit var lifecycleOwner: LifecycleOwner
private lateinit var requiresPermission: Fun
private lateinit var onPermissionDenied: Fun
private lateinit var onNeverAskAgain: Fun
@Before
fun setup() {
viewModel = PermissionRequestViewModel()
lifecycleOwner = mock()
val lifecycle = LifecycleRegistry(mock())
lifecycle.markState(Lifecycle.State.RESUMED)
whenever(lifecycleOwner.lifecycle).thenReturn(lifecycle)
onPermissionDenied = mock()
requiresPermission = mock()
onNeverAskAgain = mock()
}
@After
fun cleanup() {
viewModel.removeObservers(lifecycleOwner)
}
@Test
fun `GRANTED emits requiresPermission`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.GRANTED)
verify(requiresPermission).invoke()
verify(onPermissionDenied, never()).invoke()
verify(onNeverAskAgain, never()).invoke()
}
@Test
fun `DENIED emits onPermissionDenied`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.DENIED)
verify(requiresPermission, never()).invoke()
verify(onPermissionDenied).invoke()
verify(onNeverAskAgain, never()).invoke()
}
@Test
fun `DENIED_AND_DISABLED emits onNeverAskAgain`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.DENIED_AND_DISABLED)
verify(requiresPermission, never()).invoke()
verify(onPermissionDenied, never()).invoke()
verify(onNeverAskAgain).invoke()
}
}
| apache-2.0 | 81ecace8987e69c36e538a153feccd8b | 31.959184 | 95 | 0.713003 | 5.78853 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.